target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void failedAnalysisWhenScmSystemIsNotAvailable() { ScmAvailabilityCheckerService notAvailableScmSystem = mock(ScmAvailabilityCheckerService.class); when(notAvailableScmSystem.isAvailable(any(ScmConnectionSettings.class))).thenReturn(false); ScmAvailabilityCheckerServiceFactory notAvailableCheckerServiceFactory = mock(ScmAvailabilityCheckerServiceFactory.class); when(notAvailableCheckerServiceFactory.create(any(ScmConnectionSettings.class))).thenReturn(notAvailableScmSystem); ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Collections.<ViolationOccurence>emptyList())); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, notAvailableCheckerServiceFactory, mock(CodeChangeProbabilityCalculatorFactory.class), secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThat(analysis.isSuccessful()).isFalse(); } | @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } |
@Test public void failedAnalysisWhenProblemWithCodeChurnCalculationOccurred() throws CodeChurnCalculationException, ScmConnectionEncodingException { QualityAnalyzerService qualityAnalyzerService = createMockedSystemThatThrowsExceptionInCodeChangeCalculation(CodeChurnCalculationException.class); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThat(analysis.isSuccessful()).isFalse(); } | @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } |
@Test public void failedAnalysisWhenProblemWithScmConnectionEncodingOccurred() throws CodeChurnCalculationException, ScmConnectionEncodingException { QualityAnalyzerService qualityAnalyzerService = createMockedSystemThatThrowsExceptionInCodeChangeCalculation(ScmConnectionEncodingException.class); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThat(analysis.isSuccessful()).isFalse(); } | @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } |
@Test public void failedAnalysisWhenCostCalculatorThrowsResourceNotFoundExceptionOnRemediationCosts() throws CodeChurnCalculationException, ScmConnectionEncodingException, ResourceNotFoundException { ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Arrays.asList(new ViolationOccurence(firstRequirement, new Artefact("A", "A"), 0)))); CodeChangeProbabilityCalculator codeChangeProbabilityCalculator = mock(CodeChangeProbabilityCalculator.class); when(codeChangeProbabilityCalculator.calculateCodeChangeProbability(any(ScmConnectionSettings.class), anyString())).thenReturn(1.0); CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory = createMockedCodeChangeProbabilityCalculatorFactory(); when(codeChangeProbabilityCalculatorFactory.create(any(CodeChangeSettings.class))).thenReturn(codeChangeProbabilityCalculator); when(costsCalculator.calculateRemediationCosts(any(SonarConnectionSettings.class), any(ViolationOccurence.class))).thenThrow(ResourceNotFoundException.class); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, scmAvailabilityCheckerServiceFactory, codeChangeProbabilityCalculatorFactory, secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThat(analysis.isSuccessful()).isFalse(); } | @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } |
@Test public void failedAnalysisWhenCostCalculatorThrowsResourceNotFoundExceptionOnNonRemediationCosts() throws CodeChurnCalculationException, ScmConnectionEncodingException, ResourceNotFoundException { ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Arrays.asList(new ViolationOccurence(firstRequirement, new Artefact("A", "A"), 0)))); CodeChangeProbabilityCalculator codeChangeProbabilityCalculator = mock(CodeChangeProbabilityCalculator.class); when(codeChangeProbabilityCalculator.calculateCodeChangeProbability(any(ScmConnectionSettings.class), anyString())).thenReturn(1.0); CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory = createMockedCodeChangeProbabilityCalculatorFactory(); when(codeChangeProbabilityCalculatorFactory.create(any(CodeChangeSettings.class))).thenReturn(codeChangeProbabilityCalculator); when(costsCalculator.calculateNonRemediationCosts(any(SonarConnectionSettings.class), any(ViolationOccurence.class))).thenThrow(ResourceNotFoundException.class); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, scmAvailabilityCheckerServiceFactory, codeChangeProbabilityCalculatorFactory, secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThat(analysis.isSuccessful()).isFalse(); } | @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } | DefaultQualityAnalyzerService implements QualityAnalyzerService { @Override public QualityAnalysis analyzeProject(Project project) { try { ViolationsAnalysisResult violationsAnalysisResult = violationsCalculatorService.calculateAllViolation(project); if (!violationsAnalysisResult.isSuccessful()) { log.error("Quality analysis for project {} failed due '{}'", project.getName(), violationsAnalysisResult.getFailureReason().get()); return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), violationsAnalysisResult.getFailureReason().get())); } log.info("Checking the availability of the SCM system {} for project {}", project.getScmSettings(), project.getName()); if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { return qualityAnalysisRepository.save(QualityAnalysis.failed(project, zeroCostsForEachViolation(violationsAnalysisResult), "The scm system is not available.")); } QualityAnalysis qualityAnalysis = addChangeProbabilityToEachArtifact(project, violationsAnalysisResult); if (!qualityAnalysis.isSuccessful()) { return qualityAnalysisRepository.save(qualityAnalysis); } qualityAnalysis = addSecureChangeProbabilityToEachArtifact(project, qualityAnalysis); log.info("Quality analysis succeeded for project {} with {} violations.", project.getName(), violationsAnalysisResult.getViolations().size()); return qualityAnalysisRepository.save(qualityAnalysis); } catch (Exception e) { String errorMessage = "Unexpected error occured during quality analysis!"; log.error(errorMessage, e); return QualityAnalysis.failed(project, new ArrayList<QualityViolation>(), errorMessage); } } @Autowired DefaultQualityAnalyzerService(ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator,
QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); @Override QualityAnalysis analyzeProject(Project project); } |
@Test public void createCalculatorForDefaultSetting() { assertThat(codeChangeProbabilityCalculatorFactory.create(CodeChangeSettings.defaultSetting(0))) .isInstanceOf(DefaultCodeChangeProbabilityCalculator.class); } | CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } |
@Test public void createCalculatorWithCorrectNumberOfDaysForDefaultSetting() { assertThat(((DefaultCodeChangeProbabilityCalculator) codeChangeProbabilityCalculatorFactory.create(CodeChangeSettings.defaultSetting(30))).getDays()) .isEqualTo(30); } | CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } |
@Test public void createCalculatorForWeightedSetting() { assertThat(codeChangeProbabilityCalculatorFactory.create(CodeChangeSettings.weightedSetting(0))) .isInstanceOf(WeightedCodeChangeProbabilityCalculator.class); } | CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } |
@Test public void containsAllQualityViolationsSortedByProfitAndRemediationCosts() { QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 80); QualityInvestmentPlanEntry[] investments = qualityInvestmentPlan.getEntries().toArray(new QualityInvestmentPlanEntry[0]); assertThat(investments).hasSize(3); assertThat(investments[0].getArtefactLongName()).isEqualTo("C"); assertThat(investments[1].getArtefactLongName()).isEqualTo("org.A"); assertThat(investments[2].getArtefactLongName()).isEqualTo("org.project.B"); } | public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } |
@Test public void createCalculatorWithCorrectNumberOfDaysForWeightedSetting() { assertThat(((WeightedCodeChangeProbabilityCalculator) codeChangeProbabilityCalculatorFactory.create(CodeChangeSettings.weightedSetting(30))).getDays()) .isEqualTo(30); } | CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } | CodeChangeProbabilityCalculatorFactory { CodeChangeProbabilityCalculator create(CodeChangeSettings codeChangeSettings) { if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.WEIGHTED.getId()) { return new WeightedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } else if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { return new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, codeChangeSettings.getNumberOfCommits()); } else { return new DefaultCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, LocalDate.now(), codeChangeSettings.getDays()); } } @Autowired CodeChangeProbabilityCalculatorFactory(CodeChurnCalculatorFactory codeChurnCalculatorFactory); } |
@Test public void profileWithNoChangeRiskAssessmentFunctions() throws ResourceNotFoundException { assertThat(secureChangeProbabilityCalculator.calculateSecureChangeProbability( profile, mock(SonarConnectionSettings.class), mock(Artefact.class))).isEqualTo(1.0); } | public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact); } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact); } |
@Test public void profileWithOneChangeRiskAssessmentFunction() throws ResourceNotFoundException { metricCollectorService.addMetricValue("A", "metric", 9.0); profile.addChangeRiskAssessmentFunction(new ChangeRiskAssessmentFunction(profile, "metric", Sets.newHashSet(new RiskCharge(0.2, "<", 10.0)))); assertThat(secureChangeProbabilityCalculator.calculateSecureChangeProbability( profile, mock(SonarConnectionSettings.class), artefact)).isEqualTo(1.2); } | public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact); } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact); } |
@Test public void profileWithManyChangeRiskAssessmentFunctions() throws ResourceNotFoundException { metricCollectorService.addMetricValue("A", "metric1", 9.0); metricCollectorService.addMetricValue("A", "metric2", -1.0); metricCollectorService.addMetricValue("A", "metric3", 0.0); profile.addChangeRiskAssessmentFunction(new ChangeRiskAssessmentFunction(profile, "metric1", Sets.newHashSet(new RiskCharge(0.2, "<", 10.0)))); profile.addChangeRiskAssessmentFunction(new ChangeRiskAssessmentFunction(profile, "metric2", Sets.newHashSet(new RiskCharge(0.11, ">", -2.0)))); profile.addChangeRiskAssessmentFunction(new ChangeRiskAssessmentFunction(profile, "metric3", Sets.newHashSet(new RiskCharge(0.005, ">=", 0.0)))); assertThat(secureChangeProbabilityCalculator.calculateSecureChangeProbability( profile, mock(SonarConnectionSettings.class), artefact)).isEqualTo(1.315); } | public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact); } | SecureChangeProbabilityCalculator { public double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact) throws ResourceNotFoundException { log.info("Calculate secure change probability for artefact {}", artefact.getName()); double secureChangeProbability = 1.0; for (ChangeRiskAssessmentFunction riskAssessmentFunction : qualityProfile.getChangeRiskAssessmentFunctions()) { final double metricValueForArtefact = metricCollectorService.collectMetricForResource(sonarConnectionSettings, artefact.getSonarIdentifier(), riskAssessmentFunction.getMetricIdentifier()); secureChangeProbability += riskAssessmentFunction.getRiskChargeAmount(metricValueForArtefact); } return secureChangeProbability; } @Autowired SecureChangeProbabilityCalculator(MetricCollectorService metricCollectorService); double calculateSecureChangeProbability(QualityProfile qualityProfile, SonarConnectionSettings sonarConnectionSettings, Artefact artefact); } |
@Test public void retrieveProjectWithRepositoryFromDatabaseAndTriggerAnalysisAfterwards() { analyzerRunnable.run(); InOrder inOrder = inOrder(projectRepository, analyzerService); inOrder.verify(projectRepository).findOne(1L); inOrder.verify(analyzerService).analyzeProject(project); inOrder.verifyNoMoreInteractions(); } | @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } |
@Test public void markProjectAsHadAnalysis() { analyzerRunnable.run(); verify(project).setHadAnalysis(true); } | @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } |
@Test public void executedProjectShouldBeSavedToDatabaseAfterMarkedAsHadAnalysis() { analyzerRunnable.run(); InOrder inOrder = inOrder(project, projectRepository); inOrder.verify(project).setHadAnalysis(true); inOrder.verify(projectRepository).save(project); } | @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } |
@Test public void notFailWhenProjectIsNotRetrievableViaRepository() { when(projectRepository.findOne(1L)).thenReturn(null); analyzerRunnable.run(); } | @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } | AnalyzerRunnable implements Runnable { @Override public void run() { Project project = projectRepository.findOne(projectId); if (project != null) { project.setHadAnalysis(true); projectRepository.save(project); log.info("Start analyzer run for project {}", project.getName()); qualityAnalyzerService.analyzeProject(project); log.info("Finished analyzer run for project {}", project.getName()); } else { log.error("Could not find project with id " + projectId + " for starting an analyzer run!"); } } AnalyzerRunnable(Project project, ProjectRepository projectRepository, QualityAnalyzerService qualityAnalyzerService); @Override void run(); } |
@Test public void failedViolationAnalysisResultWhenSonarProjectIsNotReachable() { SonarConnectionSettings connectionSettings = new SonarConnectionSettings(defaultSonarHost, "abc"); Project project = mock(Project.class); when(project.getSonarConnectionSettings()).thenReturn(connectionSettings); SonarConnectionCheckerService connectionCheckerService = mock(SonarConnectionCheckerService.class); when(connectionCheckerService.isReachable(any(SonarConnectionSettings.class))).thenReturn(false); ViolationsCalculatorService violationsCalculatorService = new ViolationsCalculatorService(connectionCheckerService, new ResourcesCollectorService(), new MetricCollectorService()); assertThat(violationsCalculatorService.calculateAllViolation(project).isSuccessful()).isFalse(); } | ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } |
@Test public void failedViolationAnalysisResultWhenOneMetricValueIsNotReachable() throws ResourceNotFoundException { Resource dummyResource = new Resource(); ResourcesCollectorService resourcesCollectorService = mock(ResourcesCollectorService.class); when(resourcesCollectorService.collectAllResourcesForProject(any(SonarConnectionSettings.class))) .thenReturn(Arrays.asList(dummyResource)); MetricCollectorService metricCollectorService = mock(MetricCollectorService.class); when(metricCollectorService.collectMetricForResource(any(SonarConnectionSettings.class), anyString(), anyString())) .thenThrow(ResourceNotFoundException.class); ViolationsCalculatorService violationsCalculatorService = new ViolationsCalculatorService(connectionCheckerService, resourcesCollectorService, metricCollectorService); assertThat(violationsCalculatorService.calculateAllViolation(project).isSuccessful()).isFalse(); } | ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } |
@Test public void shouldOnlyConsiderArtefactThatStartWithBasePackageName() { QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "org.project", 80); assertThat(qualityInvestmentPlan.getEntries()).hasSize(1); assertThat(qualityInvestmentPlan.getEntries().iterator().next().getArtefactLongName()).isEqualTo("org.project.B"); } | public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } |
@Test public void noViolationsWhenNoRequirementsAreViolated() { FakeResourcesCollectorService resourcesCollectorService = new FakeResourcesCollectorService(); resourcesCollectorService.addResource("A"); resourcesCollectorService.addResource("B"); FakeMetricCollectorService metricCollectorService = new FakeMetricCollectorService(); metricCollectorService.addMetricValue("A", "cc", 11.0); metricCollectorService.addMetricValue("A", "ec", 14.0); metricCollectorService.addMetricValue("A", "nloc", 1.0); metricCollectorService.addMetricValue("B", "cc", 20.0); metricCollectorService.addMetricValue("B", "ec", 2.0); metricCollectorService.addMetricValue("B", "nloc", 1.0); ViolationsCalculatorService violationsCalculatorService = new ViolationsCalculatorService(connectionCheckerService, resourcesCollectorService, metricCollectorService); ViolationsAnalysisResult analysisResult = violationsCalculatorService.calculateAllViolation(project); assertThat(analysisResult.isSuccessful()).isTrue(); assertThat(analysisResult.getViolations()).isEmpty(); } | ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } |
@Test public void violationsWhenRequirementsAreViolatedInOneArtefact() { FakeResourcesCollectorService resourcesCollectorService = new FakeResourcesCollectorService(); resourcesCollectorService.addResource("A"); resourcesCollectorService.addResource("B"); FakeMetricCollectorService metricCollectorService = new FakeMetricCollectorService(); metricCollectorService.addMetricValue("A", "cc", 11.0); metricCollectorService.addMetricValue("A", "ec", 14.0); metricCollectorService.addMetricValue("A", "nloc", 5.0); metricCollectorService.addMetricValue("B", "cc", 10.0); metricCollectorService.addMetricValue("B", "ec", 15.0); metricCollectorService.addMetricValue("B", "nloc", 50.0); ViolationsCalculatorService violationsCalculatorService = new ViolationsCalculatorService(connectionCheckerService, resourcesCollectorService, metricCollectorService); ViolationsAnalysisResult analysisResult = violationsCalculatorService.calculateAllViolation(project); assertThat(analysisResult.isSuccessful()).isTrue(); assertThat(analysisResult.getViolations()).containsOnly( new ViolationOccurence(firstRequirement, new Artefact("B", "B"), 50.0), new ViolationOccurence(secondRequirement, new Artefact("B", "B"), 50.0) ); } | ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } |
@Test public void violationsWhenRequirementsAreViolatedInManyArtefact() { FakeResourcesCollectorService resourcesCollectorService = new FakeResourcesCollectorService(); resourcesCollectorService.addResource("A"); resourcesCollectorService.addResource("B"); resourcesCollectorService.addResource("C"); FakeMetricCollectorService metricCollectorService = new FakeMetricCollectorService(); metricCollectorService.addMetricValue("A", "cc", 9.0); metricCollectorService.addMetricValue("A", "ec", 20.0); metricCollectorService.addMetricValue("A", "nloc", 10.0); metricCollectorService.addMetricValue("B", "cc", 10.0); metricCollectorService.addMetricValue("B", "ec", 15.0); metricCollectorService.addMetricValue("B", "nloc", 5.0); metricCollectorService.addMetricValue("C", "cc", 11.0); metricCollectorService.addMetricValue("C", "ec", 14.0); metricCollectorService.addMetricValue("C", "nloc", 21.0); ViolationsCalculatorService violationsCalculatorService = new ViolationsCalculatorService(connectionCheckerService, resourcesCollectorService, metricCollectorService); ViolationsAnalysisResult analysisResult = violationsCalculatorService.calculateAllViolation(project); assertThat(analysisResult.isSuccessful()).isTrue(); assertThat(analysisResult.getViolations()).containsOnly( new ViolationOccurence(firstRequirement, new Artefact("A", "A"), 10.0), new ViolationOccurence(secondRequirement, new Artefact("A", "A"), 10.0), new ViolationOccurence(firstRequirement, new Artefact("B", "B"), 5.0), new ViolationOccurence(secondRequirement, new Artefact("B", "B"), 5.0) ); } | ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } | ViolationsCalculatorService { ViolationsAnalysisResult calculateAllViolation(Project project) { if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { return ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "sonar project is not reachable with supplied connection settings: " + project.getSonarConnectionSettings().toString()); } log.info("Start violation analysis for project {}", project.getName()); Map<String, Artefact> artefactsThatHaveAtLeastOneViolation = Maps.newHashMap(); List<ViolationOccurence> violations = new ArrayList<ViolationOccurence>(); long violationsOfCurrentArtefact = 0; for (Resource resource : resourcesCollectorService.collectAllResourcesForProject(project.getSonarConnectionSettings())) { log.info("Analyzing resource {}", resource.getLongName()); violationsOfCurrentArtefact = 0; for (QualityRequirement qualityRequirement : project.getProfile().getRequirements()) { final double weightingMetricValue; final double metricValue; try { weightingMetricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getWeightingMetricIdentifier()); metricValue = metricCollectorService.collectMetricForResource(project.getSonarConnectionSettings(), resource.getKey(), qualityRequirement.getCriteria().getMetricIdentifier()); } catch (ResourceNotFoundException e) { log.warn("Quality analysis run failed due one resource or metric could not be find in Sonar!", e); return ViolationsAnalysisResult.createFailedAnalysis(violations, "resource " + resource.getKey() + " or metric " + qualityRequirement.getCriteria().getMetricIdentifier() + " not available on Sonar"); } if (qualityRequirement.isViolated(metricValue)) { final Artefact artefact; if (artefactsThatHaveAtLeastOneViolation.containsKey(resource.getKey())) { artefact = artefactsThatHaveAtLeastOneViolation.get(resource.getKey()); } else { artefact = new Artefact(resource.getLongName(), resource.getKey()); artefactsThatHaveAtLeastOneViolation.put(resource.getKey(), artefact); } log.debug("Create quality violation for artefact {} with violated requirement {}", artefact.getName(), qualityRequirement.getCriteria()); violations.add(new ViolationOccurence(qualityRequirement, artefact, weightingMetricValue)); violationsOfCurrentArtefact++; } } log.info("Found {} violations at resource {}", violationsOfCurrentArtefact, resource.getLongName()); } log.info("Successfully analysed project {} and found {} quality violations in {} artefacts", project.getName(), violations.size(), artefactsThatHaveAtLeastOneViolation.size()); return ViolationsAnalysisResult.createSuccessfulAnalysis(violations); } @Autowired ViolationsCalculatorService(SonarConnectionCheckerService sonarConnectionCheckerService,
ResourcesCollectorService resourcesCollectorService,
MetricCollectorService metricCollectorService); } |
@Test public void scheduleProjectForAnalysis() { assertThat(analyzerScheduler.scheduleAnalyzer(project)).isTrue(); } | public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } |
@Test public void failToScheduleProjectTwice() { analyzerScheduler.scheduleAnalyzer(project); assertThat(analyzerScheduler.scheduleAnalyzer(project)).isFalse(); } | public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } |
@Test public void executedProjectShouldBeMarkedAsHadAnalysis() { analyzerScheduler.executeAnalyzer(project); assertThat(project.hadAnalysis()).isTrue(); } | public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } |
@Test public void scheduledProjectShouldNotBeMarkedAsHadAnalysis() { analyzerScheduler.scheduleAnalyzer(project); assertThat(project.hadAnalysis()).isFalse(); } | public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public boolean scheduleAnalyzer(Project project) { if (alreadyScheduledProjects.contains(project)) { log.info("Project {} is already scheduled!", project.getName()); return false; } alreadyScheduledProjects.add(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.schedule(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService), new CronTrigger(project.getCronExpression())); log.info("Scheduled analyzer job for project {} with cron expression {}", project.getName(), project.getCronExpression()); return true; } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } |
@Test public void executedProjectShouldBeSavedToDatabaseAfterMarkedAsHadAnalysis() { analyzerScheduler.executeAnalyzer(project); InOrder inOrder = inOrder(project, projectRepository); inOrder.verify(project).setHadAnalysis(true); inOrder.verify(projectRepository).save(project); } | public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } | DefaultQualityAnalyzerScheduler implements QualityAnalyzerScheduler { public void executeAnalyzer(Project project) { project.setHadAnalysis(true); projectRepository.save(project); QualityAnalyzerService qualityAnalyzerService = createDefaultQualityAnalyzer(); scheduler.execute(new AnalyzerRunnable(project, projectRepository, qualityAnalyzerService)); log.info("Executing analyzer job for project {}", project.getName()); } @Autowired DefaultQualityAnalyzerScheduler(ProjectRepository projectRepository,
ViolationsCalculatorService violationsCalculatorService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory,
CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory,
SecureChangeProbabilityCalculator secureChangeProbabilityCalculator, QualityViolationCostsCalculator costsCalculator,
QualityAnalysisRepository qualityAnalysisRepository); void executeAnalyzer(Project project); boolean scheduleAnalyzer(Project project); } |
@Test public void calculateRemediationCostsProperlyForGreaterOperator() throws ResourceNotFoundException { QualityRequirement requirement = new QualityRequirement(qualityProfile, 20, 30, 100, "nloc", new QualityCriteria("metric", ">", 10.0)); ViolationOccurence violation = new ViolationOccurence(requirement, artefact, 0); assertThat(costsCalculator.calculateRemediationCosts(connectionSettings, violation)).isEqualTo(216); } | public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); } |
@Test public void calculateRemediationCostsProperlyForLessOperator() throws ResourceNotFoundException { QualityRequirement requirement = new QualityRequirement(qualityProfile, 20, 30, 100, "nloc", new QualityCriteria("metric", "<", 1.0)); ViolationOccurence violation = new ViolationOccurence(requirement, artefact, 0); assertThat(costsCalculator.calculateRemediationCosts(connectionSettings, violation)).isEqualTo(48); } | public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); } | QualityViolationCostsCalculator { public int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); } |
@Test public void shouldChooseViolationsWithMoreProfit() { QualityViolation violation1 = new QualityViolation(new Artefact("org.A", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cc", "<", 5.0)), 50, 0, 0.0, "ncloc"); QualityViolation violation2 = new QualityViolation(new Artefact("org.project.B", ""), createRequirementOnlyWithCriteria(new QualityCriteria("rfc", "<=", 50.0)), 50, 0, 0.0, "ncloc"); QualityViolation violation3 = new QualityViolation(new Artefact("C", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cov", ">", 80.0)), 10, 0, 0.0, "ncloc"); analysis = QualityAnalysis.success(null, Arrays.asList(violation1, violation2, violation3)); QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 50); assertThat(qualityInvestmentPlan.getEntries()).hasSize(1); assertThat(qualityInvestmentPlan.getEntries().iterator().next().getArtefactLongName()).isEqualTo("C"); } | public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } |
@Test public void calculateNonRemediationCostsProperlyForGreaterEqualsOperator() throws ResourceNotFoundException { QualityRequirement requirement = new QualityRequirement(qualityProfile, 20, 30, 100, "nloc", new QualityCriteria("metric", ">=", 5.0)); ViolationOccurence violation = new ViolationOccurence(requirement, artefact, 0); assertThat(costsCalculator.calculateNonRemediationCosts(connectionSettings, violation)).isEqualTo(108); } | public int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating non-remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getNonRemediationCosts()); } | QualityViolationCostsCalculator { public int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating non-remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getNonRemediationCosts()); } } | QualityViolationCostsCalculator { public int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating non-remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getNonRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); } | QualityViolationCostsCalculator { public int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating non-remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getNonRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); } | QualityViolationCostsCalculator { public int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation) throws ResourceNotFoundException { log.info("Calculating non-remediation costs for {} with violated criteria {}", violation.getArtefact().getName(), violation.getRequirement().getCriteria()); return calculateCosts(sonarConnectionSettings, violation, violation.getRequirement().getNonRemediationCosts()); } @Autowired QualityViolationCostsCalculator(MetricCollectorService metricCollectorService); int calculateRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); int calculateNonRemediationCosts(SonarConnectionSettings sonarConnectionSettings, ViolationOccurence violation); } |
@Test public void shouldConvertPackageNameToFilenameProperly() { assertThat(new Artefact("org.my.class.AbcDe", "").getFilename()).isEqualTo("org/my/class/AbcDe.java"); } | public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } |
@Test public void shouldConvertClassNameToFilenameProperly() { assertThat(new Artefact("AbcDe", "").getFilename()).isEqualTo("AbcDe.java"); } | public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } |
@Test public void shouldConvertEmptyPackageNameToFilenameProperly() { assertThat(new Artefact("", "").getFilename()).isEqualTo(""); } | public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } | Artefact implements Serializable { public String getFilename() { if (name.isEmpty()) { return ""; } return name.replace('.', '/') + ".java"; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } |
@Test public void shouldConvertFullyQualifiedClassNameToShortClassName() { assertThat(new Artefact("org.util.MyClass", "").getShortClassName()).isEqualTo("MyClass"); } | public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } |
@Test public void shouldConvertFullyQualifiedClassNameWithoutPackagesToShortClassName() { assertThat(new Artefact("Class123", "").getShortClassName()).isEqualTo("Class123"); } | public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } |
@Test public void shouldConvertEmptyFullyQualifiedClassNameToShortClassName() { assertThat(new Artefact("", "").getShortClassName()).isEqualTo(""); } | public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } | Artefact implements Serializable { public String getShortClassName() { String className = null; for (String packageName : Splitter.on('.').split(name)) { className = packageName; } return className; } protected Artefact(); Artefact(String name, String sonarIdentifier); String getFilename(); String getShortClassName(); boolean hasManualEstimate(); } |
@Test public void scheduleAllProjects() { analyzerRunsSchedulerOnStartup.onApplicationEvent(null); verify(analyzerScheduler).scheduleAnalyzer(projectA); verify(analyzerScheduler).scheduleAnalyzer(projectB); verify(analyzerScheduler).scheduleAnalyzer(projectC); } | @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } @Autowired QualityAnalyzerRunsSchedulerOnStartup(QualityAnalyzerScheduler analyzerScheduler, ProjectRepository projectRepository); } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } @Autowired QualityAnalyzerRunsSchedulerOnStartup(QualityAnalyzerScheduler analyzerScheduler, ProjectRepository projectRepository); @Override void onApplicationEvent(ContextRefreshedEvent event); } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } @Autowired QualityAnalyzerRunsSchedulerOnStartup(QualityAnalyzerScheduler analyzerScheduler, ProjectRepository projectRepository); @Override void onApplicationEvent(ContextRefreshedEvent event); } |
@Test public void preventSchedulingProjectsTwice() { analyzerRunsSchedulerOnStartup.onApplicationEvent(null); analyzerRunsSchedulerOnStartup.onApplicationEvent(null); verify(analyzerScheduler, times(1)).scheduleAnalyzer(projectA); verify(analyzerScheduler, times(1)).scheduleAnalyzer(projectB); verify(analyzerScheduler, times(1)).scheduleAnalyzer(projectC); } | @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } @Autowired QualityAnalyzerRunsSchedulerOnStartup(QualityAnalyzerScheduler analyzerScheduler, ProjectRepository projectRepository); } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } @Autowired QualityAnalyzerRunsSchedulerOnStartup(QualityAnalyzerScheduler analyzerScheduler, ProjectRepository projectRepository); @Override void onApplicationEvent(ContextRefreshedEvent event); } | QualityAnalyzerRunsSchedulerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadyExecuted.compareAndSet(false, true)) { List<Project> projects = projectRepository.findAll(); log.info("Schedule analyzer jobs for {} projects", projects.size()); for (Project project : projects) { analyzerScheduler.scheduleAnalyzer(project); } } else { log.info("Projects already scheduled."); } } @Autowired QualityAnalyzerRunsSchedulerOnStartup(QualityAnalyzerScheduler analyzerScheduler, ProjectRepository projectRepository); @Override void onApplicationEvent(ContextRefreshedEvent event); } |
@Test public void shouldSupportSonarServerType() { assertThat(validator.supports(SonarServer.class)).isTrue(); } | @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldChooseViolationWithBiggerRoiWhenProfitIsTheSame() { QualityViolation violationWithSmallerRoi = new QualityViolation(new Artefact("org.A", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cc", "<", 5.0)), 50, 0, 0.0, "ncloc"); QualityViolation violationWithBiggerRoi = new QualityViolation(new Artefact("B", ""), createRequirementOnlyWithCriteria(new QualityCriteria("rfc", "<=", 50.0)), 40, 0, 0.0, "ncloc"); analysis = QualityAnalysis.success(null, Arrays.asList(violationWithSmallerRoi, violationWithBiggerRoi)); when(profitCalculator.calculateProfit(violationWithSmallerRoi)).thenReturn(100.0); when(profitCalculator.calculateProfit(violationWithBiggerRoi)).thenReturn(100.0); QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 50); assertThat(qualityInvestmentPlan.getEntries()).hasSize(1); assertThat(qualityInvestmentPlan.getEntries().iterator().next().getArtefactLongName()).isEqualTo("B"); } | public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } |
@Test public void shouldNotSupportOtherTypeThanSonarServer() { assertThat(validator.supports(Object.class)).isFalse(); } | @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | SonarServerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarServer.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void filterCorrectNumberOfBestRois() { Map<String, Integer> roiByArtefact = Maps.newHashMap(); roiByArtefact.put("A", 10); roiByArtefact.put("B", 10); roiByArtefact.put("C", 10); List<RoiDistribution> roiDistribution = Arrays.asList(new RoiDistribution(0, roiByArtefact)); assertThat(roiDistributionFilter.filterHighestRoi(roiDistribution, 2).iterator().next().getRoiByArtefact().keySet()).containsOnly("A", "B"); } | Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } |
@Test public void notFailWhenNumberOfArtefactsToFilterIsBiggerThanActualArtefacts() { Map<String, Integer> roiByArtefact = Maps.newHashMap(); roiByArtefact.put("A", 10); List<RoiDistribution> roiDistribution = Arrays.asList(new RoiDistribution(0, roiByArtefact)); assertThat(roiDistributionFilter.filterHighestRoi(roiDistribution, 2).iterator().next().getRoiByArtefact().keySet()).containsOnly("A"); } | Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } |
@Test public void filterBestRoisFromOneDistribution() { Map<String, Integer> roiByArtefact = Maps.newHashMap(); roiByArtefact.put("A", 10); roiByArtefact.put("B", 11); roiByArtefact.put("C", 9); roiByArtefact.put("D", 12); List<RoiDistribution> roiDistribution = Arrays.asList(new RoiDistribution(0, roiByArtefact)); assertThat(roiDistributionFilter.filterHighestRoi(roiDistribution, 3).iterator().next().getRoiByArtefact().keySet()).containsOnly("A", "B", "D"); } | Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } |
@Test public void filterBestRoisFromManyDistributions() { Map<String, Integer> roiByArtefactOneInvest = Maps.newHashMap(); roiByArtefactOneInvest.put("A", 10); roiByArtefactOneInvest.put("B", 1); roiByArtefactOneInvest.put("C", 2); roiByArtefactOneInvest.put("D", 9); roiByArtefactOneInvest.put("E", 8); Map<String, Integer> roiByArtefactForTwoInvest = Maps.newHashMap(); roiByArtefactForTwoInvest.put("A", 2); roiByArtefactForTwoInvest.put("B", 10); roiByArtefactForTwoInvest.put("C", 4); roiByArtefactForTwoInvest.put("D", 3); roiByArtefactForTwoInvest.put("E", 1); Map<String, Integer> roiByArtefactForThreeInvest = Maps.newHashMap(); roiByArtefactForThreeInvest.put("A", 1); roiByArtefactForThreeInvest.put("B", 2); roiByArtefactForThreeInvest.put("C", 3); roiByArtefactForThreeInvest.put("D", 4); roiByArtefactForThreeInvest.put("E", 10); List<RoiDistribution> roiDistributions = Arrays.asList( new RoiDistribution(1, roiByArtefactOneInvest), new RoiDistribution(2, roiByArtefactForTwoInvest), new RoiDistribution(3, roiByArtefactForThreeInvest)); List<RoiDistribution> distributions = Lists.newArrayList(roiDistributionFilter.filterHighestRoi(roiDistributions, 4)); assertThat(distributions).hasSize(3); assertThat(distributions.get(0).getRoiByArtefact().keySet()).containsOnly("A", "B", "D", "E"); } | Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } | RoiDistributionFilter { Collection<RoiDistribution> filterHighestRoi(Collection<RoiDistribution> roiDistributions, int numberOfBestElements) { Map<Integer, RoiDistribution> filteredRoiDistributionsByInvest = Maps.newHashMap(); for (RoiDistribution distribution : roiDistributions) { filteredRoiDistributionsByInvest.put(distribution.getInvestInMinutes(), new RoiDistribution(distribution.getInvestInMinutes(), new HashMap<String, Integer>())); } for (String artefact : findArtefactsWithHighestRoi(roiDistributions, numberOfBestElements)) { for (RoiDistribution distribution : roiDistributions) { Integer roi = distribution.getRoiByArtefact().get(artefact); filteredRoiDistributionsByInvest.get(distribution.getInvestInMinutes()).getRoiByArtefact().put(artefact, roi); } } return filteredRoiDistributionsByInvest.values(); } } |
@Test public void shouldSupportSonarConnectionSettingsType() { assertThat(validator.supports(SonarConnectionSettings.class)).isTrue(); } | @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldNotSupportOtherTypeThanSonarConnectionSettings() { assertThat(validator.supports(Object.class)).isFalse(); } | @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | SonarConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return SonarConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void emptyAnalysis() throws IOException { QualityAnalysis analysis = QualityAnalysis.success(project, Collections.<QualityViolation>emptyList()); String expectedJson = "{ \"name\": \"Dummy Project\", \"allChildren\": [], \"children\": []}"; assertThat(generate(analysis).toString()).isEqualTo(mapper.readTree(expectedJson).toString()); } | public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); String generate(QualityAnalysis analysis); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); String generate(QualityAnalysis analysis); } |
@Test public void analysisWithOneArtefact() throws IOException { Artefact artefact = new Artefact("org.project.MyClass", "DUMMY"); artefact.setChangeProbability(0.6); QualityViolation violation = new QualityViolation(artefact, null, 5, 10, 0, ""); QualityAnalysis analysis = QualityAnalysis.success(project, Arrays.asList(violation)); when(weightedProfitCalculator.calculateWeightedProfit(violation)).thenReturn(1234.0); JsonNode generatedJson = generate(analysis); ArrayNode rootPackagNode = (ArrayNode) generatedJson.get("children"); assertThat(rootPackagNode.get(0).get("changeProbability").asInt()).isEqualTo(60); assertThat(rootPackagNode.get(0).get("children").get(0).get("children").get(0).get("value").asDouble()).isEqualTo(1234.0); } | public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); String generate(QualityAnalysis analysis); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); String generate(QualityAnalysis analysis); } |
@Test public void analysisWithManyArtefactsAndManyViolations() throws IOException { Artefact artefact1 = new Artefact("project.A", "DUMMY"); Artefact artefact2 = new Artefact("project.B", "DUMMY"); Artefact artefact3 = new Artefact("project.test.util.C", "DUMMY"); Artefact artefact4 = new Artefact("project.test.util.D", "DUMMY"); Artefact artefact5 = new Artefact("E", "DUMMY"); artefact1.setChangeProbability(0.1); artefact2.setChangeProbability(0.2); artefact3.setChangeProbability(0.3); artefact4.setChangeProbability(0.4); artefact5.setChangeProbability(0.5); QualityViolation violation1 = new QualityViolation(artefact1, null, 0, 0, 0, ""); QualityViolation violation2 = new QualityViolation(artefact2, null, 0, 0, 0, ""); QualityViolation violation3 = new QualityViolation(artefact3, null, 0, 0, 0, ""); QualityViolation violation4 = new QualityViolation(artefact4, null, 0, 0, 0, ""); QualityViolation violation5 = new QualityViolation(artefact5, null, 0, 0, 0, ""); QualityAnalysis analysis = QualityAnalysis.success(project, Arrays.asList(violation1, violation2, violation3, violation4, violation5)); when(weightedProfitCalculator.calculateWeightedProfit(violation1)).thenReturn(10.0); when(weightedProfitCalculator.calculateWeightedProfit(violation2)).thenReturn(20.0); when(weightedProfitCalculator.calculateWeightedProfit(violation3)).thenReturn(30.0); when(weightedProfitCalculator.calculateWeightedProfit(violation4)).thenReturn(40.0); when(weightedProfitCalculator.calculateWeightedProfit(violation5)).thenReturn(50.0); JsonNode generatedJson = generate(analysis); ArrayNode rootPackagNode = (ArrayNode) generatedJson.get("children"); assertThat(rootPackagNode.get(1).get("changeProbability").asInt()).isEqualTo(22); } | public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); String generate(QualityAnalysis analysis); } | InvestmentOpportunitiesJsonGenerator { public String generate(QualityAnalysis analysis) throws JsonProcessingException { Set<String> alreadyAddedArtefacts = Sets.newHashSet(); Map<String, PackageNode> nodeLookupTable = Maps.newHashMap(); RootNode rootNode = new RootNode(analysis.getProject().getName()); for (QualityViolation violation : analysis.getViolations()) { addArtefact(violation, rootNode, alreadyAddedArtefacts, nodeLookupTable); } rootNode.filterProfitableChildren(); rootNode.updateChangeProbabilityOfProfitableChildren(); rootNode.updateAutomaticChangeProbabilityAndEstimateOfAllChildren(); return MAPPER.writeValueAsString(rootNode); } @Autowired InvestmentOpportunitiesJsonGenerator(WeightedProfitCalculator weightedProfitCalculator); String generate(QualityAnalysis analysis); } |
@Test public void shouldNotConsiderViolationsWithNegativeProfit() { when(profitCalculator.calculateProfit(any(QualityViolation.class))).thenReturn(-0.1); QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 50); assertThat(qualityInvestmentPlan.getProfitInMinutes()).isZero(); assertThat(qualityInvestmentPlan.getRoi()).isZero(); assertThat(qualityInvestmentPlan.getEntries()).isEmpty(); } | public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } | QualityInvestmentPlanService { public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); } @Autowired QualityInvestmentPlanService(ProfitCalculator profitCalculator); QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes); } |
@Test public void generatedClassWithoutAdapter() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(ThriftyConverterFactory.create(ProtocolType.BINARY)) .build(); BrokenService brokenService = retrofit.create(BrokenService.class); try { brokenService.get(); fail(); } catch (IllegalArgumentException ignored) { } } | public static ThriftyConverterFactory create(ProtocolType protocolType) { return new ThriftyConverterFactory(protocolType); } | ThriftyConverterFactory extends Converter.Factory { public static ThriftyConverterFactory create(ProtocolType protocolType) { return new ThriftyConverterFactory(protocolType); } } | ThriftyConverterFactory extends Converter.Factory { public static ThriftyConverterFactory create(ProtocolType protocolType) { return new ThriftyConverterFactory(protocolType); } private ThriftyConverterFactory(ProtocolType protocolType); } | ThriftyConverterFactory extends Converter.Factory { public static ThriftyConverterFactory create(ProtocolType protocolType) { return new ThriftyConverterFactory(protocolType); } private ThriftyConverterFactory(ProtocolType protocolType); static ThriftyConverterFactory create(ProtocolType protocolType); @Override @SuppressWarnings("unchecked") Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit); @Override @SuppressWarnings("unchecked") Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit); } | ThriftyConverterFactory extends Converter.Factory { public static ThriftyConverterFactory create(ProtocolType protocolType) { return new ThriftyConverterFactory(protocolType); } private ThriftyConverterFactory(ProtocolType protocolType); static ThriftyConverterFactory create(ProtocolType protocolType); @Override @SuppressWarnings("unchecked") Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit); @Override @SuppressWarnings("unchecked") Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit); } |
@Test public void testSetSensorOffset() { angles.setSensorOffset(Facing.BACK, 90); assertEquals(90, angles.mSensorOffset); angles.setSensorOffset(Facing.FRONT, 90); assertEquals(270, angles.mSensorOffset); } | public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } |
@Test public void testToString() { String string = pool.toString(); assertTrue(string.contains("count")); assertTrue(string.contains("active")); assertTrue(string.contains("recycled")); assertTrue(string.contains(Pool.class.getSimpleName())); } | @NonNull @Override public String toString() { return getClass().getSimpleName() + " - count:" + count() + ", active:" + activeCount() + ", recycled:" + recycledCount(); } | Pool { @NonNull @Override public String toString() { return getClass().getSimpleName() + " - count:" + count() + ", active:" + activeCount() + ", recycled:" + recycledCount(); } } | Pool { @NonNull @Override public String toString() { return getClass().getSimpleName() + " - count:" + count() + ", active:" + activeCount() + ", recycled:" + recycledCount(); } Pool(int maxPoolSize, @NonNull Factory<T> factory); } | Pool { @NonNull @Override public String toString() { return getClass().getSimpleName() + " - count:" + count() + ", active:" + activeCount() + ", recycled:" + recycledCount(); } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } | Pool { @NonNull @Override public String toString() { return getClass().getSimpleName() + " - count:" + count() + ", active:" + activeCount() + ", recycled:" + recycledCount(); } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } |
@Test(expected = IllegalStateException.class) public void testRecycle_notActive() { Item item = new Item(); pool.recycle(item); } | public void recycle(@NonNull T item) { synchronized (lock) { LOG.v("RECYCLE - Recycling item.", this); if (--activeCount < 0) { throw new IllegalStateException("Trying to recycle an item which makes " + "activeCount < 0. This means that this or some previous items being " + "recycled were not coming from this pool, or some item was recycled " + "more than once. " + this); } if (!queue.offer(item)) { throw new IllegalStateException("Trying to recycle an item while the queue " + "is full. This means that this or some previous items being recycled " + "were not coming from this pool, or some item was recycled " + "more than once. " + this); } } } | Pool { public void recycle(@NonNull T item) { synchronized (lock) { LOG.v("RECYCLE - Recycling item.", this); if (--activeCount < 0) { throw new IllegalStateException("Trying to recycle an item which makes " + "activeCount < 0. This means that this or some previous items being " + "recycled were not coming from this pool, or some item was recycled " + "more than once. " + this); } if (!queue.offer(item)) { throw new IllegalStateException("Trying to recycle an item while the queue " + "is full. This means that this or some previous items being recycled " + "were not coming from this pool, or some item was recycled " + "more than once. " + this); } } } } | Pool { public void recycle(@NonNull T item) { synchronized (lock) { LOG.v("RECYCLE - Recycling item.", this); if (--activeCount < 0) { throw new IllegalStateException("Trying to recycle an item which makes " + "activeCount < 0. This means that this or some previous items being " + "recycled were not coming from this pool, or some item was recycled " + "more than once. " + this); } if (!queue.offer(item)) { throw new IllegalStateException("Trying to recycle an item while the queue " + "is full. This means that this or some previous items being recycled " + "were not coming from this pool, or some item was recycled " + "more than once. " + this); } } } Pool(int maxPoolSize, @NonNull Factory<T> factory); } | Pool { public void recycle(@NonNull T item) { synchronized (lock) { LOG.v("RECYCLE - Recycling item.", this); if (--activeCount < 0) { throw new IllegalStateException("Trying to recycle an item which makes " + "activeCount < 0. This means that this or some previous items being " + "recycled were not coming from this pool, or some item was recycled " + "more than once. " + this); } if (!queue.offer(item)) { throw new IllegalStateException("Trying to recycle an item while the queue " + "is full. This means that this or some previous items being recycled " + "were not coming from this pool, or some item was recycled " + "more than once. " + this); } } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } | Pool { public void recycle(@NonNull T item) { synchronized (lock) { LOG.v("RECYCLE - Recycling item.", this); if (--activeCount < 0) { throw new IllegalStateException("Trying to recycle an item which makes " + "activeCount < 0. This means that this or some previous items being " + "recycled were not coming from this pool, or some item was recycled " + "more than once. " + this); } if (!queue.offer(item)) { throw new IllegalStateException("Trying to recycle an item while the queue " + "is full. This means that this or some previous items being recycled " + "were not coming from this pool, or some item was recycled " + "more than once. " + this); } } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } |
@Test public void testGet_fromFactory() { pool.get(); assertEquals(1, instances); } | @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } |
@Test public void testGet_whenFull() { for (int i = 0; i < MAX_SIZE; i++) { pool.get(); } assertNull(pool.get()); } | @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } |
@Test public void testEquals() { Frame f1 = new Frame(manager); long time = 1000; f1.setContent("foo", time, 90, 180, new Size(5, 5), ImageFormat.NV21); Frame f2 = new Frame(manager); f2.setContent("bar", time, 0, 90, new Size(10, 10), ImageFormat.NV21); assertEquals(f1, f2); f2.setContent("foo", time + 1, 0, 90, new Size(10, 10), ImageFormat.NV21); assertNotEquals(f1, f2); } | @Override public boolean equals(Object obj) { return obj instanceof Frame && ((Frame) obj).mTime == mTime; } | Frame { @Override public boolean equals(Object obj) { return obj instanceof Frame && ((Frame) obj).mTime == mTime; } } | Frame { @Override public boolean equals(Object obj) { return obj instanceof Frame && ((Frame) obj).mTime == mTime; } Frame(@NonNull FrameManager manager); } | Frame { @Override public boolean equals(Object obj) { return obj instanceof Frame && ((Frame) obj).mTime == mTime; } Frame(@NonNull FrameManager manager); @Override boolean equals(Object obj); @SuppressLint("NewApi") @NonNull Frame freeze(); void release(); @SuppressWarnings("unchecked") @NonNull T getData(); @NonNull Class<?> getDataClass(); long getTime(); @Deprecated int getRotation(); int getRotationToUser(); int getRotationToView(); @NonNull Size getSize(); int getFormat(); } | Frame { @Override public boolean equals(Object obj) { return obj instanceof Frame && ((Frame) obj).mTime == mTime; } Frame(@NonNull FrameManager manager); @Override boolean equals(Object obj); @SuppressLint("NewApi") @NonNull Frame freeze(); void release(); @SuppressWarnings("unchecked") @NonNull T getData(); @NonNull Class<?> getDataClass(); long getTime(); @Deprecated int getRotation(); int getRotationToUser(); int getRotationToView(); @NonNull Size getSize(); int getFormat(); } |
@Test public void testFreeze() { Frame frame = new Frame(manager); String data = "test data"; long time = 1000; int userRotation = 90; int viewRotation = 90; Size size = new Size(10, 10); int format = ImageFormat.NV21; frame.setContent(data, time, userRotation, viewRotation, size, format); Frame frozen = frame.freeze(); assertEquals(data, frozen.getData()); assertEquals(time, frozen.getTime()); assertEquals(userRotation, frozen.getRotationToUser()); assertEquals(viewRotation, frozen.getRotationToView()); assertEquals(size, frozen.getSize()); frame.setContent("new data", 50, 180, 180, new Size(1, 1), ImageFormat.JPEG); assertEquals(data, frozen.getData()); assertEquals(time, frozen.getTime()); assertEquals(userRotation, frozen.getRotationToUser()); assertEquals(viewRotation, frozen.getRotationToView()); assertEquals(size, frozen.getSize()); assertEquals(format, frozen.getFormat()); } | @SuppressLint("NewApi") @NonNull public Frame freeze() { ensureHasContent(); Frame other = new Frame(mManager); Object data = mManager.cloneFrameData(getData()); other.setContent(data, mTime, mUserRotation, mViewRotation, mSize, mFormat); return other; } | Frame { @SuppressLint("NewApi") @NonNull public Frame freeze() { ensureHasContent(); Frame other = new Frame(mManager); Object data = mManager.cloneFrameData(getData()); other.setContent(data, mTime, mUserRotation, mViewRotation, mSize, mFormat); return other; } } | Frame { @SuppressLint("NewApi") @NonNull public Frame freeze() { ensureHasContent(); Frame other = new Frame(mManager); Object data = mManager.cloneFrameData(getData()); other.setContent(data, mTime, mUserRotation, mViewRotation, mSize, mFormat); return other; } Frame(@NonNull FrameManager manager); } | Frame { @SuppressLint("NewApi") @NonNull public Frame freeze() { ensureHasContent(); Frame other = new Frame(mManager); Object data = mManager.cloneFrameData(getData()); other.setContent(data, mTime, mUserRotation, mViewRotation, mSize, mFormat); return other; } Frame(@NonNull FrameManager manager); @Override boolean equals(Object obj); @SuppressLint("NewApi") @NonNull Frame freeze(); void release(); @SuppressWarnings("unchecked") @NonNull T getData(); @NonNull Class<?> getDataClass(); long getTime(); @Deprecated int getRotation(); int getRotationToUser(); int getRotationToView(); @NonNull Size getSize(); int getFormat(); } | Frame { @SuppressLint("NewApi") @NonNull public Frame freeze() { ensureHasContent(); Frame other = new Frame(mManager); Object data = mManager.cloneFrameData(getData()); other.setContent(data, mTime, mUserRotation, mViewRotation, mSize, mFormat); return other; } Frame(@NonNull FrameManager manager); @Override boolean equals(Object obj); @SuppressLint("NewApi") @NonNull Frame freeze(); void release(); @SuppressWarnings("unchecked") @NonNull T getData(); @NonNull Class<?> getDataClass(); long getTime(); @Deprecated int getRotation(); int getRotationToUser(); int getRotationToView(); @NonNull Size getSize(); int getFormat(); } |
@Test public void testEquals() { AspectRatio ratio = AspectRatio.of(50, 10); assertNotNull(ratio); assertEquals(ratio, ratio); AspectRatio ratio1 = AspectRatio.of(5, 1); assertEquals(ratio, ratio1); AspectRatio.sCache.clear(); AspectRatio ratio2 = AspectRatio.of(500, 100); assertEquals(ratio, ratio2); Size size = new Size(500, 100); assertTrue(ratio.matches(size)); } | @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof AspectRatio) { return toFloat() == ((AspectRatio) o).toFloat(); } return false; } | AspectRatio implements Comparable<AspectRatio> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof AspectRatio) { return toFloat() == ((AspectRatio) o).toFloat(); } return false; } } | AspectRatio implements Comparable<AspectRatio> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof AspectRatio) { return toFloat() == ((AspectRatio) o).toFloat(); } return false; } private AspectRatio(int x, int y); } | AspectRatio implements Comparable<AspectRatio> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof AspectRatio) { return toFloat() == ((AspectRatio) o).toFloat(); } return false; } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } | AspectRatio implements Comparable<AspectRatio> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof AspectRatio) { return toFloat() == ((AspectRatio) o).toFloat(); } return false; } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } |
@Test(expected = NumberFormatException.class) public void testParse_notNumbers() { AspectRatio.parse("a:b"); } | @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } |
@Test(expected = NumberFormatException.class) public void testParse_noColon() { AspectRatio.parse("24"); } | @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } |
@Test public void testParse() { AspectRatio ratio = AspectRatio.parse("16:9"); assertEquals(ratio.getX(), 16); assertEquals(ratio.getY(), 9); } | @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } | AspectRatio implements Comparable<AspectRatio> { @NonNull @SuppressWarnings("WeakerAccess") public static AspectRatio parse(@NonNull String string) { String[] parts = string.split(":"); if (parts.length != 2) { throw new NumberFormatException("Illegal AspectRatio string. Must be x:y"); } int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); return of(x, y); } private AspectRatio(int x, int y); @NonNull static AspectRatio of(@NonNull Size size); @NonNull static AspectRatio of(int x, int y); @NonNull @SuppressWarnings("WeakerAccess") static AspectRatio parse(@NonNull String string); int getX(); int getY(); boolean matches(@NonNull Size size); boolean matches(@NonNull Size size, float tolerance); @Override boolean equals(Object o); @NonNull @Override String toString(); float toFloat(); @Override int hashCode(); @Override int compareTo(@NonNull AspectRatio another); @SuppressWarnings("SuspiciousNameCombination") @NonNull AspectRatio flip(); } |
@Test public void testSetDisplayOffset() { angles.setDisplayOffset(90); assertEquals(90, angles.mDisplayOffset); } | public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } |
@Test public void testFlip() { Size size = new Size(10, 20); Size flipped = size.flip(); assertEquals(size.getWidth(), flipped.getHeight()); assertEquals(size.getHeight(), flipped.getWidth()); } | @SuppressWarnings("SuspiciousNameCombination") public Size flip() { return new Size(mHeight, mWidth); } | Size implements Comparable<Size> { @SuppressWarnings("SuspiciousNameCombination") public Size flip() { return new Size(mHeight, mWidth); } } | Size implements Comparable<Size> { @SuppressWarnings("SuspiciousNameCombination") public Size flip() { return new Size(mHeight, mWidth); } Size(int width, int height); } | Size implements Comparable<Size> { @SuppressWarnings("SuspiciousNameCombination") public Size flip() { return new Size(mHeight, mWidth); } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } | Size implements Comparable<Size> { @SuppressWarnings("SuspiciousNameCombination") public Size flip() { return new Size(mHeight, mWidth); } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } |
@Test public void testEquals() { Size s1 = new Size(10, 20); assertEquals(s1, s1); assertNotEquals(s1, null); assertNotEquals(s1, ""); Size s2 = new Size(10, 0); Size s3 = new Size(10, 20); assertEquals(s1, s3); assertNotEquals(s1, s2); } | @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof Size) { Size size = (Size) o; return mWidth == size.mWidth && mHeight == size.mHeight; } return false; } | Size implements Comparable<Size> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof Size) { Size size = (Size) o; return mWidth == size.mWidth && mHeight == size.mHeight; } return false; } } | Size implements Comparable<Size> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof Size) { Size size = (Size) o; return mWidth == size.mWidth && mHeight == size.mHeight; } return false; } Size(int width, int height); } | Size implements Comparable<Size> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof Size) { Size size = (Size) o; return mWidth == size.mWidth && mHeight == size.mHeight; } return false; } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } | Size implements Comparable<Size> { @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (o instanceof Size) { Size size = (Size) o; return mWidth == size.mWidth && mHeight == size.mHeight; } return false; } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } |
@Test public void testHashCode() { Size s1 = new Size(10, 20); Size s2 = new Size(10, 0); assertNotEquals(s1.hashCode(), s2.hashCode()); } | @Override public int hashCode() { return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2))); } | Size implements Comparable<Size> { @Override public int hashCode() { return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2))); } } | Size implements Comparable<Size> { @Override public int hashCode() { return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2))); } Size(int width, int height); } | Size implements Comparable<Size> { @Override public int hashCode() { return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2))); } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } | Size implements Comparable<Size> { @Override public int hashCode() { return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2))); } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } |
@Test public void testCompare() { Size s1 = new Size(10, 20); Size s2 = new Size(10, 0); Size s3 = new Size(10, 20); assertTrue(s1.compareTo(s3) == 0); assertTrue(s1.compareTo(s2) > 0); assertTrue(s2.compareTo(s1) < 0); } | @Override public int compareTo(@NonNull Size another) { return mWidth * mHeight - another.mWidth * another.mHeight; } | Size implements Comparable<Size> { @Override public int compareTo(@NonNull Size another) { return mWidth * mHeight - another.mWidth * another.mHeight; } } | Size implements Comparable<Size> { @Override public int compareTo(@NonNull Size another) { return mWidth * mHeight - another.mWidth * another.mHeight; } Size(int width, int height); } | Size implements Comparable<Size> { @Override public int compareTo(@NonNull Size another) { return mWidth * mHeight - another.mWidth * another.mHeight; } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } | Size implements Comparable<Size> { @Override public int compareTo(@NonNull Size another) { return mWidth * mHeight - another.mWidth * another.mHeight; } Size(int width, int height); int getWidth(); int getHeight(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); @Override boolean equals(Object o); @NonNull @Override String toString(); @Override int hashCode(); @Override int compareTo(@NonNull Size another); } |
@Test public void testWithFilter() { SizeSelector selector = SizeSelectors.withFilter(new SizeSelectors.Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() == 600; } }); List<Size> list = selector.select(input); assertEquals(list.size(), 2); assertEquals(list.get(0), new Size(600, 900)); assertEquals(list.get(1), new Size(600, 600)); } | @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector withFilter(@NonNull Filter filter) { return new FilterSelector(filter); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector withFilter(@NonNull Filter filter) { return new FilterSelector(filter); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector withFilter(@NonNull Filter filter) { return new FilterSelector(filter); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector withFilter(@NonNull Filter filter) { return new FilterSelector(filter); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector withFilter(@NonNull Filter filter) { return new FilterSelector(filter); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMaxWidth() { SizeSelector selector = SizeSelectors.maxWidth(50); List<Size> list = selector.select(input); assertEquals(list.size(), 2); assertEquals(list.get(0), new Size(30, 40)); assertEquals(list.get(1), new Size(40, 30)); } | @NonNull public static SizeSelector maxWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() <= width; } }); } | SizeSelectors { @NonNull public static SizeSelector maxWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() <= width; } }); } } | SizeSelectors { @NonNull public static SizeSelector maxWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() <= width; } }); } } | SizeSelectors { @NonNull public static SizeSelector maxWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() <= width; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @NonNull public static SizeSelector maxWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() <= width; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMinWidth() { SizeSelector selector = SizeSelectors.minWidth(1000); List<Size> list = selector.select(input); assertEquals(list.size(), 2); assertEquals(list.get(0), new Size(1600, 900)); assertEquals(list.get(1), new Size(2000, 4000)); } | @NonNull public static SizeSelector minWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() >= width; } }); } | SizeSelectors { @NonNull public static SizeSelector minWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() >= width; } }); } } | SizeSelectors { @NonNull public static SizeSelector minWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() >= width; } }); } } | SizeSelectors { @NonNull public static SizeSelector minWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() >= width; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @NonNull public static SizeSelector minWidth(final int width) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getWidth() >= width; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMaxHeight() { SizeSelector selector = SizeSelectors.maxHeight(50); List<Size> list = selector.select(input); assertEquals(list.size(), 2); assertEquals(list.get(0), new Size(30, 40)); assertEquals(list.get(1), new Size(40, 30)); } | @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector maxHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() <= height; } }); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector maxHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() <= height; } }); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector maxHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() <= height; } }); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector maxHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() <= height; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector maxHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() <= height; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMinHeight() { SizeSelector selector = SizeSelectors.minHeight(1000); List<Size> list = selector.select(input); assertEquals(list.size(), 1); assertEquals(list.get(0), new Size(2000, 4000)); } | @NonNull public static SizeSelector minHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() >= height; } }); } | SizeSelectors { @NonNull public static SizeSelector minHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() >= height; } }); } } | SizeSelectors { @NonNull public static SizeSelector minHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() >= height; } }); } } | SizeSelectors { @NonNull public static SizeSelector minHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() >= height; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @NonNull public static SizeSelector minHeight(final int height) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() >= height; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testAspectRatio() { SizeSelector selector = SizeSelectors.aspectRatio(AspectRatio.of(16, 9), 0); List<Size> list = selector.select(input); assertEquals(list.size(), 1); assertEquals(list.get(0), new Size(1600, 900)); selector = SizeSelectors.aspectRatio(AspectRatio.of(1, 2), 0); list = selector.select(input); assertEquals(list.size(), 3); assertEquals(list.get(0), new Size(100, 200)); assertEquals(list.get(1), new Size(150, 300)); assertEquals(list.get(2), new Size(2000, 4000)); } | @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector aspectRatio(AspectRatio ratio, final float delta) { final float desired = ratio.toFloat(); return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { float candidate = AspectRatio.of(size.getWidth(), size.getHeight()).toFloat(); return candidate >= desired - delta && candidate <= desired + delta; } }); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector aspectRatio(AspectRatio ratio, final float delta) { final float desired = ratio.toFloat(); return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { float candidate = AspectRatio.of(size.getWidth(), size.getHeight()).toFloat(); return candidate >= desired - delta && candidate <= desired + delta; } }); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector aspectRatio(AspectRatio ratio, final float delta) { final float desired = ratio.toFloat(); return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { float candidate = AspectRatio.of(size.getWidth(), size.getHeight()).toFloat(); return candidate >= desired - delta && candidate <= desired + delta; } }); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector aspectRatio(AspectRatio ratio, final float delta) { final float desired = ratio.toFloat(); return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { float candidate = AspectRatio.of(size.getWidth(), size.getHeight()).toFloat(); return candidate >= desired - delta && candidate <= desired + delta; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector aspectRatio(AspectRatio ratio, final float delta) { final float desired = ratio.toFloat(); return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { float candidate = AspectRatio.of(size.getWidth(), size.getHeight()).toFloat(); return candidate >= desired - delta && candidate <= desired + delta; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testSetDeviceOrientation() { angles.setDeviceOrientation(90); assertEquals(90, angles.mDeviceOrientation); } | public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } |
@Test public void testMax() { SizeSelector selector = SizeSelectors.biggest(); List<Size> list = selector.select(input); assertEquals(list.size(), input.size()); assertEquals(list.get(0), new Size(2000, 4000)); } | @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector biggest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); Collections.reverse(source); return source; } }; } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector biggest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); Collections.reverse(source); return source; } }; } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector biggest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); Collections.reverse(source); return source; } }; } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector biggest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); Collections.reverse(source); return source; } }; } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector biggest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); Collections.reverse(source); return source; } }; } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMin() { SizeSelector selector = SizeSelectors.smallest(); List<Size> list = selector.select(input); assertEquals(list.size(), input.size()); assertTrue(list.get(0).equals(new Size(30, 40)) || list.get(0).equals(new Size(40, 30))); } | @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector smallest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); return source; } }; } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector smallest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); return source; } }; } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector smallest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); return source; } }; } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector smallest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); return source; } }; } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector smallest() { return new SizeSelector() { @NonNull @Override public List<Size> select(@NonNull List<Size> source) { Collections.sort(source); return source; } }; } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMaxArea() { SizeSelector selector = SizeSelectors.maxArea(100 * 100); List<Size> list = selector.select(input); assertEquals(list.size(), 2); assertEquals(list.get(0), new Size(30, 40)); assertEquals(list.get(1), new Size(40, 30)); } | @NonNull @SuppressWarnings("WeakerAccess") public static SizeSelector maxArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() <= area; } }); } | SizeSelectors { @NonNull @SuppressWarnings("WeakerAccess") public static SizeSelector maxArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() <= area; } }); } } | SizeSelectors { @NonNull @SuppressWarnings("WeakerAccess") public static SizeSelector maxArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() <= area; } }); } } | SizeSelectors { @NonNull @SuppressWarnings("WeakerAccess") public static SizeSelector maxArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() <= area; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @NonNull @SuppressWarnings("WeakerAccess") public static SizeSelector maxArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() <= area; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testMinArea() { SizeSelector selector = SizeSelectors.minArea(1000 * 1000); List<Size> list = selector.select(input); assertEquals(list.size(), 2); assertEquals(list.get(0), new Size(1600, 900)); assertEquals(list.get(1), new Size(2000, 4000)); } | @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector minArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() >= area; } }); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector minArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() >= area; } }); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector minArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() >= area; } }); } } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector minArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() >= area; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @SuppressWarnings("WeakerAccess") @NonNull public static SizeSelector minArea(final int area) { return withFilter(new Filter() { @Override public boolean accepts(@NonNull Size size) { return size.getHeight() * size.getWidth() >= area; } }); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test public void testAnd() { SizeSelector selector = SizeSelectors.and( SizeSelectors.aspectRatio(AspectRatio.of(1, 2), 0), SizeSelectors.maxWidth(100) ); List<Size> list = selector.select(input); assertEquals(list.size(), 1); assertEquals(list.get(0), new Size(100, 200)); } | @NonNull public static SizeSelector and(SizeSelector... selectors) { return new AndSelector(selectors); } | SizeSelectors { @NonNull public static SizeSelector and(SizeSelector... selectors) { return new AndSelector(selectors); } } | SizeSelectors { @NonNull public static SizeSelector and(SizeSelector... selectors) { return new AndSelector(selectors); } } | SizeSelectors { @NonNull public static SizeSelector and(SizeSelector... selectors) { return new AndSelector(selectors); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } | SizeSelectors { @NonNull public static SizeSelector and(SizeSelector... selectors) { return new AndSelector(selectors); } @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector withFilter(@NonNull Filter filter); @NonNull static SizeSelector maxWidth(final int width); @NonNull static SizeSelector minWidth(final int width); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector maxHeight(final int height); @NonNull static SizeSelector minHeight(final int height); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector aspectRatio(AspectRatio ratio, final float delta); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector biggest(); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector smallest(); @NonNull @SuppressWarnings("WeakerAccess") static SizeSelector maxArea(final int area); @SuppressWarnings("WeakerAccess") @NonNull static SizeSelector minArea(final int area); @NonNull static SizeSelector and(SizeSelector... selectors); @NonNull static SizeSelector or(SizeSelector... selectors); } |
@Test(expected = IllegalStateException.class) public void testSetSensorOffset_throws() { angles.setSensorOffset(Facing.BACK, 135); } | public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } | Angles { public void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset) { sanitizeInput(sensorOffset); mSensorFacing = sensorFacing; mSensorOffset = sensorOffset; if (mSensorFacing == Facing.FRONT) { mSensorOffset = sanitizeOutput(360 - mSensorOffset); } print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } |
@Test(expected = IllegalStateException.class) public void testSetDisplayOffset_throws() { angles.setDisplayOffset(135); } | public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } | Angles { public void setDisplayOffset(int displayOffset) { sanitizeInput(displayOffset); mDisplayOffset = displayOffset; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } |
@Test(expected = IllegalStateException.class) public void testSetDeviceOrientation_throws() { angles.setDeviceOrientation(135); } | public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } | Angles { public void setDeviceOrientation(int deviceOrientation) { sanitizeInput(deviceOrientation); mDeviceOrientation = deviceOrientation; print(); } void setSensorOffset(@NonNull Facing sensorFacing, int sensorOffset); void setDisplayOffset(int displayOffset); void setDeviceOrientation(int deviceOrientation); int offset(@NonNull Reference from, @NonNull Reference to, @NonNull Axis axis); boolean flip(@NonNull Reference from, @NonNull Reference to); } |
@Test public void testValues() { assertEquals(0, ExifHelper.getOrientation(ExifInterface.ORIENTATION_NORMAL)); assertEquals(0, ExifHelper.getOrientation(ExifInterface.ORIENTATION_FLIP_HORIZONTAL)); assertEquals(180, ExifHelper.getOrientation(ExifInterface.ORIENTATION_ROTATE_180)); assertEquals(180, ExifHelper.getOrientation(ExifInterface.ORIENTATION_FLIP_VERTICAL)); assertEquals(90, ExifHelper.getOrientation(ExifInterface.ORIENTATION_ROTATE_90)); assertEquals(90, ExifHelper.getOrientation(ExifInterface.ORIENTATION_TRANSPOSE)); assertEquals(270, ExifHelper.getOrientation(ExifInterface.ORIENTATION_ROTATE_270)); assertEquals(270, ExifHelper.getOrientation(ExifInterface.ORIENTATION_TRANSVERSE)); } | public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } static int getOrientation(int exifOrientation); static int getExifOrientation(int orientation); } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } static int getOrientation(int exifOrientation); static int getExifOrientation(int orientation); } |
@Test public void testUnknownValues() { assertEquals(0, ExifHelper.getOrientation(-15)); assertEquals(0, ExifHelper.getOrientation(-1)); assertEquals(0, ExifHelper.getOrientation(195)); assertEquals(0, ExifHelper.getOrientation(Integer.MAX_VALUE)); } | public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } static int getOrientation(int exifOrientation); static int getExifOrientation(int orientation); } | ExifHelper { public static int getOrientation(int exifOrientation) { int orientation; switch (exifOrientation) { case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = 0; break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSPOSE: orientation = 90; break; case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_TRANSVERSE: orientation = 270; break; default: orientation = 0; } return orientation; } static int getOrientation(int exifOrientation); static int getExifOrientation(int orientation); } |
@Test public void testInstances() { for (int i = 0; i < MAX_SIZE; i++) { assertEquals(instances, i); pool.get(); } } | @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } | Pool { @Nullable public T get() { synchronized (lock) { T item = queue.poll(); if (item != null) { activeCount++; LOG.v("GET - Reusing recycled item.", this); return item; } if (isEmpty()) { LOG.v("GET - Returning null. Too much items requested.", this); return null; } activeCount++; LOG.v("GET - Creating a new item.", this); return factory.create(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } |
@Test public void testClear() { Item item = pool.get(); assertNotNull(item); pool.recycle(item); assertEquals(pool.recycledCount(), 1); assertEquals(pool.activeCount(), 0); assertEquals(pool.count(), 1); pool.clear(); assertEquals(pool.recycledCount(), 0); assertEquals(pool.activeCount(), 0); assertEquals(pool.count(), 0); } | @CallSuper public void clear() { synchronized (lock) { queue.clear(); } } | Pool { @CallSuper public void clear() { synchronized (lock) { queue.clear(); } } } | Pool { @CallSuper public void clear() { synchronized (lock) { queue.clear(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); } | Pool { @CallSuper public void clear() { synchronized (lock) { queue.clear(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } | Pool { @CallSuper public void clear() { synchronized (lock) { queue.clear(); } } Pool(int maxPoolSize, @NonNull Factory<T> factory); boolean isEmpty(); @Nullable T get(); void recycle(@NonNull T item); @CallSuper void clear(); final int count(); @SuppressWarnings("WeakerAccess") final int activeCount(); @SuppressWarnings("WeakerAccess") final int recycledCount(); @NonNull @Override String toString(); } |
@Test public void invokerStrategy() throws InterruptedException { SchedulingStrategy strategy = SchedulingStrategies.createInvokerStrategy( new Logger() ); assertFalse( strategy.hasSharedThreadPool() ); assertTrue( strategy.canSchedule() ); Task task = new Task(); strategy.schedule( task ); assertTrue( strategy.canSchedule() ); assertTrue( task.result ); assertTrue( strategy.finished() ); assertFalse( strategy.canSchedule() ); } | public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) { return new InvokerStrategy( logger ); } | SchedulingStrategies { public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) { return new InvokerStrategy( logger ); } } | SchedulingStrategies { public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) { return new InvokerStrategy( logger ); } } | SchedulingStrategies { public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) { return new InvokerStrategy( logger ); } static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ); static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleLogger logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleLogger logger, ExecutorService threadPool ); } | SchedulingStrategies { public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) { return new InvokerStrategy( logger ); } static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ); static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleLogger logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleLogger logger, ExecutorService threadPool ); } |
@Test public void optimizationParameter() { assertFalse( newTestSetOptimization( false ).isParallelOptimization() ); } | public boolean isParallelOptimization() { return parallelOptimization; } | JUnitCoreParameters { public boolean isParallelOptimization() { return parallelOptimization; } } | JUnitCoreParameters { public boolean isParallelOptimization() { return parallelOptimization; } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isParallelOptimization() { return parallelOptimization; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isParallelOptimization() { return parallelOptimization; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void isParallelMethod() { assertFalse( newTestSetClasses().isParallelMethods() ); assertTrue( newTestSetMethods().isParallelMethods() ); assertTrue( newTestSetBoth().isParallelMethods() ); } | public boolean isParallelMethods() { return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( parallel ); } | JUnitCoreParameters { public boolean isParallelMethods() { return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( parallel ); } } | JUnitCoreParameters { public boolean isParallelMethods() { return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isParallelMethods() { return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isParallelMethods() { return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void isParallelClasses() { assertTrue( newTestSetClasses().isParallelClasses() ); assertFalse( newTestSetMethods().isParallelClasses() ); assertTrue( newTestSetBoth().isParallelClasses() ); } | public boolean isParallelClasses() { return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( parallel ); } | JUnitCoreParameters { public boolean isParallelClasses() { return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( parallel ); } } | JUnitCoreParameters { public boolean isParallelClasses() { return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isParallelClasses() { return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isParallelClasses() { return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void isParallelBoth() { assertFalse( isParallelMethodsAndClasses( newTestSetClasses() ) ); assertFalse( isParallelMethodsAndClasses( newTestSetMethods() ) ); assertTrue( isParallelMethodsAndClasses( newTestSetBoth() ) ); } | @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } | JUnitCoreParameters { @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } } | JUnitCoreParameters { @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void nonSharedPoolStrategy() throws InterruptedException { SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategy( new Logger(), 2 ); assertFalse( strategy.hasSharedThreadPool() ); assertTrue( strategy.canSchedule() ); Task task1 = new Task(); Task task2 = new Task(); strategy.schedule( task1 ); strategy.schedule( task2 ); assertTrue( strategy.canSchedule() ); assertTrue( strategy.finished() ); assertFalse( strategy.canSchedule() ); assertTrue( task1.result ); assertTrue( task2.result ); } | public static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ) { return new NonSharedThreadPoolStrategy( logger, Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); } | SchedulingStrategies { public static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ) { return new NonSharedThreadPoolStrategy( logger, Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); } } | SchedulingStrategies { public static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ) { return new NonSharedThreadPoolStrategy( logger, Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); } } | SchedulingStrategies { public static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ) { return new NonSharedThreadPoolStrategy( logger, Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); } static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ); static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleLogger logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleLogger logger, ExecutorService threadPool ); } | SchedulingStrategies { public static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ) { return new NonSharedThreadPoolStrategy( logger, Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); } static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ); static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleLogger logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleLogger logger, ExecutorService threadPool ); } |
@Test public void isPerCoreThreadCount() { assertFalse( newTestSetClasses().isPerCoreThreadCount() ); assertFalse( newTestSetMethods().isPerCoreThreadCount() ); assertTrue( newTestSetBoth().isPerCoreThreadCount() ); } | public boolean isPerCoreThreadCount() { return perCoreThreadCount; } | JUnitCoreParameters { public boolean isPerCoreThreadCount() { return perCoreThreadCount; } } | JUnitCoreParameters { public boolean isPerCoreThreadCount() { return perCoreThreadCount; } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isPerCoreThreadCount() { return perCoreThreadCount; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isPerCoreThreadCount() { return perCoreThreadCount; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void getThreadCount() { assertFalse( newTestSetClasses().isPerCoreThreadCount() ); assertFalse( newTestSetMethods().isPerCoreThreadCount() ); assertTrue( newTestSetBoth().isPerCoreThreadCount() ); } | public int getThreadCount() { return threadCount; } | JUnitCoreParameters { public int getThreadCount() { return threadCount; } } | JUnitCoreParameters { public int getThreadCount() { return threadCount; } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public int getThreadCount() { return threadCount; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public int getThreadCount() { return threadCount; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void isUseUnlimitedThreads() { assertFalse( newTestSetClasses().isUseUnlimitedThreads() ); assertTrue( newTestSetMethods().isUseUnlimitedThreads() ); assertFalse( newTestSetBoth().isUseUnlimitedThreads() ); } | public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } | JUnitCoreParameters { public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } } | JUnitCoreParameters { public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void isNoThreading() { assertFalse( newTestSetClasses().isNoThreading() ); assertFalse( newTestSetMethods().isNoThreading() ); assertFalse( newTestSetBoth().isNoThreading() ); } | public boolean isNoThreading() { return !isParallelismSelected(); } | JUnitCoreParameters { public boolean isNoThreading() { return !isParallelismSelected(); } } | JUnitCoreParameters { public boolean isNoThreading() { return !isParallelismSelected(); } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isNoThreading() { return !isParallelismSelected(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isNoThreading() { return !isParallelismSelected(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
@Test public void isAnyParallelismSelected() { assertTrue( newTestSetClasses().isParallelismSelected() ); assertTrue( newTestSetMethods().isParallelismSelected() ); assertTrue( newTestSetBoth().isParallelismSelected() ); } | public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } | JUnitCoreParameters { public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } } | JUnitCoreParameters { public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } JUnitCoreParameters( Map<String, String> properties ); } | JUnitCoreParameters { public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); } | JUnitCoreParameters { public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( { "unused", "deprecation" } ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.