private BapPublisher createAndAddMockPublisher(final String hostConfigurationName) {
   final BapPublisher mockPublisher = mockControl.createMock(BapPublisher.class);
   if (hostConfigurationName != null) {
     mockPublisher.setEffectiveEnvironmentInBuildInfo(
         (AbstractBuild) EasyMock.anyObject(), (BPBuildInfo) EasyMock.anyObject());
     EasyMock.expect(mockPublisher.getConfigName()).andReturn(hostConfigurationName);
   }
   publishers.add(mockPublisher);
   return mockPublisher;
 }
  public void testFindAdverseEventReportingPeriods() {
    String userId = "tester";
    AdverseEventReportingPeriod rp = Fixtures.createReportingPeriod();
    ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
    Report report = Fixtures.createReport("test report");
    report.setStatus(ReportStatus.INPROCESS);
    report.setReviewStatus(ReviewStatus.DRAFT_INCOMPLETE);
    report.setWorkflowId(1);
    rp.addAeReport(aeReport);
    aeReport.addReport(report);

    List<AdverseEventReportingPeriod> reportingPeriods =
        new ArrayList<AdverseEventReportingPeriod>();
    reportingPeriods.add(rp);

    rp.setReviewStatus(ReviewStatus.DRAFT_INCOMPLETE);
    rp.setWorkflowId(1);

    AdverseEventReportingPeriodDTO rpDto = new AdverseEventReportingPeriodDTO();
    ExpeditedAdverseEventReportDTO rDto = new ExpeditedAdverseEventReportDTO();
    ReportDTO reportDto = new ReportDTO();
    rDto.addReportDTO(reportDto);
    List<String> possibleActions = new ArrayList<String>();
    possibleActions.add("abc");
    reportDto.setPossibleActions(possibleActions);
    EasyMock.expect(
            rpDao.findAdverseEventReportingPeriods(
                (AdverseEventReportingPeriodForReviewQuery) EasyMock.anyObject()))
        .andReturn(reportingPeriods);

    EasyMock.expect(factory.createAdverseEventEvalutionPeriodDTO(rp, userId, true))
        .andReturn(rpDto);
    EasyMock.expect(factory.createAdverseEventReportDTO(aeReport, userId)).andReturn(rDto);
    List rrList = new ArrayList<ReconciliationReport>();
    EasyMock.expect(
            reconciliationReportDao.search((ReconciliationReportQuery) EasyMock.anyObject()))
        .andReturn(rrList)
        .anyTimes();
    replayMocks();

    Participant participant = Fixtures.createParticipant("Joel", "biju");
    Study study = Fixtures.createStudy("Hello");
    Organization org = Fixtures.createOrganization("test org");
    ReviewStatus reviewStatus = null;
    ReportStatus reportStatus = null;

    List<AdverseEventReportingPeriodDTO> dtos =
        impl.findAdverseEventReportingPeriods(
            participant, study, org, reviewStatus, reportStatus, userId, true);

    verifyMocks();

    assertEquals(1, dtos.size());
    assertEquals(1, dtos.get(0).getAeReports().size());
  }
 private BapPublisher createLabeledPublisher(final String label, final boolean expectPerform)
     throws Exception {
   final BapPublisher mockPublisher = mockControl.createMock(BapPublisher.class);
   mockPublisher.setEffectiveEnvironmentInBuildInfo(
       (AbstractBuild) EasyMock.anyObject(), (BPBuildInfo) EasyMock.anyObject());
   expect(mockPublisher.getLabel()).andReturn(new PublisherLabel(label)).anyTimes();
   EasyMock.expect(mockPublisher.getConfigName())
       .andReturn(hostConfiguration.getName())
       .anyTimes();
   if (expectPerform) {
     mockPublisher.perform(hostConfiguration, buildInfo);
   }
   publishers.add(mockPublisher);
   return mockPublisher;
 }
  @Test
  public void testUnsafeAOFileNonExistent() throws Exception {
    expect(mockBeanFactory.getInstance(currentUser)).andReturn(mockI18nHelper).anyTimes();
    expect(mockPermissionManager.hasPermission(Permissions.SYSTEM_ADMIN, currentUser))
        .andReturn(true);
    expect(
            mockI18nHelper.getText(
                EasyMock.eq("admin.errors.could.not.find.file"), EasyMock.<String>anyObject()))
        .andReturn("File does not exist.");

    final File file = File.createTempFile("testUnsafeAOFileNonExistent", "txt");
    file.deleteOnExit();

    try {
      final DataImportParams params =
          new DataImportParams.Builder(null)
              .setUnsafeJiraBackup(file)
              .setUnsafeAOBackup(
                  new File("I.really.really.don't.exist.and.if.i.did.it.would.be.very.unlucky"))
              .build();
      executeTest(params, false, DataImportService.ImportError.NONE);
      fail("Calling doImport with invalid validation result should have thrown an exception!");
    } catch (IllegalStateException e) {
      // yay
    } finally {
      file.delete();
    }
  }
  @Test
  public void testPerformReturnsUnstableWhenNoHostConfigFound() throws Exception {
    final BapPublisher mockPublisher = createAndAddMockPublisher(null);
    mockPublisher.setEffectiveEnvironmentInBuildInfo(
        (AbstractBuild) EasyMock.anyObject(), (BPBuildInfo) EasyMock.anyObject());
    EasyMock.expect(mockPublisher.getConfigName()).andReturn(hostConfiguration.getName());

    Mockito.reset(mockHostConfigurationAccess);
    Mockito.when(mockHostConfigurationAccess.getConfiguration(hostConfiguration.getName()))
        .thenReturn(null);

    final BPInstanceConfig instanceConfig = createInstanceConfig(publishers, false, false, false);
    instanceConfig.setHostConfigurationAccess(mockHostConfigurationAccess);

    assertResult(Result.UNSTABLE, instanceConfig);
    Mockito.verify(mockHostConfigurationAccess).getConfiguration(hostConfiguration.getName());
  }
  @Test
  public void testExecuteBuildNumberTooOldInXml() throws Exception {
    expect(mockBeanFactory.getInstance(currentUser)).andReturn(mockI18nHelper).anyTimes();
    expect(mockI18nHelper.getText("data.import.parse.xml")).andReturn("Parsing XML");
    expect(
            mockI18nHelper.getText(
                EasyMock.eq("data.import.parse.progress"),
                EasyMock.<String>anyObject(),
                EasyMock.<String>anyObject()))
        .andReturn("Parsing progress");

    // called during validation!
    expect(mockPermissionManager.hasPermission(Permissions.SYSTEM_ADMIN, currentUser))
        .andReturn(true);

    // This is called during the first parse of the XML file.  At this stage nothing should have
    // been created yet!
    final MockGenericValue mockGv = new MockGenericValue("someentity");
    expect(mockOfBizDelegator.makeValue(EasyMock.<String>anyObject())).andReturn(mockGv).anyTimes();
    expect(mockAttachmentPathManager.getDefaultAttachmentPath())
        .andReturn(directories.get(0).getAbsolutePath())
        .anyTimes();
    expect(mockIndexPathManager.getDefaultIndexRootPath())
        .andReturn(directories.get(1).getAbsolutePath())
        .anyTimes();
    expect(
            mockLicenseStringFactory.create(
                EasyMock.<String>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn("");

    // after the first parse check the build number.
    expect(mockBuildUtilsInfo.getCurrentBuildNumber()).andStubReturn("400");
    expect(mockBuildUtilsInfo.getMinimumUpgradableBuildNumber()).andStubReturn("18");

    // after the first parse we also verify the license is good.
    expect(
            mockJiraLicenseService.validate(
                EasyMock.<I18nHelper>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn(mockValidationResult);
    expect(mockValidationResult.getLicenseVersion()).andStubReturn(2);
    expect(mockValidationResult.getErrorCollection()).andStubReturn(new SimpleErrorCollection());

    expect(
            mockExternalLinkUtil.getProperty(
                "external.link.jira.confluence.upgrade.guide.for.old.versions"))
        .andReturn("http://www.atlassian.com");

    expect(mockI18nHelper.getText("data.import.error.xml.too.old", "http://www.atlassian.com"))
        .andReturn("Data is too old visit http://www.atlassian.com/");

    final String filePath = getDataFilePath("jira-export-test-too-old.xml");
    final DataImportParams params = new DataImportParams.Builder(filePath).build();
    executeTest(params, false, DataImportService.ImportError.NONE);
  }
  @Test
  public void testExceptionsDealtWith() {
    final String testName = "test";

    final ConsumableTestDefinition testDefinition = new ConsumableTestDefinition();
    testDefinition.setConstants(Collections.<String, Object>emptyMap());
    testDefinition.setRule("${lang == 'en'}");

    testDefinition.setTestType(TestType.ANONYMOUS_USER);

    // most tests just set the salt to be the same as the test name
    testDefinition.setSalt(testName);
    testDefinition.setBuckets(Collections.<TestBucket>emptyList());

    final RuleEvaluator ruleEvaluator = EasyMock.createMock(RuleEvaluator.class);
    EasyMock.expect(
            ruleEvaluator.evaluateBooleanRule(
                EasyMock.<String>anyObject(), EasyMock.<Map<String, Object>>anyObject()))
        // throw an unexpected type of runtime exception
        .andThrow(new RuntimeException() {})
        // Must be evaluated, or this was not a valid test
        .once();
    EasyMock.replay(ruleEvaluator);

    final TestRangeSelector selector =
        new TestRangeSelector(ruleEvaluator, testName, testDefinition);

    // Ensure no exceptions thrown.
    final TestBucket bucket =
        new StandardTestChooser(selector)
            .choose("identifier", Collections.<String, Object>emptyMap());

    assertEquals("Expected no bucket to be found ", null, bucket);

    EasyMock.verify(ruleEvaluator);
  }
  @Test
  public void testVersion1License() throws Exception {
    expect(mockBeanFactory.getInstance(currentUser)).andReturn(mockI18nHelper).anyTimes();
    expect(mockI18nHelper.getText("data.import.parse.xml")).andReturn("Parsing XML");
    expect(
            mockI18nHelper.getText(
                EasyMock.eq("data.import.parse.progress"),
                EasyMock.<String>anyObject(),
                EasyMock.<String>anyObject()))
        .andReturn("Parsing progress");

    // called during validation!
    expect(mockPermissionManager.hasPermission(Permissions.SYSTEM_ADMIN, currentUser))
        .andReturn(true);
    expect(mockJiraLicenseService.validate(mockI18nHelper, "version1license"))
        .andReturn(mockValidationResult);
    expect(mockValidationResult.getLicenseVersion()).andReturn(1);
    expect(mockValidationResult.getErrorCollection()).andReturn(new SimpleErrorCollection());

    // This is called during the first parse of the XML file.  At this stage nothing should have
    // been created yet!
    final MockGenericValue mockGv = new MockGenericValue("someentity");
    expect(mockOfBizDelegator.makeValue(EasyMock.<String>anyObject())).andReturn(mockGv).anyTimes();
    expect(mockAttachmentPathManager.getDefaultAttachmentPath())
        .andReturn(directories.get(0).getAbsolutePath())
        .anyTimes();
    expect(mockIndexPathManager.getDefaultIndexRootPath())
        .andReturn(directories.get(1).getAbsolutePath())
        .anyTimes();
    expect(
            mockLicenseStringFactory.create(
                EasyMock.<String>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn("");

    // after the first parse check the build number.
    expect(mockBuildUtilsInfo.getCurrentBuildNumber()).andStubReturn("99999999");
    expect(mockBuildUtilsInfo.getMinimumUpgradableBuildNumber()).andStubReturn("0");

    // after the first parse we also verify the license is good.
    expect(
            mockJiraLicenseService.validate(
                EasyMock.<I18nHelper>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn(mockValidationResult);
    expect(mockValidationResult.getLicenseVersion()).andStubReturn(2);
    expect(mockValidationResult.getErrorCollection()).andStubReturn(new SimpleErrorCollection());

    final String filePath = getDataFilePath("jira-export-test.xml");
    final DataImportParams params =
        new DataImportParams.Builder(filePath).setLicenseString("version1license").build();
    executeTest(params, false, DataImportService.ImportError.V1_LICENSE_EXCEPTION);
  }
  @Test
  public void testFileNonExistent() throws Exception {
    expect(mockBeanFactory.getInstance(currentUser)).andReturn(mockI18nHelper).anyTimes();
    expect(mockPermissionManager.hasPermission(Permissions.SYSTEM_ADMIN, currentUser))
        .andReturn(true);
    expect(mockJiraHome.getImportDirectory()).andReturn(new File("somewhere")).anyTimes();
    expect(
            mockI18nHelper.getText(
                EasyMock.eq("admin.errors.could.not.find.file"), EasyMock.<String>anyObject()))
        .andReturn("File does not exist.");

    try {
      final DataImportParams params =
          new DataImportParams.Builder("idontexisthopefully.txt").build();
      executeTest(params, false, DataImportService.ImportError.NONE);
      fail("Calling doImport with invalid validation result should have thrown an exception!");
    } catch (IllegalStateException e) {
      // yay
    }
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    final FieldVisibilityManager visibilityBean = EasyMock.createMock(FieldVisibilityManager.class);
    EasyMock.expect(
            visibilityBean.isFieldHidden(
                (String) EasyMock.anyObject(), (Issue) EasyMock.anyObject()))
        .andReturn(false)
        .anyTimes();
    EasyMock.replay(visibilityBean);
    ManagerFactory.addService(FieldVisibilityManager.class, visibilityBean);

    originalFactory =
        ComponentManager.getComponentInstanceOfType(FieldClausePermissionChecker.Factory.class);
    ManagerFactory.addService(
        FieldClausePermissionChecker.Factory.class, new MockFieldClausePermissionFactory());
    bob = createMockUser("bob");

    final Group group = addUserToNewGroup(bob, "group");
    carl = createMockUser("carl");

    final GenericValue project =
        UtilsForTests.getTestEntity("Project", EasyMap.build("key", "TST"));

    final PermissionSchemeManager permissionSchemeManager =
        ManagerFactory.getPermissionSchemeManager();
    final GenericValue defaultScheme = permissionSchemeManager.createDefaultScheme();
    final SchemeEntity schemeEntity =
        new SchemeEntity(GroupDropdown.DESC, null, Permissions.BROWSE);
    permissionSchemeManager.createSchemeEntity(defaultScheme, schemeEntity);

    permissionSchemeManager.addSchemeToProject(project, defaultScheme);

    UtilsForTests.getTestEntity("Resolution", EasyMap.build("id", resolutionId));
    // Create two Issues with same comment but different level
    final GenericValue issue1 =
        UtilsForTests.getTestEntity(
            "Issue",
            EasyMap.build(
                "project",
                project.getLong("id"),
                "key",
                "TST-1",
                "resolution",
                resolutionId,
                "summary",
                SUMMARY_BODY));
    UtilsForTests.getTestEntity(
        "Action",
        EasyMap.build(
            "issue",
            issue1.getLong("id"),
            "type",
            ActionConstants.TYPE_COMMENT,
            "body",
            COMMENT_BODY));

    final GenericValue issue2 =
        UtilsForTests.getTestEntity(
            "Issue",
            EasyMap.build(
                "project",
                project.getLong("id"),
                "key",
                "TST-2",
                "resolution",
                resolutionId,
                "summary",
                SUMMARY_BODY));
    UtilsForTests.getTestEntity(
        "Action",
        EasyMap.build(
            "issue",
            issue2.getLong("id"),
            "type",
            ActionConstants.TYPE_COMMENT,
            "body",
            COMMENT_BODY,
            "level",
            group.getName()));

    final GenericValue issue3 =
        UtilsForTests.getTestEntity(
            "Issue",
            EasyMap.build(
                "project",
                project.getLong("id"),
                "key",
                "TST-3",
                "resolution",
                resolutionId,
                "summary",
                ANOTHER_SUMMARY_BODY));
    UtilsForTests.getTestEntity(
        "Action",
        EasyMap.build(
            "issue",
            issue3.getLong("id"),
            "type",
            ActionConstants.TYPE_COMMENT,
            "body",
            ANOTHER_COMMENT_BODY,
            "level",
            group.getName()));

    ManagerFactory.getIndexManager().reIndexAll();
  }
  @Test
  public void testExecuteBuildNumberMissing() throws Exception {
    expect(mockBarrier.await(20, TimeUnit.SECONDS)).andReturn(true);
    expect(mockBeanFactory.getInstance(currentUser)).andReturn(new MockI18nHelper()).anyTimes();

    // called during validation!
    expect(mockPermissionManager.hasPermission(Permissions.SYSTEM_ADMIN, currentUser))
        .andReturn(true);

    // This is called during the first parse of the XML file.  At this stage nothing should have
    // been created yet!
    final MockGenericValue mockGv = new MockGenericValue("someentity");
    expect(mockOfBizDelegator.makeValue(EasyMock.<String>anyObject())).andReturn(mockGv).anyTimes();
    expect(mockAttachmentPathManager.getDefaultAttachmentPath())
        .andReturn(directories.get(0).getAbsolutePath())
        .anyTimes();
    expect(mockIndexPathManager.getDefaultIndexRootPath())
        .andReturn(directories.get(1).getAbsolutePath())
        .anyTimes();
    expect(
            mockLicenseStringFactory.create(
                EasyMock.<String>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn("");

    // after the first parse check the build number.
    expect(mockBuildUtilsInfo.getCurrentBuildNumber()).andStubReturn("1");
    expect(mockBuildUtilsInfo.getMinimumUpgradableBuildNumber()).andStubReturn("0");

    // after the first parse we also verify the license is good.
    expect(
            mockJiraLicenseService.validate(
                EasyMock.<I18nHelper>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn(mockValidationResult);
    expect(mockValidationResult.getLicenseVersion()).andStubReturn(2);
    expect(mockValidationResult.getErrorCollection()).andStubReturn(new SimpleErrorCollection());

    // this gets called during shutdownAndFlushAsyncServices.  After parse and before the import.
    // This shuts down
    // the scheduler
    expect(mockScheduler.isShutdown()).andReturn(false);
    mockScheduler.shutdown();
    mockMailQueue.sendBuffer();
    expect(mockTaskManager.shutdownAndWait(5)).andReturn(true);

    // Expect AO to be cleared.
    backup.clear();

    // Once the import is running one of the first things to do is to clear out the old database
    // values.
    expect(mockOfBizDelegator.getModelReader()).andReturn(mockModelReader);
    expect(mockModelReader.getEntityNames())
        .andReturn(CollectionBuilder.<String>list("Issue", "User"));
    expect(mockModelReader.getModelEntity("Issue")).andReturn(new ModelEntity());
    expect(mockOfBizDelegator.removeByAnd("Issue", Collections.<String, Object>emptyMap()))
        .andReturn(10);
    expect(mockModelReader.getModelEntity("User")).andReturn(new ModelEntity());
    expect(mockOfBizDelegator.removeByAnd("User", Collections.<String, Object>emptyMap()))
        .andReturn(5);

    // then we go through and create all our GVs (already mocked out during the first parse above)

    // once everything's been imported need to refresh the ofbiz sequencer and check for data
    // consistency.
    mockOfBizDelegator.refreshSequencer();
    mockConsistencyChecker.checkDataConsistency();

    // after the consistency check lets do the upgrade
    expect(mockUpgradeManager.doUpgradeIfNeededAndAllowed(null))
        .andReturn(Collections.<String>emptyList());

    // now do a reindex
    mockIndexManager.deactivate();
    expect(mockIndexManager.size()).andReturn(5);
    expect(mockIndexManager.activate((Context) notNull())).andReturn(1L);

    // raise the JiraStartedEvent
    mockPluginEventManager.broadcast(EasyMock.<JiraStartedEvent>anyObject());

    // finally we can restart the scheduler!
    expect(
            mockScheduler.scheduleJob(
                EasyMock.<JobDetail>anyObject(), EasyMock.<Trigger>anyObject()))
        .andReturn(new Date())
        .anyTimes();
    mockScheduler.start();

    final String filePath = getDataFilePath("jira-export-test-no-build-number.xml");
    final DataImportParams params = new DataImportParams.Builder(filePath).build();

    // Finally everything's mocked out.  Run the import!
    executeTest(params, true, DataImportService.ImportError.NONE);

    // create() should have been called on our GVs
    assertTrue(mockGv.isCreated());
    // the world should have been rebuilt!
    assertTrue(((MockDataImportDependencies) mockDependencies).globalRefreshCalled);
  }