UpgradeService { @PostConstruct void sortAndCheckTasks() { Collections.sort(tasks); Map<String, List<Integer>> groupTasks = new HashMap<>(); List<UpgradeTaskId> conflictTasks = new ArrayList<>(); tasks.stream().map(UpgradeTask::getId).forEach(id -> { if (!groupTasks.containsKey(id.getVersion())) { groupTasks.put(id.getVersion(), new ArrayList<>()); } final List<Integer> orders = groupTasks.get(id.getVersion()); if (orders.contains(id.getOrder())) { conflictTasks.add(id); } else { orders.add(id.getOrder()); } }); if (!conflictTasks.isEmpty()) { throw new IllegalArgumentException("The are " + conflictTasks.size() + " conflicted upgrade tasks (task with the same order for one version) : " + conflictTasks); } }  boolean needUpgrade(); void upgradeVersion(); void upgradeUser(String userId);  }
@Test public void shouldSortTasks() throws Exception { tasks.add(new MockUpgradeTask("12.3-EE", "fourth", 4, USER)); tasks.add(new MockUpgradeTask("1.4-EE", "second", 2, USER)); tasks.add(new MockUpgradeTask("75.12.0-EE", "sixth", 6, USER)); tasks.add(new MockUpgradeTask("100.5.0-EE", "seventh", 7, USER)); tasks.add(new MockUpgradeTask("2.5-PE", "third", 3, USER)); tasks.add(new MockUpgradeTask("1.3-PE", "first", 1, USER)); tasks.add(new MockUpgradeTask("50.4-PE", "fifth", 5, USER)); service.sortAndCheckTasks(); int i = 1; for (UpgradeTask task : tasks) { assertEquals(i, task.getId().getOrder()); i++; } }
@Test(expected = IllegalArgumentException.class) public void shouldDetectConflictTasks() throws Exception { tasks.add(new MockUpgradeTask("1.0.0", "one", 1, USER)); tasks.add(new MockUpgradeTask("1.0.0", "second", 2, USER)); tasks.add(new MockUpgradeTask("1.2.0", "one", 1, USER)); tasks.add(new MockUpgradeTask("1.2.0", "second", 2, USER)); tasks.add(new MockUpgradeTask("1.2.0", "second bis", 2, USER)); tasks.add(new MockUpgradeTask("1.2.0", "third", 3, USER)); tasks.add(new MockUpgradeTask("1.3.0", "second", 2, USER)); tasks.add(new MockUpgradeTask("1.3.0", "second bis", 2, USER)); service.sortAndCheckTasks(); }