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 addPetTest() { Pet body = null; api.addPet(body); } | public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); } | PetApi { public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); } } | PetApi { public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void deletePetTest() { Long petId = null; String apiKey = null; api.deletePet(petId, apiKey); } | public void deletePet(Long petId, String apiKey) throws RestClientException { deletePetWithHttpInfo(petId, apiKey); } | PetApi { public void deletePet(Long petId, String apiKey) throws RestClientException { deletePetWithHttpInfo(petId, apiKey); } } | PetApi { public void deletePet(Long petId, String apiKey) throws RestClientException { deletePetWithHttpInfo(petId, apiKey); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public void deletePet(Long petId, String apiKey) throws RestClientException { deletePetWithHttpInfo(petId, apiKey); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public void deletePet(Long petId, String apiKey) throws RestClientException { deletePetWithHttpInfo(petId, apiKey); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void findPetsByStatusTest() { List<String> status = null; List<Pet> response = api.findPetsByStatus(status); } | public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { return findPetsByStatusWithHttpInfo(status).getBody(); } | PetApi { public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { return findPetsByStatusWithHttpInfo(status).getBody(); } } | PetApi { public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { return findPetsByStatusWithHttpInfo(status).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { return findPetsByStatusWithHttpInfo(status).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { return findPetsByStatusWithHttpInfo(status).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void findPetsByTagsTest() { List<String> tags = null; List<Pet> response = api.findPetsByTags(tags); } | @Deprecated public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { return findPetsByTagsWithHttpInfo(tags).getBody(); } | PetApi { @Deprecated public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { return findPetsByTagsWithHttpInfo(tags).getBody(); } } | PetApi { @Deprecated public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { return findPetsByTagsWithHttpInfo(tags).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { @Deprecated public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { return findPetsByTagsWithHttpInfo(tags).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { @Deprecated public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { return findPetsByTagsWithHttpInfo(tags).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void getPetByIdTest() { Long petId = null; Pet response = api.getPetById(petId); } | public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); } | PetApi { public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); } } | PetApi { public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void updatePetTest() { Pet body = null; api.updatePet(body); } | public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); } | PetApi { public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); } } | PetApi { public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void whenSortStream_thenGetSortedStream() { List<Employee> employees = empList.stream() .sorted((e1, e2) -> e1.getName().compareTo(e2.getName())) .collect(Collectors.toList()); assertEquals(employees.get(0).getName(), "Bill Gates"); assertEquals(employees.get(1).getName(), "Jeff Bezos"); assertEquals(employees.get(2).getName(), "Mark Zuckerberg"); } | public String getName() { return name; } | Employee { public String getName() { return name; } } | Employee { public String getName() { return name; } Employee(Integer id, String name, Double salary); } | Employee { public String getName() { return name; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } | Employee { public String getName() { return name; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } |
@Test public void updatePetWithFormTest() { Long petId = null; String name = null; String status = null; api.updatePetWithForm(petId, name, status); } | public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { updatePetWithFormWithHttpInfo(petId, name, status); } | PetApi { public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { updatePetWithFormWithHttpInfo(petId, name, status); } } | PetApi { public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { updatePetWithFormWithHttpInfo(petId, name, status); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { updatePetWithFormWithHttpInfo(petId, name, status); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { updatePetWithFormWithHttpInfo(petId, name, status); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void uploadFileTest() { Long petId = null; String additionalMetadata = null; File file = null; ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); } | public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); } | PetApi { public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); } } | PetApi { public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); } | PetApi { public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | PetApi { public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } |
@Test public void testFormatter() { String dateRegex1 = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$"; String dateString = Formatter.getFormattedDate(); assertTrue(Pattern .matches(dateRegex1, dateString)); } | public static String getFormattedDate() { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } | Formatter { public static String getFormattedDate() { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } } | Formatter { public static String getFormattedDate() { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } } | Formatter { public static String getFormattedDate() { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } static String getFormattedDate(); } | Formatter { public static String getFormattedDate() { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } static String getFormattedDate(); } |
@Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); } | @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } | @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } | @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); } | @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( options("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) .andExpect(header().string(HttpHeaders.VARY, "Origin")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); } | @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testCorsFilterOnOtherPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/test/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } | @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } | @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void whenFindMin_thenGetMinElementFromStream() { Employee firstEmp = empList.stream() .min((e1, e2) -> e1.getId() - e2.getId()) .orElseThrow(NoSuchElementException::new); assertEquals(firstEmp.getId(), new Integer(1)); } | public Integer getId() { return id; } | Employee { public Integer getId() { return id; } } | Employee { public Integer getId() { return id; } Employee(Integer id, String name, Double salary); } | Employee { public Integer getId() { return id; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } | Employee { public Integer getId() { return id; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } |
@Test public void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } | @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testAuthenticationCookies() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); request.addHeader("Authorization", CLIENT_AUTHORIZATION); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user"); params.put("rememberMe", "true"); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.authenticate(request, response, params); Cookie accessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(ACCESS_TOKEN_VALUE, accessTokenCookie.getValue()); Cookie refreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(REFRESH_TOKEN_VALUE, OAuth2CookieHelper.getRefreshTokenValue(refreshTokenCookie)); Assert.assertTrue(OAuth2CookieHelper.isRememberMe(refreshTokenCookie)); } | public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } |
@Test public void whenFindMax_thenGetMaxElementFromStream() { Employee maxSalEmp = empList.stream() .max(Comparator.comparing(Employee::getSalary)) .orElseThrow(NoSuchElementException::new); assertEquals(maxSalEmp.getSalary(), new Double(300000.0)); } | public Double getSalary() { return salary; } | Employee { public Double getSalary() { return salary; } } | Employee { public Double getSalary() { return salary; } Employee(Integer id, String name, Double salary); } | Employee { public Double getSalary() { return salary; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } | Employee { public Double getSalary() { return salary; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } |
@Test public void testAuthenticationNoRememberMe() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user"); params.put("rememberMe", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.authenticate(request, response, params); Cookie accessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(ACCESS_TOKEN_VALUE, accessTokenCookie.getValue()); Cookie refreshTokenCookie = response.getCookie(OAuth2CookieHelper.SESSION_TOKEN_COOKIE); Assert.assertEquals(REFRESH_TOKEN_VALUE, OAuth2CookieHelper.getRefreshTokenValue(refreshTokenCookie)); Assert.assertFalse(OAuth2CookieHelper.isRememberMe(refreshTokenCookie)); } | public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } |
@Test public void testInvalidPassword() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user2"); params.put("rememberMe", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); expectedException.expect(InvalidPasswordException.class); authenticationService.authenticate(request, response, params); } | public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } |
@Test public void testLogout() { MockHttpServletRequest request = new MockHttpServletRequest(); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE, REFRESH_TOKEN_VALUE); request.setCookies(accessTokenCookie, refreshTokenCookie); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.logout(request, response); Cookie newAccessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(0, newAccessTokenCookie.getMaxAge()); Cookie newRefreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(0, newRefreshTokenCookie.getMaxAge()); } | public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } | OAuth2AuthenticationService { public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } } | OAuth2AuthenticationService { public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); } | OAuth2AuthenticationService { public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | OAuth2AuthenticationService { public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } |
@Test public void testStripTokens() { MockHttpServletRequest request = createMockHttpServletRequest(); HttpServletRequest newRequest = authenticationService.stripTokens(request); CookieCollection cookies = new CookieCollection(newRequest.getCookies()); Assert.assertFalse(cookies.contains(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE)); Assert.assertFalse(cookies.contains(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE)); } | public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } | OAuth2AuthenticationService { public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } } | OAuth2AuthenticationService { public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); } | OAuth2AuthenticationService { public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | OAuth2AuthenticationService { public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } |
@Test public void size() throws Exception { CookieCollection cookies = new CookieCollection(); Assert.assertEquals(0, cookies.size()); cookies.add(cookie); Assert.assertEquals(1, cookies.size()); } | @Override public int size() { return cookieMap.size(); } | CookieCollection implements Collection<Cookie> { @Override public int size() { return cookieMap.size(); } } | CookieCollection implements Collection<Cookie> { @Override public int size() { return cookieMap.size(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public int size() { return cookieMap.size(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public int size() { return cookieMap.size(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void isEmpty() throws Exception { CookieCollection cookies = new CookieCollection(); Assert.assertTrue(cookies.isEmpty()); cookies.add(cookie); Assert.assertFalse(cookies.isEmpty()); } | @Override public boolean isEmpty() { return cookieMap.isEmpty(); } | CookieCollection implements Collection<Cookie> { @Override public boolean isEmpty() { return cookieMap.isEmpty(); } } | CookieCollection implements Collection<Cookie> { @Override public boolean isEmpty() { return cookieMap.isEmpty(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean isEmpty() { return cookieMap.isEmpty(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean isEmpty() { return cookieMap.isEmpty(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void contains() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Assert.assertTrue(cookies.contains(cookie)); Assert.assertTrue(cookies.contains(COOKIE_NAME)); Assert.assertFalse(cookies.contains("yuck")); } | @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } | CookieCollection implements Collection<Cookie> { @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } } | CookieCollection implements Collection<Cookie> { @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void iterator() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Iterator<Cookie> it = cookies.iterator(); Assert.assertTrue(it.hasNext()); Assert.assertEquals(cookie, it.next()); Assert.assertFalse(it.hasNext()); } | @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } | CookieCollection implements Collection<Cookie> { @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } } | CookieCollection implements Collection<Cookie> { @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void toArray() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Cookie[] array = cookies.toArray(); Assert.assertEquals(cookies.size(), array.length); Assert.assertEquals(cookie, array[0]); } | public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } | CookieCollection implements Collection<Cookie> { public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } } | CookieCollection implements Collection<Cookie> { public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void add() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Cookie newCookie = new Cookie(BROWNIE_NAME, "mmh"); cookies.add(newCookie); Assert.assertEquals(2, cookies.size()); Assert.assertTrue(cookies.contains(newCookie)); Assert.assertTrue(cookies.contains(BROWNIE_NAME)); } | @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } | CookieCollection implements Collection<Cookie> { @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } } | CookieCollection implements Collection<Cookie> { @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void whenCollectByJoining_thenGetJoinedString() { String empNames = empList.stream() .map(Employee::getName) .collect(Collectors.joining(", ")) .toString(); assertEquals(empNames, "Jeff Bezos, Bill Gates, Mark Zuckerberg"); } | public String toString() { return "Id: " + id + " Name:" + name + " Price:" + salary; } | Employee { public String toString() { return "Id: " + id + " Name:" + name + " Price:" + salary; } } | Employee { public String toString() { return "Id: " + id + " Name:" + name + " Price:" + salary; } Employee(Integer id, String name, Double salary); } | Employee { public String toString() { return "Id: " + id + " Name:" + name + " Price:" + salary; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } | Employee { public String toString() { return "Id: " + id + " Name:" + name + " Price:" + salary; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } |
@Test public void get() { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); Cookie c = cookies.get(COOKIE_NAME); Assert.assertNotNull(c); Assert.assertEquals(cookie, c); } | public Cookie get(String name) { return cookieMap.get(name); } | CookieCollection implements Collection<Cookie> { public Cookie get(String name) { return cookieMap.get(name); } } | CookieCollection implements Collection<Cookie> { public Cookie get(String name) { return cookieMap.get(name); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { public Cookie get(String name) { return cookieMap.get(name); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { public Cookie get(String name) { return cookieMap.get(name); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void remove() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); cookies.remove(cookie); Assert.assertEquals(2, cookies.size()); Assert.assertFalse(cookies.contains(cookie)); Assert.assertFalse(cookies.contains(COOKIE_NAME)); Assert.assertTrue(cookies.contains(brownieCookie)); Assert.assertTrue(cookies.contains(BROWNIE_NAME)); } | @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } | CookieCollection implements Collection<Cookie> { @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } } | CookieCollection implements Collection<Cookie> { @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void containsAll() throws Exception { List<Cookie> content = Arrays.asList(cookie, brownieCookie); CookieCollection cookies = new CookieCollection(content); Assert.assertTrue(cookies.containsAll(content)); Assert.assertTrue(cookies.containsAll(Collections.singletonList(cookie))); Assert.assertFalse(cookies.containsAll(Arrays.asList(cookie, brownieCookie, cupsCookie))); Assert.assertTrue(cookies.containsAll(Arrays.asList(COOKIE_NAME, BROWNIE_NAME))); } | @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } | CookieCollection implements Collection<Cookie> { @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } } | CookieCollection implements Collection<Cookie> { @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test @SuppressWarnings("unchecked") public void addAll() throws Exception { CookieCollection cookies = new CookieCollection(); List<Cookie> content = Arrays.asList(cookie, brownieCookie, cupsCookie); boolean modified = cookies.addAll(content); Assert.assertTrue(modified); Assert.assertEquals(3, cookies.size()); Assert.assertTrue(cookies.containsAll(content)); Assert.assertFalse(cookies.addAll(Collections.EMPTY_LIST)); } | @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } | CookieCollection implements Collection<Cookie> { @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } } | CookieCollection implements Collection<Cookie> { @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void removeAll() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); boolean modified = cookies.removeAll(Arrays.asList(brownieCookie, cupsCookie)); Assert.assertTrue(modified); Assert.assertEquals(1, cookies.size()); Assert.assertFalse(cookies.contains(brownieCookie)); Assert.assertFalse(cookies.contains(cupsCookie)); Assert.assertFalse(cookies.removeAll(Collections.EMPTY_LIST)); } | @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } | CookieCollection implements Collection<Cookie> { @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } } | CookieCollection implements Collection<Cookie> { @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void retainAll() throws Exception { CookieCollection cookies = new CookieCollection(cookie, brownieCookie, cupsCookie); List<Cookie> content = Arrays.asList(cookie, brownieCookie); boolean modified = cookies.retainAll(content); Assert.assertTrue(modified); Assert.assertEquals(2, cookies.size()); Assert.assertTrue(cookies.containsAll(content)); Assert.assertFalse(cookies.contains(cupsCookie)); Assert.assertFalse(cookies.retainAll(content)); } | @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } | CookieCollection implements Collection<Cookie> { @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } } | CookieCollection implements Collection<Cookie> { @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void clear() throws Exception { CookieCollection cookies = new CookieCollection(cookie); cookies.clear(); Assert.assertTrue(cookies.isEmpty()); } | @Override public void clear() { cookieMap.clear(); } | CookieCollection implements Collection<Cookie> { @Override public void clear() { cookieMap.clear(); } } | CookieCollection implements Collection<Cookie> { @Override public void clear() { cookieMap.clear(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); } | CookieCollection implements Collection<Cookie> { @Override public void clear() { cookieMap.clear(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | CookieCollection implements Collection<Cookie> { @Override public void clear() { cookieMap.clear(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } |
@Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); } | @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } | @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } | @Override public void customize(WebServerFactory server) { setMimeMappings(server); setLocationForStaticAssets(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); setLocationForStaticAssets(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); setLocationForStaticAssets(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); setLocationForStaticAssets(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } | WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); setLocationForStaticAssets(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); } |
@Test public void whenStreamGroupingBy_thenGetMap() { Map<Character, List<Employee>> groupByAlphabet = empList.stream().collect( Collectors.groupingBy(e -> new Character(e.getName().charAt(0)))); assertEquals(groupByAlphabet.get('B').get(0).getName(), "Bill Gates"); assertEquals(groupByAlphabet.get('J').get(0).getName(), "Jeff Bezos"); assertEquals(groupByAlphabet.get('M').get(0).getName(), "Mark Zuckerberg"); } | public String getName() { return name; } | Employee { public String getName() { return name; } } | Employee { public String getName() { return name; } Employee(Integer id, String name, Double salary); } | Employee { public String getName() { return name; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } | Employee { public String getName() { return name; } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); } |
@Test public void zeroProfitWhenThereAreNoQualityViolations() { QualityAnalysis analysisWithoutViolations = QualityAnalysis.success(null, Collections.<QualityViolation>emptyList()); QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysisWithoutViolations, "", 100); assertThat(qualityInvestmentPlan.getProfitInMinutes()) .as("When there are no quality violations the overall profit should be zero.") .isZero(); } | 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 profitablePacakgesAndArtefactsShouldBeFilteredProperly() throws IOException { Artefact artefact1 = new Artefact("org.project.test.util.C", "DUMMY"); Artefact artefact2 = new Artefact("org.project.test.util.D", "DUMMY"); Artefact artefact3 = new Artefact("org.project.test.E", "DUMMY"); Artefact artefact4 = new Artefact("org.project.F", "DUMMY"); artefact1.setChangeProbability(0.1); artefact1.setManualEstimate(40); artefact2.setChangeProbability(0.2); artefact2.setManualEstimate(80); artefact3.setChangeProbability(0.0); artefact4.setChangeProbability(0.0); 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, ""); QualityAnalysis analysis = QualityAnalysis.success(project, Arrays.asList(violation1, violation2, violation3, violation4)); when(weightedProfitCalculator.calculateWeightedProfit(violation1)).thenReturn(10.0); when(weightedProfitCalculator.calculateWeightedProfit(violation2)).thenReturn(20.0); when(weightedProfitCalculator.calculateWeightedProfit(violation3)).thenReturn(-10.0); when(weightedProfitCalculator.calculateWeightedProfit(violation4)).thenReturn(-20.0); JsonNode generatedJson = generate(analysis); ArrayNode rootPackagNode = (ArrayNode) generatedJson.get("children"); assertThat(rootPackagNode.get(0).get("changeProbability").asInt()).isEqualTo(60); } | 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 shouldSupportProjectType() { assertThat(validator.supports(Project.class)).isTrue(); } | @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectValidator(ProjectRepository projectRepository,
QualityProfileRepository profileRepository,
SonarConnectionSettingsValidator sonarConnectionSettingsValidator,
ScmConnectionSettingsValidator scmConnectionSettingsValidator,
CodeChangeSettingsValidator codeChangeSettingsValidator); } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectValidator(ProjectRepository projectRepository,
QualityProfileRepository profileRepository,
SonarConnectionSettingsValidator sonarConnectionSettingsValidator,
ScmConnectionSettingsValidator scmConnectionSettingsValidator,
CodeChangeSettingsValidator codeChangeSettingsValidator); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectValidator(ProjectRepository projectRepository,
QualityProfileRepository profileRepository,
SonarConnectionSettingsValidator sonarConnectionSettingsValidator,
ScmConnectionSettingsValidator scmConnectionSettingsValidator,
CodeChangeSettingsValidator codeChangeSettingsValidator); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldNotSupportOtherTypeThanProject() { assertThat(validator.supports(Object.class)).isFalse(); } | @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectValidator(ProjectRepository projectRepository,
QualityProfileRepository profileRepository,
SonarConnectionSettingsValidator sonarConnectionSettingsValidator,
ScmConnectionSettingsValidator scmConnectionSettingsValidator,
CodeChangeSettingsValidator codeChangeSettingsValidator); } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectValidator(ProjectRepository projectRepository,
QualityProfileRepository profileRepository,
SonarConnectionSettingsValidator sonarConnectionSettingsValidator,
ScmConnectionSettingsValidator scmConnectionSettingsValidator,
CodeChangeSettingsValidator codeChangeSettingsValidator); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ProjectValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectValidator(ProjectRepository projectRepository,
QualityProfileRepository profileRepository,
SonarConnectionSettingsValidator sonarConnectionSettingsValidator,
ScmConnectionSettingsValidator scmConnectionSettingsValidator,
CodeChangeSettingsValidator codeChangeSettingsValidator); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldSupportCodeChangeSettingsType() { assertThat(validator.supports(CodeChangeSettings.class)).isTrue(); } | @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldNotSupportOtherTypeThanCodeChangeSettings() { assertThat(validator.supports(Object.class)).isFalse(); } | @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | CodeChangeSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CodeChangeSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldSupportProjectType() { assertThat(validator.supports(Project.class)).isTrue(); } | @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldNotSupportOtherTypeThanProject() { assertThat(validator.supports(Object.class)).isFalse(); } | @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ProjectConnectionsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Project.class.equals(clazz); } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldCallSuppliedProjectValidator() { when(sonarConnectionCheckerService.isReachable(any(SonarConnectionSettings.class))).thenReturn(true); mockAvailableScmSystem(); validateProject(project); verify(projectValidator).validate(any(), any(Errors.class)); } | @Override public void validate(Object target, Errors errors) { ValidationUtils.invokeValidator(projectValidator, target, errors); Project project = (Project) target; if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { errors.rejectValue("sonarConnectionSettings", "sonar.not.reachable"); } try { if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { scmSystemNotAvailable(errors); } } catch (UnsupportedScmSystem e) { scmSystemNotAvailable(errors); } } | ProjectConnectionsValidator implements Validator { @Override public void validate(Object target, Errors errors) { ValidationUtils.invokeValidator(projectValidator, target, errors); Project project = (Project) target; if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { errors.rejectValue("sonarConnectionSettings", "sonar.not.reachable"); } try { if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { scmSystemNotAvailable(errors); } } catch (UnsupportedScmSystem e) { scmSystemNotAvailable(errors); } } } | ProjectConnectionsValidator implements Validator { @Override public void validate(Object target, Errors errors) { ValidationUtils.invokeValidator(projectValidator, target, errors); Project project = (Project) target; if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { errors.rejectValue("sonarConnectionSettings", "sonar.not.reachable"); } try { if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { scmSystemNotAvailable(errors); } } catch (UnsupportedScmSystem e) { scmSystemNotAvailable(errors); } } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); } | ProjectConnectionsValidator implements Validator { @Override public void validate(Object target, Errors errors) { ValidationUtils.invokeValidator(projectValidator, target, errors); Project project = (Project) target; if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { errors.rejectValue("sonarConnectionSettings", "sonar.not.reachable"); } try { if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { scmSystemNotAvailable(errors); } } catch (UnsupportedScmSystem e) { scmSystemNotAvailable(errors); } } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ProjectConnectionsValidator implements Validator { @Override public void validate(Object target, Errors errors) { ValidationUtils.invokeValidator(projectValidator, target, errors); Project project = (Project) target; if (!sonarConnectionCheckerService.isReachable(project.getSonarConnectionSettings())) { errors.rejectValue("sonarConnectionSettings", "sonar.not.reachable"); } try { if (!scmAvailabilityCheckerServiceFactory.create(project.getScmSettings()).isAvailable(project.getScmSettings())) { scmSystemNotAvailable(errors); } } catch (UnsupportedScmSystem e) { scmSystemNotAvailable(errors); } } @Autowired ProjectConnectionsValidator(ProjectValidator projectValidator,
SonarConnectionCheckerService sonarConnectionCheckerService,
ScmAvailabilityCheckerServiceFactory scmAvailabilityCheckerServiceFactory); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldSupportScmConnectionSettingsType() { assertThat(validator.supports(ScmConnectionSettings.class)).isTrue(); } | @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldNotSupportOtherTypeThanScmConnectionSettings() { assertThat(validator.supports(Object.class)).isFalse(); } | @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } | ScmConnectionSettingsValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return ScmConnectionSettings.class.equals(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); } |
@Test public void shouldGenerateInvestmentPlanForOneArtefact() { QualityViolation violation1 = new QualityViolation(new Artefact("org.project.A", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cc", "<", 5.0)), 50, 0, 0.0, "ncloc"); QualityViolation violation2 = new QualityViolation(new Artefact("org.project.AB", ""), createRequirementOnlyWithCriteria(new QualityCriteria("rfc", "<=", 50.0)), 50, 0, 0.0, "ncloc"); QualityViolation violation3 = new QualityViolation(new Artefact("org.project.ABC", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cov", ">", 80.0)), 10, 0, 0.0, "ncloc"); analysis = QualityAnalysis.success(null, Arrays.asList(violation1, violation2, violation3)); when(profitCalculator.calculateProfit(violation1)).thenReturn(100.0); QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "org.project.A", 50); assertThat(qualityInvestmentPlan.getEntries()).hasSize(1); assertThat(qualityInvestmentPlan.getEntries().iterator().next().getArtefactLongName()).isEqualTo("org.project.A"); } | 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 shouldGenerateInvestmentPlanForOneSubPackage() { QualityViolation violation1 = new QualityViolation(new Artefact("org.project.a.test.A", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cc", "<", 5.0)), 50, 0, 0.0, "ncloc"); QualityViolation violation2 = new QualityViolation(new Artefact("org.project.b.B", ""), createRequirementOnlyWithCriteria(new QualityCriteria("rfc", "<=", 50.0)), 50, 0, 0.0, "ncloc"); QualityViolation violation3 = new QualityViolation(new Artefact("org.project.C", ""), createRequirementOnlyWithCriteria(new QualityCriteria("cov", ">", 80.0)), 10, 0, 0.0, "ncloc"); analysis = QualityAnalysis.success(null, Arrays.asList(violation1, violation2, violation3)); when(profitCalculator.calculateProfit(violation1)).thenReturn(100.0); QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "org.project.a.test.A", 50); assertThat(qualityInvestmentPlan.getEntries()).hasSize(1); assertThat(qualityInvestmentPlan.getEntries().iterator().next().getArtefactLongName()).isEqualTo("org.project.a.test.A"); } | 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 emptyStringShouldBeParsedToZeroMinutes() throws InvestmentParsingException { assertThat(parser.parseMinutes("")).isEqualTo(0); } | public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } |
@Test public void shouldParseHoursProperly() throws InvestmentParsingException { assertThat(parser.parseMinutes("3h")).isEqualTo(180); } | public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } |
@Test public void shouldParseMinutesProperly() throws InvestmentParsingException { assertThat(parser.parseMinutes("21m")).isEqualTo(21); } | public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } |
@Test public void shouldParseHoursAndMinutesProperly() throws InvestmentParsingException { assertThat(parser.parseMinutes("3h 70m")).isEqualTo(250); } | public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } |
@Test(expected = InvestmentParsingException.class) public void shouldThrowExceptionWhenGivenStringIsNotParsable() throws InvestmentParsingException { parser.parseMinutes("abc0m"); } | public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } | InvestmentAmountParser { public int parseMinutes(String formattedInvestmentAmount) throws InvestmentParsingException { if (formattedInvestmentAmount.isEmpty()) { return 0; } Pattern pattern = Pattern.compile("(\\d*h)?\\s?(\\d*m)?"); Matcher matcher = pattern.matcher(formattedInvestmentAmount); int minutes = 0; if (!matcher.find()) { throw new InvestmentParsingException(); } String[] timeValues = matcher.group().split("\\s"); minutes += getMinutesFor(timeValues[0]); if (timeValues.length > 1) { minutes += getMinutesFor(timeValues[1]); } return minutes; } int parseMinutes(String formattedInvestmentAmount); } |
@Test public void profitForAutomaticFixableViolation() { when(requirement.isAutomaticallyFixable()).thenReturn(true); assertThat(calculator.calculateProfit(violation)).isEqualTo(2.0); } | public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } double calculateProfit(QualityViolation violation); } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } double calculateProfit(QualityViolation violation); } |
@Test public void profitForNotAutomaticFixableViolation() { when(requirement.isAutomaticallyFixable()).thenReturn(false); when(artefact.getSecureChangeProbability()).thenReturn(1.1); assertThat(calculator.calculateProfit(violation)).isEqualTo(1.0); } | public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } double calculateProfit(QualityViolation violation); } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } double calculateProfit(QualityViolation violation); } |
@Test public void profitForViolationWhereArtefactHasManualEstimate() { when(requirement.isAutomaticallyFixable()).thenReturn(true); when(artefact.getManualEstimate()).thenReturn(80); when(artefact.hasManualEstimate()).thenReturn(true); assertThat(calculator.calculateProfit(violation)).isEqualTo(6.0); } | public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } double calculateProfit(QualityViolation violation); } | ProfitCalculator { public double calculateProfit(QualityViolation violation) { double nonRemediationCosts = violation.getNonRemediationCosts() * (violation.getArtefact().hasManualEstimate() ? violation.getArtefact().getManualEstimate() / 100.0 : violation.getArtefact().getChangeProbability()); return violation.getRequirement().isAutomaticallyFixable() ? nonRemediationCosts - violation.getRemediationCosts() : nonRemediationCosts - violation.getRemediationCosts() * violation.getArtefact().getSecureChangeProbability(); } double calculateProfit(QualityViolation violation); } |
@Test public void calculatesOverallProfitForAllQualityViolations() { QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 80); assertThat(qualityInvestmentPlan.getProfitInMinutes()) .as("The overall profit should be calculated based on all quality violations.") .isEqualTo(300); assertThat(qualityInvestmentPlan.getInvestmentInMinutes()).isEqualTo(80); } | 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 shouldDivideProfitOfViolationByWeightingMetricValue() { ProfitCalculator profitCalculator = mock(ProfitCalculator.class); when(profitCalculator.calculateProfit(any(QualityViolation.class))).thenReturn(20.0); QualityViolation violation = mock(QualityViolation.class); when(violation.getWeightingMetricValue()).thenReturn(13.0); WeightedProfitCalculator weightedProfitCalculator = new WeightedProfitCalculator(profitCalculator); assertThat(weightedProfitCalculator.calculateWeightedProfit(violation)).isEqualTo(1.54, Delta.delta(0.01)); } | public double calculateWeightedProfit(QualityViolation violation) { return profitCalculator.calculateProfit(violation) / violation.getWeightingMetricValue(); } | WeightedProfitCalculator { public double calculateWeightedProfit(QualityViolation violation) { return profitCalculator.calculateProfit(violation) / violation.getWeightingMetricValue(); } } | WeightedProfitCalculator { public double calculateWeightedProfit(QualityViolation violation) { return profitCalculator.calculateProfit(violation) / violation.getWeightingMetricValue(); } @Autowired WeightedProfitCalculator(ProfitCalculator profitCalculator); } | WeightedProfitCalculator { public double calculateWeightedProfit(QualityViolation violation) { return profitCalculator.calculateProfit(violation) / violation.getWeightingMetricValue(); } @Autowired WeightedProfitCalculator(ProfitCalculator profitCalculator); double calculateWeightedProfit(QualityViolation violation); } | WeightedProfitCalculator { public double calculateWeightedProfit(QualityViolation violation) { return profitCalculator.calculateProfit(violation) / violation.getWeightingMetricValue(); } @Autowired WeightedProfitCalculator(ProfitCalculator profitCalculator); double calculateWeightedProfit(QualityViolation violation); } |
@Test public void codeChurnForOneLastCommit() throws CodeChurnCalculationException, ScmConnectionEncodingException { fakeCodeChurnCalculator.addCodeChurnWithoutDay("A", new CodeChurn(Arrays.asList(0.8))); CodeChangeProbabilityCalculator codeChangeProbabilityCalculator = new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, 1); assertThat(codeChangeProbabilityCalculator.calculateCodeChangeProbability(dummyConnectionSettings, "A")).isEqualTo(0.8); } | @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); @Override double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); @Override double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file); } |
@Test public void codeChurnForManyLastCommits() throws CodeChurnCalculationException, ScmConnectionEncodingException { fakeCodeChurnCalculator.addCodeChurnWithoutDay("A", new CodeChurn(Arrays.asList(0.8))); fakeCodeChurnCalculator.addCodeChurnWithoutDay("A", new CodeChurn(Arrays.asList(1.0))); fakeCodeChurnCalculator.addCodeChurnWithoutDay("A", new CodeChurn(Arrays.asList(0.2))); CodeChangeProbabilityCalculator codeChangeProbabilityCalculator = new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, 4); assertThat(codeChangeProbabilityCalculator.calculateCodeChangeProbability(dummyConnectionSettings, "A")).isEqualTo(0.5); } | @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); @Override double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); @Override double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file); } |
@Test public void maxPossibleProbabilityShouldBeOne() throws CodeChurnCalculationException, ScmConnectionEncodingException { fakeCodeChurnCalculator.addCodeChurnWithoutDay("A", new CodeChurn(Arrays.asList(10.0))); CodeChangeProbabilityCalculator codeChangeProbabilityCalculator = new CommitBasedCodeChangeProbabilityCalculator(codeChurnCalculatorFactory, 1); assertThat(codeChangeProbabilityCalculator.calculateCodeChangeProbability(dummyConnectionSettings, "A")).isEqualTo(1.0); } | @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); @Override double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file); } | CommitBasedCodeChangeProbabilityCalculator implements CodeChangeProbabilityCalculator { @Override public double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file) throws CodeChurnCalculationException, ScmConnectionEncodingException { log.info("Calculate code change probability for file {}", file); final CodeChurnCalculator codeChurnCalculator = codeChurnCalculatorFactory.create(connectionSettings); CodeChurn codeChurn = codeChurnCalculator.calculateCodeChurnForLastCommits(connectionSettings, file, numberOfCommits); double changeProbability = 0.0; for (Double codeChurnProportion : codeChurn.getCodeChurnProportions()) { changeProbability += codeChurnProportion * (1 / (double) numberOfCommits); } return Math.min(1.0, changeProbability); } CommitBasedCodeChangeProbabilityCalculator(CodeChurnCalculatorFactory codeChurnCalculatorFactory, int numberOfCommits); @Override double calculateCodeChangeProbability(ScmConnectionSettings connectionSettings, String file); } |
@Test(expected = UnsupportedScmSystem.class) public void shouldFailForNotSupportedSvmTypesWithException() { ScmConnectionSettings connectionSettings = mock(ScmConnectionSettings.class); when(connectionSettings.getType()).thenReturn(Integer.MAX_VALUE); codeChurnCalculatorFactory.create(connectionSettings); } | public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } @Autowired CodeChurnCalculatorFactory(SvnCodeChurnCalculatorService svnCodeChurnCalculator); } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } @Autowired CodeChurnCalculatorFactory(SvnCodeChurnCalculatorService svnCodeChurnCalculator); CodeChurnCalculator create(ScmConnectionSettings connectionSettings); } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } @Autowired CodeChurnCalculatorFactory(SvnCodeChurnCalculatorService svnCodeChurnCalculator); CodeChurnCalculator create(ScmConnectionSettings connectionSettings); } |
@Test public void createSvnCodeChurnCalculatorForSvnType() { ScmConnectionSettings connectionSettings = mock(ScmConnectionSettings.class); when(connectionSettings.getType()).thenReturn(SupportedScmSystem.SVN.getType()); assertThat(codeChurnCalculatorFactory.create(connectionSettings)).isInstanceOf(SvnCodeChurnCalculatorService.class); } | public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } @Autowired CodeChurnCalculatorFactory(SvnCodeChurnCalculatorService svnCodeChurnCalculator); } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } @Autowired CodeChurnCalculatorFactory(SvnCodeChurnCalculatorService svnCodeChurnCalculator); CodeChurnCalculator create(ScmConnectionSettings connectionSettings); } | CodeChurnCalculatorFactory { public CodeChurnCalculator create(ScmConnectionSettings connectionSettings) { if (connectionSettings.getType() == SupportedScmSystem.SVN.getType()) { return svnCodeChurnCalculator; } throw new UnsupportedScmSystem(); } @Autowired CodeChurnCalculatorFactory(SvnCodeChurnCalculatorService svnCodeChurnCalculator); CodeChurnCalculator create(ScmConnectionSettings connectionSettings); } |
@Test public void notAvailableWhenScmSettingsAreNull() { assertThat(availabilityCheckerService.isAvailable(null)).isFalse(); } | @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } @Override boolean isAvailable(ScmConnectionSettings connectionSettings); } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } @Override boolean isAvailable(ScmConnectionSettings connectionSettings); } |
@Test public void notAvailableWhenUrlOfScmSettingsIsNull() { assertThat(availabilityCheckerService.isAvailable(new ScmConnectionSettings(null))).isFalse(); } | @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } @Override boolean isAvailable(ScmConnectionSettings connectionSettings); } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } @Override boolean isAvailable(ScmConnectionSettings connectionSettings); } |
@Test public void notAvailableWhenUrlOfScmSettingsIsEmpty() { assertThat(availabilityCheckerService.isAvailable(new ScmConnectionSettings(""))).isFalse(); } | @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } @Override boolean isAvailable(ScmConnectionSettings connectionSettings); } | SvnServerAvailabilityCheckerService implements ScmAvailabilityCheckerService { @Override public boolean isAvailable(ScmConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } try { SvnRepositoryFactory.create(connectionSettings).testConnection(); log.info("The given svn server is reachable with connection settings: {}", connectionSettings); return true; } catch (SVNException e) { log.warn("The given svn server is not reachable during connection check.", e); return false; } } @Override boolean isAvailable(ScmConnectionSettings connectionSettings); } |
@Test public void shouldParseFilePartOutOfOldPathProperly() throws SVNException { ScmConnectionSettings connectionSettings = new ScmConnectionSettings("http: SvnFileRevision fileRevision = new SvnFileRevision(0L, "/commons/proper/configuration/trunk/src/main/java/org/apache/commons/configuration/reloading/ManagedReloadingStrategy.java", null); assertThat(fileRevision.getFilePartOfOldPath(connectionSettings)).isEqualTo("org/apache/commons/configuration/reloading/ManagedReloadingStrategy.java"); } | String getFilePartOfOldPath(ScmConnectionSettings connectionSettings) throws SVNException { SVNURL svnurl = SVNURL.parseURIEncoded(connectionSettings.getUrl()); List<String> splittedBasePath = splitUrl(svnurl.getPath()); List<String> splittedOldPath = splitUrl(oldPath); int i = 0; boolean foundBeginningOfSomeCommonParts = false; for (String s : splittedBasePath) { if (!foundBeginningOfSomeCommonParts && s.equalsIgnoreCase(splittedOldPath.get(0))) { foundBeginningOfSomeCommonParts = true; } if (foundBeginningOfSomeCommonParts) { i++; } } StringBuilder filePart = new StringBuilder(); boolean isFirst = true; for (; i < splittedOldPath.size(); i++) { if (!isFirst) { filePart.append('/'); } filePart.append(splittedOldPath.get(i)); isFirst = false; } return filePart.toString(); } | SvnFileRevision { String getFilePartOfOldPath(ScmConnectionSettings connectionSettings) throws SVNException { SVNURL svnurl = SVNURL.parseURIEncoded(connectionSettings.getUrl()); List<String> splittedBasePath = splitUrl(svnurl.getPath()); List<String> splittedOldPath = splitUrl(oldPath); int i = 0; boolean foundBeginningOfSomeCommonParts = false; for (String s : splittedBasePath) { if (!foundBeginningOfSomeCommonParts && s.equalsIgnoreCase(splittedOldPath.get(0))) { foundBeginningOfSomeCommonParts = true; } if (foundBeginningOfSomeCommonParts) { i++; } } StringBuilder filePart = new StringBuilder(); boolean isFirst = true; for (; i < splittedOldPath.size(); i++) { if (!isFirst) { filePart.append('/'); } filePart.append(splittedOldPath.get(i)); isFirst = false; } return filePart.toString(); } } | SvnFileRevision { String getFilePartOfOldPath(ScmConnectionSettings connectionSettings) throws SVNException { SVNURL svnurl = SVNURL.parseURIEncoded(connectionSettings.getUrl()); List<String> splittedBasePath = splitUrl(svnurl.getPath()); List<String> splittedOldPath = splitUrl(oldPath); int i = 0; boolean foundBeginningOfSomeCommonParts = false; for (String s : splittedBasePath) { if (!foundBeginningOfSomeCommonParts && s.equalsIgnoreCase(splittedOldPath.get(0))) { foundBeginningOfSomeCommonParts = true; } if (foundBeginningOfSomeCommonParts) { i++; } } StringBuilder filePart = new StringBuilder(); boolean isFirst = true; for (; i < splittedOldPath.size(); i++) { if (!isFirst) { filePart.append('/'); } filePart.append(splittedOldPath.get(i)); isFirst = false; } return filePart.toString(); } } | SvnFileRevision { String getFilePartOfOldPath(ScmConnectionSettings connectionSettings) throws SVNException { SVNURL svnurl = SVNURL.parseURIEncoded(connectionSettings.getUrl()); List<String> splittedBasePath = splitUrl(svnurl.getPath()); List<String> splittedOldPath = splitUrl(oldPath); int i = 0; boolean foundBeginningOfSomeCommonParts = false; for (String s : splittedBasePath) { if (!foundBeginningOfSomeCommonParts && s.equalsIgnoreCase(splittedOldPath.get(0))) { foundBeginningOfSomeCommonParts = true; } if (foundBeginningOfSomeCommonParts) { i++; } } StringBuilder filePart = new StringBuilder(); boolean isFirst = true; for (; i < splittedOldPath.size(); i++) { if (!isFirst) { filePart.append('/'); } filePart.append(splittedOldPath.get(i)); isFirst = false; } return filePart.toString(); } } | SvnFileRevision { String getFilePartOfOldPath(ScmConnectionSettings connectionSettings) throws SVNException { SVNURL svnurl = SVNURL.parseURIEncoded(connectionSettings.getUrl()); List<String> splittedBasePath = splitUrl(svnurl.getPath()); List<String> splittedOldPath = splitUrl(oldPath); int i = 0; boolean foundBeginningOfSomeCommonParts = false; for (String s : splittedBasePath) { if (!foundBeginningOfSomeCommonParts && s.equalsIgnoreCase(splittedOldPath.get(0))) { foundBeginningOfSomeCommonParts = true; } if (foundBeginningOfSomeCommonParts) { i++; } } StringBuilder filePart = new StringBuilder(); boolean isFirst = true; for (; i < splittedOldPath.size(); i++) { if (!isFirst) { filePart.append('/'); } filePart.append(splittedOldPath.get(i)); isFirst = false; } return filePart.toString(); } } |
@Test public void whenInvestmentIsBiggerThanPossibleOverallProfitOnlyThePossibleProfitShouldBeCalculated() { QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 100); assertThat(qualityInvestmentPlan.getProfitInMinutes()).isEqualTo(300); assertThat(qualityInvestmentPlan.getInvestmentInMinutes()).isEqualTo(80); } | 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 countLinesWithSuppliedSeparator() { assertThat(new SvnFile("1a2a3", "a").countLines()).isEqualTo(3); } | int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } |
@Test public void shouldNotFailOnEmptyText() { assertThat(new SvnFile("", "a").countLines()).isEqualTo(0); } | int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } |
@Test public void countLineCorrectlyWhenSeparatorConsistsOfManyCharacters() { assertThat(new SvnFile("111abc222abc333", "abc").countLines()).isEqualTo(3); } | int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } | SvnFile { int countLines() { if (content.isEmpty()) { return 0; } return content.split(lineSeparator).length; } SvnFile(String content, String lineSeparator); } |
@Test public void A_is_sorted_before_B() { assertThat(A.compareTo(B)).isEqualTo(comesBefore); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void a_is_sorted_before_B() { assertThat(a.compareTo(B)).isEqualTo(comesBefore); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void B_is_sorted_after_A() { assertThat(B.compareTo(A)).isEqualTo(comesAfter); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void A_and_a_are_the_same() { assertThat(a.compareTo(A)).isEqualTo(areTheSame); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void compared_to_null_is_the_same() { assertThat(B.compareTo(null)).isEqualTo(comesAfter); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void compared_to_null_name_is_sorted_after() { assertThat(B.compareTo(nullName)).isEqualTo(comesAfter); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void compared__valid_projectInfo_to_null_is_sorted_after() { assertThat(nullName.compareTo(A)).isEqualTo(comesAfter); } | @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } | ProjectInformation implements Comparable { @Override public int compareTo(Object o) { if (o != null) { ProjectInformation otherProjectInformation = (ProjectInformation) o; if (otherProjectInformation.getName() != null && this.getName() != null) { return this.name.compareToIgnoreCase(otherProjectInformation.getName()); } } return 1; } ProjectInformation(); ProjectInformation(String name, String resourceKey); @Override int compareTo(Object o); } |
@Test public void whenInvestmentIsSmallerThanPossibleOverallProfitOnlyTheInvestedAmountShouldBeCalculated() { QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 35); assertThat(qualityInvestmentPlan.getProfitInMinutes()).isEqualTo(220); assertThat(qualityInvestmentPlan.getInvestmentInMinutes()).isEqualTo(20); } | 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(expected = IllegalArgumentException.class) public void shouldFailWhenConnectionSettingsMissProjectAttribute() throws ResourceNotFoundException { new MetricCollectorService().collectMetricForResource(new SonarConnectionSettings("dummy"), "", ""); } | public double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier) throws ResourceNotFoundException { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect metric value for a resource with connection settings that has a project"); } Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); Resource resource = sonar.find(ResourceQuery.create(resourceKey).setMetrics(metricIdentifier)); if (resource == null) { log.debug("Could not find measurement for metric {} at resource {}", metricIdentifier, resourceKey); return DEFAULT_VALUE; } Double metricValue = resource.getMeasureValue(metricIdentifier); if (metricValue == null) { log.error("Metric identifier " + metricIdentifier + " is not supported by the given Sonar server at " + connectionSettings.toString()); throw new ResourceNotFoundException("Could not find metric with identifier: " + metricIdentifier); } log.debug("{} = {} for {}", metricIdentifier, metricValue, resourceKey); return metricValue; } | MetricCollectorService { public double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier) throws ResourceNotFoundException { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect metric value for a resource with connection settings that has a project"); } Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); Resource resource = sonar.find(ResourceQuery.create(resourceKey).setMetrics(metricIdentifier)); if (resource == null) { log.debug("Could not find measurement for metric {} at resource {}", metricIdentifier, resourceKey); return DEFAULT_VALUE; } Double metricValue = resource.getMeasureValue(metricIdentifier); if (metricValue == null) { log.error("Metric identifier " + metricIdentifier + " is not supported by the given Sonar server at " + connectionSettings.toString()); throw new ResourceNotFoundException("Could not find metric with identifier: " + metricIdentifier); } log.debug("{} = {} for {}", metricIdentifier, metricValue, resourceKey); return metricValue; } } | MetricCollectorService { public double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier) throws ResourceNotFoundException { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect metric value for a resource with connection settings that has a project"); } Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); Resource resource = sonar.find(ResourceQuery.create(resourceKey).setMetrics(metricIdentifier)); if (resource == null) { log.debug("Could not find measurement for metric {} at resource {}", metricIdentifier, resourceKey); return DEFAULT_VALUE; } Double metricValue = resource.getMeasureValue(metricIdentifier); if (metricValue == null) { log.error("Metric identifier " + metricIdentifier + " is not supported by the given Sonar server at " + connectionSettings.toString()); throw new ResourceNotFoundException("Could not find metric with identifier: " + metricIdentifier); } log.debug("{} = {} for {}", metricIdentifier, metricValue, resourceKey); return metricValue; } } | MetricCollectorService { public double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier) throws ResourceNotFoundException { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect metric value for a resource with connection settings that has a project"); } Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); Resource resource = sonar.find(ResourceQuery.create(resourceKey).setMetrics(metricIdentifier)); if (resource == null) { log.debug("Could not find measurement for metric {} at resource {}", metricIdentifier, resourceKey); return DEFAULT_VALUE; } Double metricValue = resource.getMeasureValue(metricIdentifier); if (metricValue == null) { log.error("Metric identifier " + metricIdentifier + " is not supported by the given Sonar server at " + connectionSettings.toString()); throw new ResourceNotFoundException("Could not find metric with identifier: " + metricIdentifier); } log.debug("{} = {} for {}", metricIdentifier, metricValue, resourceKey); return metricValue; } double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier); } | MetricCollectorService { public double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier) throws ResourceNotFoundException { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect metric value for a resource with connection settings that has a project"); } Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); Resource resource = sonar.find(ResourceQuery.create(resourceKey).setMetrics(metricIdentifier)); if (resource == null) { log.debug("Could not find measurement for metric {} at resource {}", metricIdentifier, resourceKey); return DEFAULT_VALUE; } Double metricValue = resource.getMeasureValue(metricIdentifier); if (metricValue == null) { log.error("Metric identifier " + metricIdentifier + " is not supported by the given Sonar server at " + connectionSettings.toString()); throw new ResourceNotFoundException("Could not find metric with identifier: " + metricIdentifier); } log.debug("{} = {} for {}", metricIdentifier, metricValue, resourceKey); return metricValue; } double collectMetricForResource(SonarConnectionSettings connectionSettings, String resourceKey, String metricIdentifier); } |
@Test(expected = IllegalArgumentException.class) public void shouldFailWhenConnectionSettingsMissProjectAttribute() { new ResourcesCollectorService().collectAllResourcesForProject(new SonarConnectionSettings("dummy")); } | public Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings) { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect resources with connection settings that has a project"); } log.info("Start collecting all classes for project {} at Sonar server", connectionSettings.getProject()); Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); List<Resource> resources = sonar.findAll(ResourceQuery.create(connectionSettings.getProject()) .setAllDepths() .setScopes("FIL") .setQualifiers("FIL")); log.info("Found {} classes for project {}", resources.size(), connectionSettings.getProject()); return resources; } | ResourcesCollectorService { public Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings) { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect resources with connection settings that has a project"); } log.info("Start collecting all classes for project {} at Sonar server", connectionSettings.getProject()); Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); List<Resource> resources = sonar.findAll(ResourceQuery.create(connectionSettings.getProject()) .setAllDepths() .setScopes("FIL") .setQualifiers("FIL")); log.info("Found {} classes for project {}", resources.size(), connectionSettings.getProject()); return resources; } } | ResourcesCollectorService { public Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings) { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect resources with connection settings that has a project"); } log.info("Start collecting all classes for project {} at Sonar server", connectionSettings.getProject()); Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); List<Resource> resources = sonar.findAll(ResourceQuery.create(connectionSettings.getProject()) .setAllDepths() .setScopes("FIL") .setQualifiers("FIL")); log.info("Found {} classes for project {}", resources.size(), connectionSettings.getProject()); return resources; } } | ResourcesCollectorService { public Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings) { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect resources with connection settings that has a project"); } log.info("Start collecting all classes for project {} at Sonar server", connectionSettings.getProject()); Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); List<Resource> resources = sonar.findAll(ResourceQuery.create(connectionSettings.getProject()) .setAllDepths() .setScopes("FIL") .setQualifiers("FIL")); log.info("Found {} classes for project {}", resources.size(), connectionSettings.getProject()); return resources; } Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings); } | ResourcesCollectorService { public Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings) { if (!connectionSettings.hasProject()) { throw new IllegalArgumentException("you can only collect resources with connection settings that has a project"); } log.info("Start collecting all classes for project {} at Sonar server", connectionSettings.getProject()); Sonar sonar = new Sonar(new HttpClient4Connector(connectionSettings.asHostObject())); List<Resource> resources = sonar.findAll(ResourceQuery.create(connectionSettings.getProject()) .setAllDepths() .setScopes("FIL") .setQualifiers("FIL")); log.info("Found {} classes for project {}", resources.size(), connectionSettings.getProject()); return resources; } Collection<Resource> collectAllResourcesForProject(SonarConnectionSettings connectionSettings); } |
@Test public void notReachableWhenConnectionSettingsAreNull() { assertThat(sonarConnectionCheckerService.isReachable(null)).isFalse(); } | public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } boolean isReachable(SonarConnectionSettings connectionSettings); } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } boolean isReachable(SonarConnectionSettings connectionSettings); } |
@Test public void notReachableWhenUrlOfConnectionSettingsIsNull() { assertThat(sonarConnectionCheckerService.isReachable(new SonarConnectionSettings(null))).isFalse(); } | public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } boolean isReachable(SonarConnectionSettings connectionSettings); } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } boolean isReachable(SonarConnectionSettings connectionSettings); } |
@Test public void notReachableWhenUrlOfConnectionSettingsIsEmpty() { assertThat(sonarConnectionCheckerService.isReachable(new SonarConnectionSettings(""))).isFalse(); } | public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } boolean isReachable(SonarConnectionSettings connectionSettings); } | SonarConnectionCheckerService { public boolean isReachable(SonarConnectionSettings connectionSettings) { if (connectionSettings == null || Strings.isNullOrEmpty(connectionSettings.getUrl())) { return false; } HttpClient4Connector connector = new HttpClient4Connector(connectionSettings.asHostObject()); try { return connector.getHttpClient() .execute(new HttpGet(connectionSettings.getUrl() + "/api/metrics")).getStatusLine().getStatusCode() == OK; } catch (IOException e) { log.info("Sonar is not reachable during connection check.", e); return false; } } boolean isReachable(SonarConnectionSettings connectionSettings); } |
@Test public void succeededAnalysisWithOneViolation() throws CodeChurnCalculationException, ScmConnectionEncodingException { Artefact artefact = new Artefact("A", "A"); QualityAnalyzerService qualityAnalyzerService = createMockedSystemWithArtefactsAndViolations( Arrays.asList(new ViolationOccurence(firstRequirement, artefact, 12))); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThatIsSuccessfulAndContainsOnlyGivenViolationsWithoutCostsComparison(analysis, new QualityViolation(artefact, firstRequirement, 0, 0, 12, "nloc")); } | @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 succeededAnalysisWithManyViolations() throws CodeChurnCalculationException, ScmConnectionEncodingException { Artefact artefactA = new Artefact("A", "A"); Artefact artefactB = new Artefact("B", "B"); Artefact artefactC = new Artefact("C", "C"); QualityAnalyzerService qualityAnalyzerService = createMockedSystemWithArtefactsAndViolations( Arrays.asList(new ViolationOccurence(firstRequirement, artefactA, 12), new ViolationOccurence(secondRequirement, artefactA, 1), new ViolationOccurence(firstRequirement, artefactB, 22), new ViolationOccurence(firstRequirement, artefactC, 45), new ViolationOccurence(secondRequirement, artefactC, 67))); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThatIsSuccessfulAndContainsOnlyGivenViolationsWithoutCostsComparison(analysis, new QualityViolation(artefactA, firstRequirement, 0, 0, 12, "nloc"), new QualityViolation(artefactA, secondRequirement, 0, 0, 1, "nloc"), new QualityViolation(artefactB, firstRequirement, 0, 0, 22, "nloc"), new QualityViolation(artefactC, firstRequirement, 0, 0, 45, "nloc"), new QualityViolation(artefactC, secondRequirement, 0, 0, 67, "nloc")); } | @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 addCodeChangeProbabilityToArtefacts() throws CodeChurnCalculationException, ScmConnectionEncodingException, ResourceNotFoundException { Artefact artefactA = new Artefact("A", "A"); Artefact artefactB = new Artefact("B", "B"); ViolationOccurence violationA = new ViolationOccurence(firstRequirement, artefactA, 0); ViolationOccurence violationB = new ViolationOccurence(firstRequirement, artefactB, 0); ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Arrays.asList(violationA, violationB))); CodeChangeProbabilityCalculator codeChangeProbabilityCalculator = mock(CodeChangeProbabilityCalculator.class); when(codeChangeProbabilityCalculator.calculateCodeChangeProbability(any(ScmConnectionSettings.class), anyString())).thenReturn(1.2); CodeChangeProbabilityCalculatorFactory codeChangeProbabilityCalculatorFactory = createMockedCodeChangeProbabilityCalculatorFactory(); when(codeChangeProbabilityCalculatorFactory.create(any(CodeChangeSettings.class))).thenReturn(codeChangeProbabilityCalculator); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, scmAvailabilityCheckerServiceFactory, codeChangeProbabilityCalculatorFactory, secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); qualityAnalyzerService.analyzeProject(project); assertThat(artefactA.getChangeProbability()).isEqualTo(1.2); assertThat(artefactB.getChangeProbability()).isEqualTo(1.2); } | @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 addSecureChangeProbabilityToArtefacts() throws CodeChurnCalculationException, ScmConnectionEncodingException, ResourceNotFoundException { Artefact artefactA = new Artefact("A", "A"); Artefact artefactB = new Artefact("B", "B"); ViolationOccurence violationA = new ViolationOccurence(firstRequirement, artefactA, 0); ViolationOccurence violationB = new ViolationOccurence(firstRequirement, artefactB, 0); ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Arrays.asList(violationA, violationB))); 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(secureChangeProbabilityCalculator.calculateSecureChangeProbability(any(QualityProfile.class), any(SonarConnectionSettings.class), eq(artefactA))).thenReturn(1.115); when(secureChangeProbabilityCalculator.calculateSecureChangeProbability(any(QualityProfile.class), any(SonarConnectionSettings.class), eq(artefactB))).thenReturn(1.341); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, scmAvailabilityCheckerServiceFactory, codeChangeProbabilityCalculatorFactory, secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); qualityAnalyzerService.analyzeProject(project); assertThat(artefactA.getSecureChangeProbability()).isEqualTo(1.115); assertThat(artefactB.getSecureChangeProbability()).isEqualTo(1.341); } | @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 failedAnalysisWhenSecureChangeProbabilityCalculatorThrowsResourceNotFoundException() throws CodeChurnCalculationException, ScmConnectionEncodingException, ResourceNotFoundException { ViolationOccurence violation = new ViolationOccurence(firstRequirement, new Artefact("A", "A"), 0); ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Arrays.asList(violation))); 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(secureChangeProbabilityCalculator.calculateSecureChangeProbability(any(QualityProfile.class), any(SonarConnectionSettings.class), any(Artefact.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 calculatesRoiBasedOnRemediationCostsAndProfit() { QualityInvestmentPlan qualityInvestmentPlan = investmentPlanService.computeInvestmentPlan(analysis, "", 80); assertThat(qualityInvestmentPlan.getRoi()).isEqualTo(375); } | 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 takeCostsFromSuppliedCostCalculator() throws CodeChurnCalculationException, ScmConnectionEncodingException, ResourceNotFoundException { ViolationOccurence violation = new ViolationOccurence(firstRequirement, new Artefact("A", "A"), 0); ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createSuccessfulAnalysis(Arrays.asList(violation))); 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); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, scmAvailabilityCheckerServiceFactory, codeChangeProbabilityCalculatorFactory, secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); qualityAnalyzerService.analyzeProject(project); verify(costsCalculator).calculateRemediationCosts(project.getSonarConnectionSettings(), violation); verify(costsCalculator).calculateNonRemediationCosts(project.getSonarConnectionSettings(), violation); } | @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 failedAnalysisWhenViolationAnalysisWasNotSuccessful() throws CodeChurnCalculationException, ScmConnectionEncodingException { ViolationsCalculatorService violationsCalculatorService = mock(ViolationsCalculatorService.class); when(violationsCalculatorService.calculateAllViolation(any(Project.class))) .thenReturn(ViolationsAnalysisResult.createFailedAnalysis(Collections.<ViolationOccurence>emptyList(), "error")); QualityAnalyzerService qualityAnalyzerService = new DefaultQualityAnalyzerService(violationsCalculatorService, scmAvailabilityCheckerServiceFactory, mock(CodeChangeProbabilityCalculatorFactory.class), secureChangeProbabilityCalculator, costsCalculator, qualityAnalysisRepository); QualityAnalysis analysis = qualityAnalyzerService.analyzeProject(project); assertThat(analysis.isSuccessful()).isFalse(); assertThat(analysis.getFailureReason()).isEqualTo("error"); } | @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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.