From 7bb48bec9bd45d6d011413e58dc7451385d354ba Mon Sep 17 00:00:00 2001 From: Vova Perebykivskyi Date: Thu, 5 May 2016 14:44:59 +0300 Subject: [PATCH] Update Commons Collections. Code refactoring. --- NEWS.rst | 28 +- ganttzk/pom.xml | 4 +- .../FunctionalityExposedForExtensions.java | 192 ++-- .../data/resourceload/LoadTimeLine.java | 9 +- .../resourceload/ResourcesLoadPanel.java | 24 +- .../components/NewDataSortableColumn.java | 31 +- .../bandboxsearch/BandboxMultipleSearch.java | 94 +- .../web/limitingresources/GapsMergeSort.java | 55 +- .../planner/tabs/ResourcesLoadTabCreator.java | 67 +- .../resourceload/ResourceLoadController.java | 400 ++++---- .../web/resourceload/ResourceLoadModel.java | 879 +++++++++--------- pom.xml | 12 +- 12 files changed, 931 insertions(+), 864 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index 67b99088d..56bb8e96d 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -24,27 +24,33 @@ Thanks to all the contributors to this new version: Changes ~~~~~~~ -* Update MPXJ * Update Maven Gettext Plugin * Update Maven Compiler Plugin * Update Maven War Plugin * Update Maven Surfire Plugin -* Update Bonecp -* Update Slf4j API -* Update Slf4j Simple -* Update Guava * Update Maven Cobertura Plugin * Update Maven Liquibase Plugin -* Update Liquibase Core -* Update Jackson -* Update LibrePlan version to 1.6.0 -* Update Javax Servlet -* Update Jfree + +* Update Slf4j API +* Update Slf4j Simple +* Update Log4j +* Update Slf4j + * Update Commons Lang * Update Commons Math +* Update Commons Collections + +* Update MPXJ +* Update Bonecp +* Update Guava +* Update Liquibase Core +* Update Jackson +* Update Javax Servlet +* Update Jfree * Update JGraphT * Update DBUnit -* Update Log4j + +* Update LibrePlan version to 1.6.0 * Remove Ezmorph diff --git a/ganttzk/pom.xml b/ganttzk/pom.xml index 55e7b2e7c..865e33994 100644 --- a/ganttzk/pom.xml +++ b/ganttzk/pom.xml @@ -120,8 +120,8 @@ commons-lang3 - commons-collections - commons-collections + org.apache.commons + commons-collections4 diff --git a/ganttzk/src/main/java/org/zkoss/ganttz/FunctionalityExposedForExtensions.java b/ganttzk/src/main/java/org/zkoss/ganttz/FunctionalityExposedForExtensions.java index df7aa5f1d..8f62483da 100644 --- a/ganttzk/src/main/java/org/zkoss/ganttz/FunctionalityExposedForExtensions.java +++ b/ganttzk/src/main/java/org/zkoss/ganttz/FunctionalityExposedForExtensions.java @@ -30,7 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections4.CollectionUtils; import org.joda.time.LocalDate; import org.zkoss.ganttz.adapters.DomainDependency; import org.zkoss.ganttz.adapters.IAdapterToTaskFundamentalProperties; @@ -65,23 +65,25 @@ import org.zkoss.zul.Window; public class FunctionalityExposedForExtensions implements IContext { private static class OneToOneMapper implements IDomainAndBeansMapper { - private Map fromDomainToTask = new HashMap(); - private Map fromTaskToDomain = new HashMap(); + private Map fromDomainToTask = new HashMap<>(); - private Map fromTaskToParent = new HashMap(); + private Map fromTaskToDomain = new HashMap<>(); - private List topLevel = new ArrayList(); + private Map fromTaskToParent = new HashMap<>(); + + private List topLevel = new ArrayList<>(); @Override - public Task findAssociatedBean(T domainObject) - throws IllegalArgumentException { - if (domainObject == null) { + public Task findAssociatedBean(T domainObject) throws IllegalArgumentException { + if ( domainObject == null ) { throw new IllegalArgumentException("domainObject is null"); } - if (!fromDomainToTask.containsKey(domainObject)) { + + if ( !fromDomainToTask.containsKey(domainObject) ) { throw new IllegalArgumentException("not found " + domainObject); } + return fromDomainToTask.get(domainObject); } @@ -96,9 +98,9 @@ public class FunctionalityExposedForExtensions implements IContext { fromDomainToTask.put(domainObject, task); fromTaskToDomain.put(task, domainObject); - if (position.isAppendToTop()) { + if ( position.isAppendToTop() ) { topLevel.add(task); - } else if (position.isAtTop()) { + } else if ( position.isAtTop() ) { topLevel.add(position.getInsertionPosition(), task); } else { fromTaskToParent.put(task, position.getParent()); @@ -110,34 +112,39 @@ public class FunctionalityExposedForExtensions implements IContext { fromDomainToTask.remove(domainObject); fromTaskToDomain.remove(toBeRemoved); TaskContainer parent = fromTaskToParent.get(toBeRemoved); - if (parent != null) { + + if ( parent != null ) { parent.remove(toBeRemoved); } + fromTaskToParent.remove(toBeRemoved); topLevel.remove(toBeRemoved); } @Override - public T findAssociatedDomainObject(Task task) - throws IllegalArgumentException { - if (task == null) { + public T findAssociatedDomainObject(Task task) throws IllegalArgumentException { + if ( task == null ) { throw new IllegalArgumentException("taskBean is null"); } - if (!fromTaskToDomain.containsKey(task)) { + + if ( !fromTaskToDomain.containsKey(task) ) { throw new IllegalArgumentException(); } + return fromTaskToDomain.get(task); } @Override public Position findPositionFor(Task task) { List ancestors = ancestorsOf(task); - if (ancestors.isEmpty()) { + + if ( ancestors.isEmpty() ) { return Position.createAtTopPosition(topLevel.indexOf(task)); } + TaskContainer parent = ancestors.get(0); - return Position.createPosition(ancestors, parent.getTasks() - .indexOf(task)); + + return Position.createPosition(ancestors, parent.getTasks().indexOf(task)); } @Override @@ -146,18 +153,21 @@ public class FunctionalityExposedForExtensions implements IContext { } private List ancestorsOf(Task task) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); TaskContainer taskContainer = fromTaskToParent.get(task); + while (taskContainer != null) { result.add(taskContainer); taskContainer = fromTaskToParent.get(taskContainer); } + return result; } @Override public List getParents(Task task) { Position position = findPositionFor(task); + return position.getAncestors(); } @@ -171,39 +181,38 @@ public class FunctionalityExposedForExtensions implements IContext { private TimeTracker timeTracker; private final PlannerConfiguration configuration; - public FunctionalityExposedForExtensions(Planner planner, - PlannerConfiguration configuration, - GanttZKDiagramGraph diagramGraph) { + public FunctionalityExposedForExtensions( + Planner planner, PlannerConfiguration configuration, GanttZKDiagramGraph diagramGraph) { + this.planner = planner; this.configuration = configuration; this.adapter = configuration.getAdapter(); this.navigator = configuration.getNavigator(); this.diagramGraph = diagramGraph; - final IDetailItemModificator firstLevelModificators = configuration - .getFirstLevelModificators(); - final IDetailItemModificator secondLevelModificators = configuration - .getSecondLevelModificators(); + final IDetailItemModificator firstLevelModificators = configuration.getFirstLevelModificators(); + final IDetailItemModificator secondLevelModificators = configuration.getSecondLevelModificators(); Calendar calendarRightNow = Calendar.getInstance(); LocalDate localDateRightNow = LocalDate.fromCalendarFields(calendarRightNow); LocalDate initDate = localDateRightNow.minusYears(1); LocalDate endDate = localDateRightNow.plusYears(5); - this.timeTracker = new TimeTracker(new Interval( - TimeTrackerState.year(initDate.getYear()), - TimeTrackerState.year(endDate.getYear())), - planner.getZoomLevel(), firstLevelModificators, - secondLevelModificators, planner); + this.timeTracker = new TimeTracker( + new Interval(TimeTrackerState.year(initDate.getYear()), TimeTrackerState.year(endDate.getYear())), + planner.getZoomLevel(), + firstLevelModificators, + secondLevelModificators, + planner); } /** - * @param insertionPosition - * the position in which to register the task at top level. It - * can be null + * @param insertionPosition the position in which to register the task at top level. + * It can be null * @param accumulatedDependencies * @param data * @param parent + * * @return */ private Task buildAndRegister(Position position, List> accumulatedDependencies, T data) { @@ -212,15 +221,17 @@ public class FunctionalityExposedForExtensions implements IContext { final Task result = build(data); - if (!navigator.isLeaf(data)) { + if ( !navigator.isLeaf(data) ) { TaskContainer container = (TaskContainer) result; int i = 0; + for (T child : navigator.getChildren(data)) { container.add(buildAndRegister(position.down(container, i), accumulatedDependencies, child)); i++; } - } else if (navigator.isMilestone(data)) { + + } else if ( navigator.isMilestone(data) ) { Milestone milestone = (Milestone) result; milestone.setOwner(position.getParent()); } @@ -230,6 +241,7 @@ public class FunctionalityExposedForExtensions implements IContext { result.setShowingAdvances(planner.showAdvancesRightNow()); mapper.register(position, result, data); + return result; } @@ -245,14 +257,17 @@ public class FunctionalityExposedForExtensions implements IContext { } public void add(Position position, Collection domainObjects) { - List> totalDependencies = new ArrayList>(); - List tasksCreated = new ArrayList(); + List> totalDependencies = new ArrayList<>(); + List tasksCreated = new ArrayList<>(); + for (T object : domainObjects) { Task task = buildAndRegister(position, totalDependencies, object); tasksCreated.add(task); } + updateTimeTracker(tasksCreated); - if (position.isAppendToTop() || position.isAtTop()) { + + if ( position.isAppendToTop() || position.isAtTop() ) { this.diagramGraph.addTopLevel(tasksCreated); } else { this.diagramGraph.addTasks(tasksCreated); @@ -260,10 +275,11 @@ public class FunctionalityExposedForExtensions implements IContext { parent.addAll(position.getInsertionPosition(), tasksCreated); this.diagramGraph.childrenAddedTo(parent); } - for (Dependency dependency : DomainDependency.toDependencies(mapper, - totalDependencies)) { + + for (Dependency dependency : DomainDependency.toDependencies(mapper, totalDependencies)) { this.diagramGraph.addWithoutEnforcingConstraints(dependency); } + this.diagramGraph.enforceAllRestrictions(); this.planner.addTasks(position, tasksCreated); } @@ -271,7 +287,8 @@ public class FunctionalityExposedForExtensions implements IContext { private void updateTimeTracker(List tasksCreated) { for (Task task : tasksCreated) { timeTracker.trackPosition(task); - if (task.isContainer()) { + + if ( task.isContainer() ) { TaskContainer container = (TaskContainer) task; updateTimeTracker(container.getTasks()); } @@ -310,6 +327,7 @@ public class FunctionalityExposedForExtensions implements IContext { diagramGraph.remove(task); task.removed(); planner.removeTask(task); + return position; } @@ -330,20 +348,19 @@ public class FunctionalityExposedForExtensions implements IContext { private DomainDependency toDomainDependency(Dependency bean) { T source = mapper.findAssociatedDomainObject(bean.getSource()); - T destination = mapper - .findAssociatedDomainObject(bean.getDestination()); - DomainDependency dep = DomainDependency.createDependency(source, - destination, bean.getType()); + T destination = mapper.findAssociatedDomainObject(bean.getDestination()); + DomainDependency dep = DomainDependency.createDependency(source, destination, bean.getType()); + return dep; } public void addDependency(Dependency dependency) { - if (!canAddDependency(dependency)) { + if ( !canAddDependency(dependency) ) { return; } + diagramGraph.add(dependency); - getDependencyList().addDependencyComponent( - getTaskList().asDependencyComponent(dependency)); + getDependencyList().addDependencyComponent(getTaskList().asDependencyComponent(dependency)); adapter.addDependency(toDomainDependency(dependency)); } @@ -352,8 +369,7 @@ public class FunctionalityExposedForExtensions implements IContext { } private boolean canAddDependency(Dependency dependency) { - return diagramGraph.canAddDependency(dependency) - && adapter.canAddDependency(toDomainDependency(dependency)); + return diagramGraph.canAddDependency(dependency) && adapter.canAddDependency(toDomainDependency(dependency)); } private DependencyList getDependencyList() { @@ -370,18 +386,22 @@ public class FunctionalityExposedForExtensions implements IContext { * Substitutes the dependency for a new one with the same source and * destination but with the specified type. If the new dependency cannot be * added, the old one remains. + * * @param dependency * @param type * the new type + * * @return true only if the new dependency can be added. */ public boolean changeType(Dependency dependency, DependencyType type) { Dependency newDependency = dependency.createWithType(type); boolean canAddDependency = diagramGraph.canAddDependency(newDependency); - if (canAddDependency) { + + if ( canAddDependency ) { removeDependency(dependency); addDependency(newDependency); } + return canAddDependency; } @@ -398,19 +418,20 @@ public class FunctionalityExposedForExtensions implements IContext { @Override public void showCriticalPath() { - CriticalPathCalculator criticalPathCalculator = CriticalPathCalculator - .create(configuration.isDependenciesConstraintsHavePriority()); + CriticalPathCalculator criticalPathCalculator = + CriticalPathCalculator.create(configuration.isDependenciesConstraintsHavePriority()); + + List criticalPath = criticalPathCalculator.calculateCriticalPath(diagramGraph); - List criticalPath = criticalPathCalculator - .calculateCriticalPath(diagramGraph); for (Task task : diagramGraph.getTasks()) { task.setInCriticalPath(isInCriticalPath(criticalPath, task)); } } private boolean isInCriticalPath(List criticalPath, Task task) { - if (task.isContainer()) { - List allTaskLeafs = ((TaskContainer) task).getAllTaskLeafs(); + if ( task.isContainer() ) { + List allTaskLeafs = task.getAllTaskLeafs(); + return CollectionUtils.containsAny(criticalPath, allTaskLeafs); } else { return criticalPath.contains(task); @@ -419,13 +440,15 @@ public class FunctionalityExposedForExtensions implements IContext { @Override public List getCriticalPath() { - List result = new ArrayList(); - CriticalPathCalculator criticalPathCalculator = CriticalPathCalculator - .create(configuration.isDependenciesConstraintsHavePriority()); - for (Task each : criticalPathCalculator - .calculateCriticalPath(diagramGraph)) { + List result = new ArrayList<>(); + + CriticalPathCalculator criticalPathCalculator = + CriticalPathCalculator.create(configuration.isDependenciesConstraintsHavePriority()); + + for (Task each : criticalPathCalculator.calculateCriticalPath(diagramGraph)) { result.add(mapper.findAssociatedDomainObject(each)); } + return result; } @@ -488,49 +511,56 @@ public class FunctionalityExposedForExtensions implements IContext { } private HashMap buildParameters(Component parent) { - HashMap parameters = new HashMap(); + HashMap parameters = new HashMap<>(); Checkbox expanded = (Checkbox) parent.getFellow("print_expanded"); Checkbox resources = (Checkbox) parent.getFellow("print_resources"); Checkbox labels = (Checkbox) parent.getFellow("print_labels"); Checkbox advances = (Checkbox) parent.getFellow("print_advances"); - Checkbox reportedHours = (Checkbox) parent - .getFellow("print_reported_hours"); - Checkbox moneyCostBar = (Checkbox) parent - .getFellow("print_money_cost_bar"); + Checkbox reportedHours = (Checkbox) parent.getFellow("print_reported_hours"); + Checkbox moneyCostBar = (Checkbox) parent.getFellow("print_money_cost_bar"); parameters.put("extension", ".png"); - if (expanded.isChecked() == true) { + + if ( expanded.isChecked() ) { parameters.put("expanded", "all"); } - if (labels.isChecked() == true) { + + if ( labels.isChecked() ) { parameters.put("labels", "all"); } - if (advances.isChecked() == true) { + + if ( advances.isChecked() ) { parameters.put("advances", "all"); } - if (reportedHours.isChecked() == true) { + + if ( reportedHours.isChecked() ) { parameters.put("reportedHours", "all"); } - if (moneyCostBar.isChecked() == true) { + + if ( moneyCostBar.isChecked() ) { parameters.put("moneyCostBar", "all"); } - if (resources.isChecked() == true) { + + if ( resources.isChecked() ) { parameters.put("resources", "all"); } + parameters.put("zoom", planner.getZoomLevel().getInternalName()); + return parameters; } public void print() { - if (!isPrintEnabled()) { + if ( !isPrintEnabled() ) { throw new UnsupportedOperationException("print is not supported"); } - final Window printProperties = (Window) Executions.createComponents( - "/planner/print_configuration.zul", planner, null); + final Window printProperties = + (Window) Executions.createComponents("/planner/print_configuration.zul", planner, null); Button printButton = (Button) printProperties.getFellow("printButton"); + printButton.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) { @@ -538,6 +568,7 @@ public class FunctionalityExposedForExtensions implements IContext { configuration.print(buildParameters(printProperties),planner); } }); + printButton.setParent(printProperties); try { @@ -551,13 +582,14 @@ public class FunctionalityExposedForExtensions implements IContext { @Override public List getTasksOrderedByStartDate() { List tasks = diagramGraph.getTasks(); - Collections.sort(tasks, new Comparator() { + Collections.sort(tasks, new Comparator() { @Override public int compare(Task o1, Task o2) { return o1.getBeginDate().compareTo(o2.getBeginDate()); } }); + return tasks; } @@ -571,7 +603,7 @@ public class FunctionalityExposedForExtensions implements IContext { private void setExpandAll(boolean expand, List tasks) { for (Task task : tasks) { - if (task instanceof TaskContainer) { + if ( task instanceof TaskContainer ) { ((TaskContainer) task).setExpanded(expand); } } diff --git a/ganttzk/src/main/java/org/zkoss/ganttz/data/resourceload/LoadTimeLine.java b/ganttzk/src/main/java/org/zkoss/ganttz/data/resourceload/LoadTimeLine.java index 10d16eebf..2b89e0dfa 100644 --- a/ganttzk/src/main/java/org/zkoss/ganttz/data/resourceload/LoadTimeLine.java +++ b/ganttzk/src/main/java/org/zkoss/ganttz/data/resourceload/LoadTimeLine.java @@ -26,7 +26,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.apache.commons.collections.ComparatorUtils; +import org.apache.commons.collections4.comparators.NullComparator; import org.apache.commons.lang3.Validate; import org.joda.time.LocalDate; import org.zkoss.ganttz.data.GanttDate; @@ -35,15 +35,14 @@ import org.zkoss.ganttz.util.Interval; public class LoadTimeLine { @SuppressWarnings("unchecked") - private static final Comparator nullSafeComparator = - ComparatorUtils.nullLowComparator(ComparatorUtils.naturalComparator()); + private static final Comparator nullSafeComparator = new NullComparator<>(false); public static Comparator byStartAndEndDate() { return new Comparator() { - @Override public int compare(LoadTimeLine o1, LoadTimeLine o2) { int result = nullSafeComparator.compare(o1.getStartPeriod(), o2.getStartPeriod()); + if ( result == 0 ) { return nullSafeComparator.compare(o1.getEndPeriod(), o2.getEndPeriod()); } @@ -151,7 +150,7 @@ public class LoadTimeLine { GanttDate end = null; for (LoadTimeLine loadTimeLine : timeLines) { - if( !loadTimeLine.isEmpty() ) { + if ( !loadTimeLine.isEmpty() ) { Validate.notNull(loadTimeLine.getStart()); start = min(start, loadTimeLine.getStart()); Validate.notNull(loadTimeLine.getEnd()); diff --git a/ganttzk/src/main/java/org/zkoss/ganttz/resourceload/ResourcesLoadPanel.java b/ganttzk/src/main/java/org/zkoss/ganttz/resourceload/ResourcesLoadPanel.java index 155822dcd..0244acc6a 100644 --- a/ganttzk/src/main/java/org/zkoss/ganttz/resourceload/ResourcesLoadPanel.java +++ b/ganttzk/src/main/java/org/zkoss/ganttz/resourceload/ResourcesLoadPanel.java @@ -285,9 +285,8 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { @SuppressWarnings("unchecked") private Separator getSeparator() { List children = getToolbar().getChildren(); - Separator separator = ComponentsFinder.findComponentsOfType(Separator.class, children).get(0); - return separator; + return ComponentsFinder.findComponentsOfType(Separator.class, children).get(0); } private Component getToolbar() { @@ -364,12 +363,12 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { // Insert additional filters if any Component additionalFilter = getFirstOptionalFilter(); - if( additionalFilter != null ) { + if ( additionalFilter != null ) { getFellow("additionalFilterInsertionPoint1").appendChild(additionalFilter); } additionalFilter = getSecondOptionalFilter(); - if( additionalFilter != null ) { + if ( additionalFilter != null ) { getFellow("additionalFilterInsertionPoint2").appendChild(additionalFilter); } @@ -378,10 +377,10 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { listZoomLevels = (Listbox) getFellow("listZoomLevels"); listZoomLevels.setSelectedIndex(timeTracker.getDetailLevel().ordinal()); - if( paginationType == PaginationType.INTERNAL_PAGINATION && refreshNameFilter ) { + if ( paginationType == PaginationType.INTERNAL_PAGINATION && refreshNameFilter ) { setupNameFilter(); } - else if( paginationType == PaginationType.NONE ) { + else if ( paginationType == PaginationType.NONE ) { getFellow("filterByNameCombo").setVisible(false); getFellow("filterByNameLabel").setVisible(false); } @@ -443,15 +442,15 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { filterByNameCombo.getChildren().clear(); int size = groups.size(); - if( size > numberOfGroupsByName ) { + if ( size > numberOfGroupsByName ) { int position = 0; - while(position < size) { + while (position < size) { String firstName = groups.get(position).getConceptName(); String lastName; int newPosition = position + numberOfGroupsByName; - if( newPosition - 1 < size ) { + if ( newPosition - 1 < size ) { lastName = groups.get(newPosition - 1).getConceptName(); } else { @@ -483,7 +482,7 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { * @return */ private List getGroupsToShow() { - if( paginationType != PaginationType.INTERNAL_PAGINATION || filterByNamePosition == -1 ) { + if ( paginationType != PaginationType.INTERNAL_PAGINATION || filterByNamePosition == -1 ) { return groups; } @@ -522,7 +521,7 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { LongOperationFeedback.execute(componentOnWhichGiveFeedback, new ILongOperation() { @Override public void doAction() { - if( paginationType == PaginationType.INTERNAL_PAGINATION ) { + if ( paginationType == PaginationType.INTERNAL_PAGINATION ) { //if the pagination is internal, we are in charge of repainting the graph treeModel = createModelForTree(); @@ -563,6 +562,7 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { public void changeChartVisibility(boolean visible) { visibleChart = visible; + chartVisibilityListeners.fireEvent(new IListenerNotification() { @Override public void doNotify(IChartVisibilityChangedListener listener) { @@ -588,7 +588,7 @@ public class ResourcesLoadPanel extends HtmlMacroComponent { } public Combobox getPaginationFilterCombobox() { - if( paginationType == PaginationType.EXTERNAL_PAGINATION ) { + if ( paginationType == PaginationType.EXTERNAL_PAGINATION ) { return (Combobox) getFellow("filterByNameCombo"); } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/components/NewDataSortableColumn.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/components/NewDataSortableColumn.java index 6232287b1..8bc004d85 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/components/NewDataSortableColumn.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/components/NewDataSortableColumn.java @@ -23,7 +23,7 @@ package org.libreplan.web.common.components; import java.util.Comparator; -import org.apache.commons.collections.comparators.BooleanComparator; +import org.apache.commons.collections4.comparators.BooleanComparator; import org.apache.commons.lang.Validate; import org.libreplan.business.INewObject; import org.zkoss.zk.ui.ext.AfterCompose; @@ -45,13 +45,13 @@ import org.zkoss.zul.api.Grid; * in order to work properly. They notify the {@link NewDataSortableGrid} in which are * included when they are requested to be sorted. *

+ * * @author Javier Moran Rua */ public class NewDataSortableColumn extends Column implements AfterCompose { - private static class NewObjectDecoratorComparator implements - Comparator { + private static class NewObjectDecoratorComparator implements Comparator { private Comparator decoratedComparator; public NewObjectDecoratorComparator(Comparator c) { @@ -61,7 +61,7 @@ public class NewDataSortableColumn extends Column implements AfterCompose { @Override public int compare(Object o1, Object o2) { - if (!doComparingObjectsSupportInterface(o1, o2)) { + if ( !doComparingObjectsSupportInterface(o1, o2) ) { return decoratedComparator.compare(o1, o2); } else { return decorateBehaviour((INewObject) o1, (INewObject) o2); @@ -73,11 +73,11 @@ public class NewDataSortableColumn extends Column implements AfterCompose { } private int decorateBehaviour(INewObject o1, INewObject o2) { - if (o1.isNewObject() == o2.isNewObject()) { + if ( o1.isNewObject() == o2.isNewObject() ) { return decoratedComparator.compare(o1, o2); } - return BooleanComparator.getTrueFirstComparator().compare( - o1.isNewObject(), o2.isNewObject()); + + return BooleanComparator.getTrueFirstComparator().compare(o1.isNewObject(), o2.isNewObject()); } } @@ -94,10 +94,11 @@ public class NewDataSortableColumn extends Column implements AfterCompose { @Override public boolean sort(boolean ascending) { Grid grid = getGrid(); - if (grid instanceof NewDataSortableGrid) { + if ( grid instanceof NewDataSortableGrid ) { ((NewDataSortableGrid) grid).setSortedColumn(this); ((NewDataSortableGrid) grid).setLastSortedColumnAscending(ascending); } + return super.sort(ascending); } @@ -105,11 +106,11 @@ public class NewDataSortableColumn extends Column implements AfterCompose { public void afterCompose() { Grid g = getGrid(); - if (g instanceof NewDataSortableGrid) { + if ( g instanceof NewDataSortableGrid ) { NewDataSortableGrid castedGrid = (NewDataSortableGrid) g; // The first registered column is responsible for ordering - if (castedGrid.getSortedColumn() == null) { + if ( castedGrid.getSortedColumn() == null ) { markInGridAsColumnToOrder(castedGrid); } } @@ -118,12 +119,10 @@ public class NewDataSortableColumn extends Column implements AfterCompose { private void markInGridAsColumnToOrder(NewDataSortableGrid parentGrid) { parentGrid.setSortedColumn(this); - if ("ascending".equals(getSortDirection())) { - parentGrid.setLastSortedColumnAscending( - Boolean.TRUE.booleanValue()); - } else if ("descending".equals(getSortDirection())) { - parentGrid.setLastSortedColumnAscending( - Boolean.FALSE.booleanValue()); + if ( "ascending".equals(getSortDirection()) ) { + parentGrid.setLastSortedColumnAscending(true); + } else if ( "descending".equals(getSortDirection()) ) { + parentGrid.setLastSortedColumnAscending(false); } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/components/bandboxsearch/BandboxMultipleSearch.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/components/bandboxsearch/BandboxMultipleSearch.java index 4d3424e5b..4b701ba14 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/components/bandboxsearch/BandboxMultipleSearch.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/components/bandboxsearch/BandboxMultipleSearch.java @@ -81,7 +81,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { private List selectedFilters = new ArrayList(); - private String selectedFiltersText = new String(""); + private String selectedFiltersText = ""; public void afterCompose() { super.afterCompose(); @@ -104,15 +104,17 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { @Override public boolean service(AuRequest request, boolean everError) { String command = request.getCommand(); - if (command.equals("closeBandbox")) { + if ( command.equals("closeBandbox") ) { pickElementFromListAndCloseBandbox(); + return true; } + return false; } }); - listbox.addEventListener(Events.ON_OK, new EventListener() { + listbox.addEventListener(Events.ON_OK, new EventListener() { @Override public void onEvent(Event event) { pickElementFromListAndCloseBandbox(); @@ -125,11 +127,10 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { * Search for matching elements while typing on bandbox */ bandbox.addEventListener("onChanging", new EventListener() { - @Override public void onEvent(Event event) { final String inputText = ((InputEvent) event).getValue(); - if ((inputText == null) || (inputText.isEmpty())) { + if ( (inputText == null) || (inputText.isEmpty()) ) { clear(); listbox.setSelectedIndex(0); Events.postEvent(Events.ON_CHANGE, listbox, null); @@ -145,7 +146,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { @Override public void onEvent(Event event) { List items = listbox.getItems(); - if (!items.isEmpty()) { + if ( !items.isEmpty() ) { listbox.setSelectedIndex(0); items.get(0).setFocus(true); } @@ -154,20 +155,22 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { } private void initFinder() { - if (multipleFiltersFinder != null) { - if (listbox != null) { + if ( multipleFiltersFinder != null ) { + + if ( listbox != null ) { initListbox(); } - if (bandbox != null) { + + if ( bandbox != null ) { initBandbox(); } } } private void pickElementFromListAndCloseBandbox() { - if(getSelectedItem() != null) { + if ( getSelectedItem() != null ) { final Object object = getSelectedItem().getValue(); - if (multipleFiltersFinder.isValidNewFilter(selectedFilters, object)) { + if ( multipleFiltersFinder.isValidNewFilter(selectedFilters, object) ) { addSelectedElement(object); clearListbox(); listbox.setModel(getSubModel()); @@ -186,16 +189,16 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { private void searchMultipleFilters(String inputText) { // update the filters list if some filter was deleted - boolean someRemoved = multipleFiltersFinder.updateDeletedFilters( - selectedFilters, inputText); - if (someRemoved) { + boolean someRemoved = multipleFiltersFinder.updateDeletedFilters(selectedFilters, inputText); + + if ( someRemoved ) { updateselectedFiltersText(); updateBandboxValue(); } else { // find the filter set to show it in the listbox - String newFilterText = multipleFiltersFinder - .getNewFilterText(inputText); - if ((newFilterText != null) && (!newFilterText.isEmpty())) { + String newFilterText = multipleFiltersFinder.getNewFilterText(inputText); + + if ( (newFilterText != null) && (!newFilterText.isEmpty()) ) { listbox.setModel(getSubModel(newFilterText)); listbox.invalidate(); } else { @@ -213,7 +216,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { } public void addSelectedElement(Object obj) { - if (obj != null) { + if ( obj != null ) { addFilter(obj); updateselectedFiltersText(); updateBandboxValue(); @@ -223,10 +226,11 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { private void addFilter(Object obj) { FilterPair newFilter = (FilterPair) obj; for (FilterPair filter : (List) selectedFilters) { - if ((filter.getType().equals(newFilter.getType())) - && (filter.getPattern().equals(newFilter.getPattern()))) { - throw new WrongValueException(bandbox, - _("filter already exists")); + + if ( (filter.getType().equals(newFilter.getType())) && + (filter.getPattern().equals(newFilter.getPattern())) ) { + + throw new WrongValueException(bandbox, _("filter already exists")); } } selectedFilters.add(obj); @@ -234,13 +238,12 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { public List getSelectedElements() { updateBandboxValue(); - if (this.multipleFiltersFinder != null) { - if (!multipleFiltersFinder.isValidFormatText(selectedFilters, - bandbox.getValue())) { - throw new WrongValueException(bandbox, - _("format filters are not valid")); + if ( this.multipleFiltersFinder != null ) { + if ( !multipleFiltersFinder.isValidFormatText(selectedFilters, bandbox.getValue()) ) { + throw new WrongValueException(bandbox, _("format filters are not valid")); } } + return selectedFilters; } @@ -250,6 +253,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { @SuppressWarnings("unchecked") private ListModel getSubModel() { List result = multipleFiltersFinder.getFirstTenFilters(); + return new SimpleListModel(result); } @@ -260,6 +264,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { @SuppressWarnings("unchecked") private ListModel getSubModel(String inputText) { List result = multipleFiltersFinder.getMatching(inputText); + return new SimpleListModel(result); } @@ -270,13 +275,13 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { public void addHeaders() { clearHeaderIfNecessary(); final String[] headers = multipleFiltersFinder.getHeaders(); - for (int i = 0; i < headers.length; i++) { - listhead.getChildren().add(new Listheader(_(headers[i]))); + for (String header : headers) { + listhead.getChildren().add(new Listheader(_(header))); } } private void clearHeaderIfNecessary() { - if (listhead.getChildren() != null) { + if ( listhead.getChildren() != null ) { listhead.getChildren().clear(); } } @@ -295,12 +300,12 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { } private Object getBean(String beanName) { - HttpServletRequest servletRequest = (HttpServletRequest) Executions - .getCurrent().getNativeRequest(); - ServletContext servletContext = servletRequest.getSession() - .getServletContext(); - WebApplicationContext webApplicationContext = WebApplicationContextUtils - .getWebApplicationContext(servletContext); + HttpServletRequest servletRequest = (HttpServletRequest) Executions.getCurrent().getNativeRequest(); + ServletContext servletContext = servletRequest.getSession().getServletContext(); + + WebApplicationContext webApplicationContext = + WebApplicationContextUtils.getWebApplicationContext(servletContext); + return webApplicationContext.getBean(beanName); } @@ -309,8 +314,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { } public void setFinder(String classname) { - multipleFiltersFinder = (IMultipleFiltersFinder) getBean(StringUtils - .uncapitalize(classname)); + multipleFiltersFinder = (IMultipleFiltersFinder) getBean(StringUtils.uncapitalize(classname)); initFinder(); } @@ -324,16 +328,17 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { } private void clearListbox() { - List list = new ArrayList(); + List list = new ArrayList<>(); listbox.setModel(new SimpleListModel(list)); listbox.invalidate(); } public List asList(ListModel model) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (int i = 0; i < model.getSize(); i++) { result.add(model.getElementAt(i)); } + return result; } @@ -358,14 +363,14 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { } private void updateWidth() { - if ((widthBandbox != null) && (!widthBandbox.isEmpty())) { + if ( (widthBandbox != null) && (!widthBandbox.isEmpty()) ) { this.bandbox.setWidth(widthBandbox); this.listbox.setWidth(widthListbox); } } private void updateHeight() { - if ((heightBbox != null) && (!heightBbox.isEmpty())) { + if ( (heightBbox != null) && (!heightBbox.isEmpty()) ) { this.bandbox.setHeight(heightBbox); } } @@ -377,8 +382,7 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { private void updateselectedFiltersText() { selectedFiltersText = ""; for (Object obj : selectedFilters) { - selectedFiltersText = selectedFiltersText - .concat(multipleFiltersFinder.objectToString(obj)); + selectedFiltersText = selectedFiltersText.concat(multipleFiltersFinder.objectToString(obj)); } } @@ -392,9 +396,11 @@ public class BandboxMultipleSearch extends HtmlMacroComponent { public void addSelectedElements(List sessionFilterPairs) { selectedFilters.clear(); + for (FilterPair filterPair : sessionFilterPairs) { addFilter(filterPair); } + updateselectedFiltersText(); updateBandboxValue(); } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/GapsMergeSort.java b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/GapsMergeSort.java index bc7b29ef7..fb3e3bb37 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/GapsMergeSort.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/GapsMergeSort.java @@ -26,7 +26,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import org.apache.commons.collections.comparators.BooleanComparator; +import org.apache.commons.collections4.comparators.BooleanComparator; import org.libreplan.business.planner.limiting.entities.Gap.GapOnQueue; @@ -45,12 +45,12 @@ public class GapsMergeSort { */ private static class CurrentGap implements Comparable { - static List convert( - Collection> iterators) { - List result = new ArrayList(); + static List convert(Collection> iterators) { + List result = new ArrayList<>(); for (Iterator iterator : iterators) { result.add(new CurrentGap(iterator)); } + return result; } @@ -65,6 +65,7 @@ public class GapsMergeSort { public GapOnQueue consume() { GapOnQueue result = getCurrent(); current = null; + return result; } @@ -73,12 +74,14 @@ public class GapsMergeSort { } private GapOnQueue getCurrent() { - if (hasFinished()) { + if ( hasFinished() ) { throw new IllegalStateException("already finished"); } - if (current != null) { + + if ( current != null ) { return current; } + return current = iterator.next(); } @@ -88,53 +91,61 @@ public class GapsMergeSort { */ @Override public int compareTo(CurrentGap other) { - int finishComparison = BooleanComparator.getFalseFirstComparator() - .compare(hasFinished(), other.hasFinished()); - if (finishComparison != 0) { + int finishComparison = + BooleanComparator.getFalseFirstComparator().compare(hasFinished(), other.hasFinished()); + + if ( finishComparison != 0 ) { return finishComparison; - } else if (hasFinished()) { + } else if ( hasFinished() ) { assert other.hasFinished(); + return 0; } else { assert !hasFinished() && !other.hasFinished(); - return getCurrent().getGap().compareTo( - other.getCurrent().getGap()); + + return getCurrent().getGap().compareTo(other.getCurrent().getGap()); } } } - public static List sort( - List> orderedListsOfGaps) { + public static List sort(List> orderedListsOfGaps) { - List result = new ArrayList(); + List result = new ArrayList<>(); - if (orderedListsOfGaps.isEmpty()) { + if ( orderedListsOfGaps.isEmpty() ) { return result; } - if (orderedListsOfGaps.size() == 1) { + + if ( orderedListsOfGaps.size() == 1 ) { return orderedListsOfGaps.get(0); } List currentGaps = CurrentGap.convert(iteratorsFor(orderedListsOfGaps)); CurrentGap min = Collections.min(currentGaps); + while (!currentGaps.isEmpty() && !min.hasFinished()) { + result.add(min.consume()); - if (min.hasFinished()) { + + if ( min.hasFinished() ) { + currentGaps.remove(min); - if (!currentGaps.isEmpty()) { + + if ( !currentGaps.isEmpty() ) { min = Collections.min(currentGaps); } } } + return result; } - private static List> iteratorsFor( - List> orderedListsOfGaps) { - List> result = new ArrayList>(); + private static List> iteratorsFor(List> orderedListsOfGaps) { + List> result = new ArrayList<>(); for (List each : orderedListsOfGaps) { result.add(each.iterator()); } + return result; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/planner/tabs/ResourcesLoadTabCreator.java b/libreplan-webapp/src/main/java/org/libreplan/web/planner/tabs/ResourcesLoadTabCreator.java index 5fe1a41d4..7bf18cb8c 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/planner/tabs/ResourcesLoadTabCreator.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/planner/tabs/ResourcesLoadTabCreator.java @@ -49,14 +49,13 @@ public class ResourcesLoadTabCreator { private final IOrderPlanningGate orderPlanningGate; public static ITab create(Mode mode, - ResourceLoadController resourceLoadController, - ResourceLoadController resourceLoadControllerGlobal, - IOrderPlanningGate orderPlanningGate, - Component breadcrumbs) { - return new ResourcesLoadTabCreator(mode, resourceLoadController, - resourceLoadControllerGlobal, orderPlanningGate, - breadcrumbs) - .build(); + ResourceLoadController resourceLoadController, + ResourceLoadController resourceLoadControllerGlobal, + IOrderPlanningGate orderPlanningGate, + Component breadcrumbs) { + + return new ResourcesLoadTabCreator( + mode, resourceLoadController, resourceLoadControllerGlobal, orderPlanningGate, breadcrumbs).build(); } private final Mode mode; @@ -67,10 +66,11 @@ public class ResourcesLoadTabCreator { private final Component breadcrumbs; private ResourcesLoadTabCreator(Mode mode, - ResourceLoadController resourceLoadController, - ResourceLoadController resourceLoadControllerGlobal, - IOrderPlanningGate orderPlanningGate, - Component breadcrumbs) { + ResourceLoadController resourceLoadController, + ResourceLoadController resourceLoadControllerGlobal, + IOrderPlanningGate orderPlanningGate, + Component breadcrumbs) { + this.mode = mode; this.resourceLoadController = resourceLoadController; this.resourceLoadControllerGlobal = resourceLoadControllerGlobal; @@ -87,20 +87,16 @@ public class ResourcesLoadTabCreator { private ITab createOrderResourcesLoadTab() { IComponentCreator componentCreator = new IComponentCreator() { - @Override - public org.zkoss.zk.ui.Component create( - org.zkoss.zk.ui.Component parent) { - Map arguments = new HashMap(); + public org.zkoss.zk.ui.Component create(org.zkoss.zk.ui.Component parent) { + Map arguments = new HashMap<>(); arguments.put("resourceLoadController", resourceLoadController); - return Executions.createComponents( - "/resourceload/_resourceloadfororder.zul", parent, - arguments); + + return Executions.createComponents("/resourceload/_resourceloadfororder.zul", parent, arguments); } }; - return new CreatedOnDemandTab(_("Resources Load"), "order-load", - componentCreator) { + return new CreatedOnDemandTab(_("Resources Load"), "order-load", componentCreator) { @Override protected void afterShowAction() { @@ -111,8 +107,7 @@ public class ResourcesLoadTabCreator { breadcrumbs.appendChild(new Label(_("Resources Load"))); breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR)); Order currentOrder = mode.getOrder(); - resourceLoadController - .setPlanningControllerEntryPoints(orderPlanningGate); + resourceLoadController.setPlanningControllerEntryPoints(orderPlanningGate); resourceLoadController.filterBy(currentOrder); resourceLoadController.reload(); breadcrumbs.appendChild(new Label(currentOrder.getName())); @@ -123,37 +118,33 @@ public class ResourcesLoadTabCreator { private ITab createGlobalResourcesLoadTab() { final IComponentCreator componentCreator = new IComponentCreator() { - @Override - public org.zkoss.zk.ui.Component create( - org.zkoss.zk.ui.Component parent) { - Map arguments = new HashMap(); - arguments.put("resourceLoadController", - resourceLoadControllerGlobal); - return Executions.createComponents( - "/resourceload/_resourceload.zul", parent, arguments); + public org.zkoss.zk.ui.Component create(org.zkoss.zk.ui.Component parent) { + Map arguments = new HashMap<>(); + arguments.put("resourceLoadController", resourceLoadControllerGlobal); + + return Executions.createComponents("/resourceload/_resourceload.zul", parent, arguments); } }; - return new CreatedOnDemandTab(_("Resources Load"), "company-load", - componentCreator) { + return new CreatedOnDemandTab(_("Resources Load"), "company-load", componentCreator) { @Override protected void beforeShowAction() { - if (!SecurityUtils - .isSuperuserOrUserInRoles(UserRole.ROLE_PLANNING)) { + if ( !SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_PLANNING) ) { Util.sendForbiddenStatusCodeInHttpServletResponse(); } } @Override protected void afterShowAction() { - resourceLoadControllerGlobal - .setPlanningControllerEntryPoints(orderPlanningGate); + resourceLoadControllerGlobal.setPlanningControllerEntryPoints(orderPlanningGate); resourceLoadControllerGlobal.filterBy(null); resourceLoadControllerGlobal.reload(); - if (breadcrumbs.getChildren() != null) { + + if ( breadcrumbs.getChildren() != null ) { breadcrumbs.getChildren().clear(); } + breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR)); breadcrumbs.appendChild(new Label(getSchedulingLabel())); breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR)); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadController.java b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadController.java index e09711e46..2437a5cb3 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadController.java @@ -116,7 +116,7 @@ public class ResourceLoadController implements Composer { @Autowired private IAdHocTransactionService transactionService; - private List commands = new ArrayList(); + private List commands = new ArrayList<>(); private PlanningState filterBy; @@ -177,25 +177,28 @@ public class ResourceLoadController implements Composer { private List visualizationModifiers = null; private List getVisualizationModifiers() { - if (visualizationModifiers != null) { + if ( visualizationModifiers != null ) { return visualizationModifiers; } + return visualizationModifiers = buildVisualizationModifiers(); } private List listenersToAdd = null; private List getListenersToAdd() { - if (listenersToAdd != null) { + if ( listenersToAdd != null ) { return listenersToAdd; } - List result = new ArrayList(); + + List result = new ArrayList<>(); for (VisualizationModifier each : getVisualizationModifiers()) { - if (each instanceof IListenerAdder) { + if ( each instanceof IListenerAdder ) { result.add((IListenerAdder) each); } } result.add(new GoToScheduleListener()); + return listenersToAdd = result; } @@ -209,10 +212,10 @@ public class ResourceLoadController implements Composer { public IOnTransaction reload() { return new IOnTransaction() { - @Override public Void execute() { reloadInTransaction(); + return null; } }; @@ -222,8 +225,9 @@ public class ResourceLoadController implements Composer { for (VisualizationModifier each : getVisualizationModifiers()) { each.checkDependencies(); } - ResourceLoadParameters parameters = new ResourceLoadParameters( - filterBy); + + ResourceLoadParameters parameters = new ResourceLoadParameters(filterBy); + for (VisualizationModifier each : getVisualizationModifiers()) { each.applyToParameters(parameters); } @@ -231,17 +235,19 @@ public class ResourceLoadController implements Composer { ResourceLoadDisplayData dataToShow = resourceLoadModel.calculateDataToDisplay(parameters); timeTracker = buildTimeTracker(dataToShow); - if (resourcesLoadPanel == null) { + + if ( resourcesLoadPanel == null ) { resourcesLoadPanel = buildPanel(dataToShow); listeners.addListeners(resourcesLoadPanel, getListenersToAdd()); parent.getChildren().clear(); parent.appendChild(resourcesLoadPanel); + for (VisualizationModifier each : getVisualizationModifiers()) { each.setup(resourcesLoadPanel); } + } else { - resourcesLoadPanel.init(dataToShow.getLoadTimeLines(), - timeTracker); + resourcesLoadPanel.init(dataToShow.getLoadTimeLines(), timeTracker); listeners.addListeners(resourcesLoadPanel, getListenersToAdd()); } @@ -255,27 +261,33 @@ public class ResourceLoadController implements Composer { private TimeTracker buildTimeTracker(ResourceLoadDisplayData dataToShow) { ZoomLevel zoomLevel = getZoomLevel(dataToShow); - TimeTracker result = new TimeTracker(dataToShow.getViewInterval(), - zoomLevel, SeveralModificators.create(), + + TimeTracker result = new TimeTracker( + dataToShow.getViewInterval(), + zoomLevel, + SeveralModificators.create(), SeveralModificators.create(createBankHolidaysMarker()), parent); + setupZoomLevelListener(result); + return result; } private ZoomLevel getZoomLevel(ResourceLoadDisplayData dataToShow) { - if (filterBy != null) { + if ( filterBy != null ) { Order order = filterBy.getOrder(); ZoomLevel sessionZoom = FilterUtils.readZoomLevel(order); - if (sessionZoom != null) { + if ( sessionZoom != null ) { return sessionZoom; } } ZoomLevel sessionZoom = FilterUtils.readZoomLevelResourcesLoad(); - if (sessionZoom != null) { + if ( sessionZoom != null ) { return sessionZoom; } + return dataToShow.getInitialZoomLevel(); } @@ -285,11 +297,10 @@ public class ResourceLoadController implements Composer { } private IZoomLevelChangedListener getSessionZoomLevelListener() { - IZoomLevelChangedListener zoomListener = new IZoomLevelChangedListener() { - + return new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel detailLevel) { - if (filterBy != null) { + if ( filterBy != null ) { Order order = filterBy.getOrder(); FilterUtils.writeZoomLevel(order, detailLevel); } else { @@ -297,12 +308,11 @@ public class ResourceLoadController implements Composer { } } }; - - return zoomListener; } private ResourcesLoadPanel buildPanel(ResourceLoadDisplayData dataToShow) { - return new ResourcesLoadPanel(dataToShow.getLoadTimeLines(), + return new ResourcesLoadPanel( + dataToShow.getLoadTimeLines(), timeTracker, parent, resourceLoadModel.isExpandResourceLoadViewCharts(), PaginationType.EXTERNAL_PAGINATION); @@ -310,66 +320,60 @@ public class ResourceLoadController implements Composer { } private List buildVisualizationModifiers() { - List result = new ArrayList(); - FilterTypeChanger filterTypeChanger = new FilterTypeChanger(onChange, - filterBy); + List result = new ArrayList<>(); + FilterTypeChanger filterTypeChanger = new FilterTypeChanger(onChange, filterBy); result.add(filterTypeChanger); // Only by dates and bandbox filter on global resources load - if (filterBy == null) { + if ( filterBy == null ) { LocalDate startDate = FilterUtils.readResourceLoadsStartDate(); LocalDate endDate = FilterUtils.readResourceLoadsEndDate(); User user = resourceLoadModel.getUser(); // Calculate filter based on user preferences - if (user != null) { - if (startDate == null - && !FilterUtils.hasResourceLoadsStartDateChanged()) { - if (user.getResourcesLoadFilterPeriodSince() != null) { - startDate = new LocalDate().minusMonths(user - .getResourcesLoadFilterPeriodSince()); + if ( user != null ) { + if ( startDate == null && !FilterUtils.hasResourceLoadsStartDateChanged() ) { + if ( user.getResourcesLoadFilterPeriodSince() != null ) { + startDate = new LocalDate().minusMonths(user.getResourcesLoadFilterPeriodSince()); } else { // Default filter start startDate = new LocalDate().minusDays(1); } } - if ((endDate == null) - && !FilterUtils.hasResourceLoadsEndDateChanged() - && (user.getResourcesLoadFilterPeriodTo() != null)) { - endDate = new LocalDate().plusMonths(user - .getResourcesLoadFilterPeriodTo()); + if ( (endDate == null) && + !FilterUtils.hasResourceLoadsEndDateChanged() && + (user.getResourcesLoadFilterPeriodTo() != null) ) { + + endDate = new LocalDate().plusMonths(user.getResourcesLoadFilterPeriodTo()); } } result.add(new ByDatesFilter(onChange, filterBy, startDate, endDate)); - List filterPairs = (List) FilterUtils - .readResourceLoadsBandbox(); - if ((filterPairs == null || filterPairs.isEmpty()) - && user.getResourcesLoadFilterCriterion() != null) { - filterPairs = new ArrayList(); + List filterPairs = FilterUtils.readResourceLoadsBandbox(); + if ( (filterPairs == null || filterPairs.isEmpty()) && user.getResourcesLoadFilterCriterion() != null ) { + filterPairs = new ArrayList<>(); filterPairs.add(new FilterPair( - ResourceAllocationFilterEnum.Criterion, user - .getResourcesLoadFilterCriterion() - .getFinderPattern(), user - .getResourcesLoadFilterCriterion())); + ResourceAllocationFilterEnum.Criterion, + user.getResourcesLoadFilterCriterion().getFinderPattern(), + user.getResourcesLoadFilterCriterion())); } - WorkersOrCriteriaBandbox bandbox = new WorkersOrCriteriaBandbox( - onChange, filterBy, filterTypeChanger, resourcesSearcher, filterPairs); + WorkersOrCriteriaBandbox bandbox = + new WorkersOrCriteriaBandbox(onChange, filterBy, filterTypeChanger, resourcesSearcher, filterPairs); result.add(bandbox); - result.add(new ByNamePaginator(onChange, filterBy, filterTypeChanger, - bandbox)); + result.add(new ByNamePaginator(onChange, filterBy, filterTypeChanger, bandbox)); } result.add(new LoadChart(onChange, filterBy)); + return result; } public interface IListenerAdder { - public Object addAndReturnListener(ResourcesLoadPanel panel); + Object addAndReturnListener(ResourcesLoadPanel panel); } private class GoToScheduleListener implements IListenerAdder { @@ -377,13 +381,14 @@ public class ResourceLoadController implements Composer { @Override public Object addAndReturnListener(ResourcesLoadPanel panel) { ISeeScheduledOfListener listener = new ISeeScheduledOfListener() { - @Override public void seeScheduleOf(LoadTimeLine taskLine) { onSeeScheduleOf(taskLine); } }; + panel.addSeeScheduledOfListener(listener); + return listener; } @@ -394,26 +399,25 @@ public class ResourceLoadController implements Composer { TaskElement task = (TaskElement) taskLine.getRole().getEntity(); Order order = resourceLoadModel.getOrderByTask(task); - if (resourceLoadModel.userCanRead(order, - SecurityUtils.getSessionUserLoginName())) { - if (order.isScheduled()) { - planningControllerEntryPoints.goToTaskResourceAllocation(order, - task); + if ( resourceLoadModel.userCanRead(order, SecurityUtils.getSessionUserLoginName()) ) { + if ( order.isScheduled() ) { + planningControllerEntryPoints.goToTaskResourceAllocation(order, task); } else { try { - Messagebox.show(_("The project has no scheduled elements"), - _("Information"), Messagebox.OK, - Messagebox.INFORMATION); + Messagebox.show( + _("The project has no scheduled elements"), _("Information"), + Messagebox.OK, Messagebox.INFORMATION); + } catch (InterruptedException e) { throw new RuntimeException(e); } } } else { try { - Messagebox - .show(_("You don't have read access to this project"), - _("Information"), Messagebox.OK, - Messagebox.INFORMATION); + Messagebox.show( + _("You don't have read access to this project"), _("Information"), + Messagebox.OK, Messagebox.INFORMATION); + } catch (InterruptedException e) { throw new RuntimeException(e); } @@ -456,8 +460,7 @@ public class ResourceLoadController implements Composer { } } - private static class FilterTypeChanger extends VisualizationModifier - implements IListenerAdder { + private static class FilterTypeChanger extends VisualizationModifier implements IListenerAdder { private boolean filterByResources = true; @@ -477,16 +480,17 @@ public class ResourceLoadController implements Composer { @Override public Object addAndReturnListener(ResourcesLoadPanel panel) { IFilterChangedListener listener = new IFilterChangedListener() { - @Override public void filterChanged(boolean newValue) { - if (filterByResources != newValue) { + if ( filterByResources != newValue ) { filterByResources = newValue; notifyChange(); } } }; + panel.addFilterListener(listener); + return listener; } } @@ -501,32 +505,33 @@ public class ResourceLoadController implements Composer { private final Datebox endBox = new Datebox(); - private ByDatesFilter(Runnable onChange, PlanningState filterBy, - LocalDate startDate, LocalDate endDate) { + private ByDatesFilter(Runnable onChange, PlanningState filterBy, LocalDate startDate, LocalDate endDate) { super(onChange, filterBy); - startDateValue = (isAppliedToOrder() || (startDate == null)) ? null - : startDate - .toDateTimeAtStartOfDay().toLocalDate(); - endDateValue = (endDate == null) ? null : endDate - .toDateMidnight().toLocalDate(); + + startDateValue = (isAppliedToOrder() || (startDate == null)) ? null : + startDate.toDateTimeAtStartOfDay().toLocalDate(); + + endDateValue = (endDate == null) ? null : endDate.toDateMidnight().toLocalDate(); } @Override void setup(ResourcesLoadPanel panel) { - if (isAppliedToOrder()) { + if ( isAppliedToOrder() ) { return; } + panel.setFirstOptionalFilter(buildTimeFilter()); } private Hbox buildTimeFilter() { startBox.setValue(asDate(startDateValue)); startBox.setWidth("100px"); + startBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { LocalDate newStart = toLocal(startBox.getValue()); - if (!ObjectUtils.equals(startDateValue, newStart)) { + if ( !ObjectUtils.equals(startDateValue, newStart) ) { startDateValue = newStart; FilterUtils.writeResourceLoadsStartDate(startDateValue); notifyChange(); @@ -536,11 +541,12 @@ public class ResourceLoadController implements Composer { endBox.setValue(asDate(endDateValue)); endBox.setWidth("100px"); + endBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { LocalDate newEnd = toLocal(endBox.getValue()); - if (!ObjectUtils.equals(endBox, newEnd)) { + if ( !ObjectUtils.equals(endBox, newEnd) ) { endDateValue = newEnd; FilterUtils.writeResourceLoadsEndDate(endDateValue); notifyChange(); @@ -554,6 +560,7 @@ public class ResourceLoadController implements Composer { hbox.appendChild(new Label(_("To") + ":")); hbox.appendChild(endBox); hbox.setAlign("center"); + return hbox; } @@ -565,16 +572,15 @@ public class ResourceLoadController implements Composer { } - private static abstract class DependingOnFiltering extends - VisualizationModifier { + private static abstract class DependingOnFiltering extends VisualizationModifier { private final FilterTypeChanger filterType; private boolean filteringByResource; - DependingOnFiltering(Runnable onChange, PlanningState filterBy, - FilterTypeChanger filterType) { + DependingOnFiltering(Runnable onChange, PlanningState filterBy, FilterTypeChanger filterType) { super(onChange, filterBy); + this.filterType = filterType; this.filteringByResource = filterType.isFilterByResources(); } @@ -585,7 +591,7 @@ public class ResourceLoadController implements Composer { @Override void checkDependencies() { - if (this.filteringByResource != filterType.isFilterByResources()) { + if ( this.filteringByResource != filterType.isFilterByResources() ) { this.filteringByResource = filterType.isFilterByResources(); filterTypeChanged(); } @@ -606,15 +612,17 @@ public class ResourceLoadController implements Composer { private Label label = new Label(); private WorkersOrCriteriaBandbox(Runnable onChange, - PlanningState filterBy, FilterTypeChanger filterType, - IResourcesSearcher resourcesSearcher, - List selectedFilters) { + PlanningState filterBy, + FilterTypeChanger filterType, + IResourcesSearcher resourcesSearcher, + List selectedFilters) { + super(onChange, filterBy, filterType); this.resourcesSearcher = resourcesSearcher; initBandbox(); - if ((selectedFilters != null) && !selectedFilters.isEmpty()) { + if ( (selectedFilters != null) && !selectedFilters.isEmpty() ) { for (FilterPair filterPair : selectedFilters) { bandBox.addSelectedElement(filterPair); } @@ -624,9 +632,10 @@ public class ResourceLoadController implements Composer { @Override void setup(ResourcesLoadPanel panel) { - if (isAppliedToOrder()) { + if ( isAppliedToOrder() ) { return; } + panel.setSecondOptionalFilter(buildBandboxFilterer()); } @@ -641,8 +650,7 @@ public class ResourceLoadController implements Composer { @Override public void onEvent(Event event) throws Exception { entitiesSelected = getSelected(); - FilterUtils.writeResourceLoadsParameters(bandBox - .getSelectedElements()); + FilterUtils.writeResourceLoadsParameters(bandBox.getSelectedElements()); notifyChange(); } }); @@ -659,11 +667,12 @@ public class ResourceLoadController implements Composer { private Label getLabel() { updateLabelValue(); + return label; } private void updateLabelValue() { - if (isFilteringByResource()) { + if ( isFilteringByResource() ) { label.setValue(_("Resources or criteria") + ":"); } else { label.setValue(_("Criteria") + ":"); @@ -671,7 +680,7 @@ public class ResourceLoadController implements Composer { } private String getFinderToUse() { - if (isFilteringByResource()) { + if ( isFilteringByResource() ) { return "resourceMultipleFiltersFinderByResourceAndCriterion"; } else { return "criterionMultipleFiltersFinder"; @@ -680,9 +689,10 @@ public class ResourceLoadController implements Composer { @Override protected void filterTypeChanged() { - if (isAppliedToOrder()) { + if ( isAppliedToOrder() ) { return; } + entitiesSelected = null; bandBox.setFinder(getFinderToUse()); updateLabelValue(); @@ -690,32 +700,30 @@ public class ResourceLoadController implements Composer { @Override void applyToParameters(ResourceLoadParameters parameters) { - if (!hasEntitiesSelected()) { + if ( !hasEntitiesSelected() ) { parameters.clearResourcesToShow(); parameters.clearCriteriaToShow(); - } else if (isFilteringByResource()) { + } else if ( isFilteringByResource() ) { parameters.setResourcesToShow(calculateResourcesToShow()); } else { - parameters.setCriteriaToShow(as(Criterion.class, - entitiesSelected)); + parameters.setCriteriaToShow(as(Criterion.class, entitiesSelected)); } } private List calculateResourcesToShow() { - List resources = new ArrayList(); - List criteria = new ArrayList(); + List resources = new ArrayList<>(); + List criteria = new ArrayList<>(); for (Object each : entitiesSelected) { - if (each instanceof Resource) { + if ( each instanceof Resource ) { resources.add((Resource) each); } else { criteria.add((Criterion) each); } } - if (!criteria.isEmpty()) { - resources.addAll(resourcesSearcher.searchBoth() - .byCriteria(criteria).execute()); + if ( !criteria.isEmpty()) { + resources.addAll(resourcesSearcher.searchBoth().byCriteria(criteria).execute()); } return resources; @@ -726,19 +734,19 @@ public class ResourceLoadController implements Composer { } private List getSelected() { - List result = new ArrayList(); + List result = new ArrayList<>(); @SuppressWarnings("unchecked") List filterPairList = bandBox.getSelectedElements(); for (FilterPair filterPair : filterPairList) { result.add(filterPair.getValue()); } + return result; } } - private static class ByNamePaginator extends DependingOnFiltering - implements IListenerAdder { + private static class ByNamePaginator extends DependingOnFiltering implements IListenerAdder { private static final int ALL = -1; @@ -748,9 +756,11 @@ public class ResourceLoadController implements Composer { private List allEntitiesShown = null; - public ByNamePaginator(Runnable onChange, PlanningState filterBy, - FilterTypeChanger filterTypeChanger, - WorkersOrCriteriaBandbox bandbox) { + public ByNamePaginator(Runnable onChange, + PlanningState filterBy, + FilterTypeChanger filterTypeChanger, + WorkersOrCriteriaBandbox bandbox) { + super(onChange, filterBy, filterTypeChanger); this.bandbox = bandbox; this.currentPosition = initialPage(); @@ -765,20 +775,22 @@ public class ResourceLoadController implements Composer { IPaginationFilterChangedListener listener = new IPaginationFilterChangedListener() { @Override public void filterChanged(int newPosition) { - if (currentPosition != newPosition) { + if ( currentPosition != newPosition ) { currentPosition = newPosition; notifyChange(); } } }; + panel.addPaginationFilterListener(listener); + return listener; } @Override void checkDependencies() { super.checkDependencies(); - if (bandbox.hasEntitiesSelected()) { + if ( bandbox.hasEntitiesSelected() ) { this.currentPosition = ALL; } } @@ -796,43 +808,47 @@ public class ResourceLoadController implements Composer { @Override void updateUI(ResourcesLoadPanel panel, ResourceLoadDisplayData generatedData) { + panel.setInternalPaginationDisabled(bandbox.hasEntitiesSelected()); - Paginator paginator = generatedData - .getPaginator(); + Paginator paginator = generatedData.getPaginator(); List newAllEntities = paginator.getAll(); - if (this.allEntitiesShown == null - || !equivalent(this.allEntitiesShown, newAllEntities)) { + + if ( this.allEntitiesShown == null || !equivalent(this.allEntitiesShown, newAllEntities) ) { this.currentPosition = initialPage(); this.allEntitiesShown = newAllEntities; - updatePages(panel.getPaginationFilterCombobox(), - pagesByName(this.allEntitiesShown, - paginator.getPageSize())); + + updatePages( + panel.getPaginationFilterCombobox(), + pagesByName(this.allEntitiesShown, paginator.getPageSize())); } } - private boolean equivalent(List a, - List b) { - if (a == null || b == null) { + private boolean equivalent(List a, List b) { + if ( a == null || b == null ) { return false; } - if (a.size() != b.size()) { + + if ( a.size() != b.size() ) { return false; } + for (int i = 0; i < a.size(); i++) { BaseEntity aElement = a.get(i); BaseEntity bElement = b.get(i); - if (!ObjectUtils.equals(aElement.getId(), bElement.getId())) { + + if ( !ObjectUtils.equals(aElement.getId(), bElement.getId()) ) { return false; } } + return true; } - private void updatePages(Combobox filterByNameCombo, - List pages) { - if (filterByNameCombo == null) { + private void updatePages(Combobox filterByNameCombo, List pages) { + if ( filterByNameCombo == null ) { return; } + filterByNameCombo.getChildren().clear(); Comboitem lastItem = new Comboitem(); @@ -845,10 +861,9 @@ public class ResourceLoadController implements Composer { filterByNameCombo.appendChild(each); } - if (currentPosition >= 0 && currentPosition < pages.size()) { - filterByNameCombo - .setSelectedItemApi(pages.get(currentPosition)); - } else if (currentPosition == ALL) { + if ( currentPosition >= 0 && currentPosition < pages.size() ) { + filterByNameCombo.setSelectedItemApi(pages.get(currentPosition)); + } else if ( currentPosition == ALL ) { filterByNameCombo.setSelectedItemApi(lastItem); } else { filterByNameCombo.setSelectedIndex(0); @@ -856,57 +871,53 @@ public class ResourceLoadController implements Composer { } private List pagesByName(List list, int pageSize) { - if (list.isEmpty()) { - return new ArrayList(); + if ( list.isEmpty() ) { + return new ArrayList<>(); } - Object first = list.get(0); - if (first instanceof Resource) { - return pagesByName(as(Resource.class, list), pageSize, - new INameExtractor() { + Object first = list.get(0); + if ( first instanceof Resource ) { + return pagesByName(as(Resource.class, list), pageSize, new INameExtractor() { @Override public String getNameOf(Resource resource) { return resource.getName(); } }); - } else { - return pagesByName(as(Criterion.class, list), pageSize, - new INameExtractor() { + } else { + return pagesByName(as(Criterion.class, list), pageSize, new INameExtractor() { @Override public String getNameOf(Criterion criterion) { - return criterion.getType().getName() + ": " - + criterion.getName(); + return criterion.getType().getName() + ": " + criterion.getName(); } }); } } interface INameExtractor { - public String getNameOf(T value); + String getNameOf(T value); } - private List pagesByName(List elements, - int pageSize, - INameExtractor nameExtractor) { - List result = new ArrayList(); + private List pagesByName(List elements, int pageSize, INameExtractor nameExtractor) { + List result = new ArrayList<>(); + for (int startPos = 0; startPos < elements.size(); startPos += pageSize) { - int endPos = Math.min(startPos + pageSize - 1, - elements.size() - 1); + int endPos = Math.min(startPos + pageSize - 1, elements.size() - 1); String first = nameExtractor.getNameOf(elements.get(startPos)); String end = nameExtractor.getNameOf(elements.get(endPos)); Comboitem item = buildPageCombo(startPos, first, end); result.add(item); } + return result; } - private Comboitem buildPageCombo(int startPosition, String first, - String end) { + private Comboitem buildPageCombo(int startPosition, String first, String end) { Comboitem result = new Comboitem(); result.setLabel(first.substring(0, 1) + " - " + end.substring(0, 1)); result.setDescription(first + " - " + end); result.setValue(startPosition); + return result; } @@ -917,6 +928,7 @@ public class ResourceLoadController implements Composer { for (Object each : entities) { result.add(klass.cast(each)); } + return result; } @@ -933,30 +945,28 @@ public class ResourceLoadController implements Composer { } void setup(ResourcesLoadPanel panel) { - panel.setLoadChart(buildChart(panel, emitter)); + panel.setLoadChart(buildChart(emitter)); } public Object addAndReturnListener(ResourcesLoadPanel panel) { IChartVisibilityChangedListener visibilityChangedListener = fillOnChartVisibilityChange(); panel.addChartVisibilityListener(visibilityChangedListener); + return visibilityChangedListener; } private IChartVisibilityChangedListener fillOnChartVisibilityChange() { - IChartVisibilityChangedListener result = new IChartVisibilityChangedListener() { - + return new IChartVisibilityChangedListener() { @Override public void chartVisibilityChanged(final boolean visible) { - if (visible && loadChart != null) { + if ( visible && loadChart != null ) { loadChart.fillChart(); } } }; - return result; } - private Tabbox buildChart(ResourcesLoadPanel resourcesLoadPanel, - Emitter timePlot) { + private Tabbox buildChart(Emitter timePlot) { Tabbox chartComponent = new Tabbox(); chartComponent.setOrient("vertical"); chartComponent.setHeight("200px"); @@ -969,61 +979,55 @@ public class ResourceLoadController implements Composer { Tabpanels chartTabpanels = new Tabpanels(); Tabpanel loadChartPannel = new Tabpanel(); // avoid adding Timeplot since it has some pending issues - CompanyPlanningModel.appendLoadChartAndLegend(loadChartPannel, - timePlot); + CompanyPlanningModel.appendLoadChartAndLegend(loadChartPannel, timePlot); chartTabpanels.appendChild(loadChartPannel); chartComponent.appendChild(chartTabpanels); + return chartComponent; } @Override - void updateUI(ResourcesLoadPanel panel, - ResourceLoadDisplayData generatedData) { + void updateUI(ResourcesLoadPanel panel, ResourceLoadDisplayData generatedData) { TimeTracker timeTracker = panel.getTimeTracker(); zoomLevelListener = fillOnZoomChange(panel); timeTracker.addZoomListener(zoomLevelListener); - Timeplot newLoadChart = buildLoadChart(panel, generatedData, - timeTracker); + Timeplot newLoadChart = buildLoadChart(panel, generatedData, timeTracker); emitter.emit(newLoadChart); } - private Timeplot buildLoadChart(ResourcesLoadPanel resourcesLoadPanel, - ResourceLoadDisplayData generatedData, TimeTracker timeTracker) { + private Timeplot buildLoadChart( + ResourcesLoadPanel resourcesLoadPanel, ResourceLoadDisplayData generatedData, TimeTracker timeTracker) { + Timeplot chartLoadTimeplot = createEmptyTimeplot(); - ResourceLoadChartFiller chartFiller = - new ResourceLoadChartFiller(generatedData); - loadChart = new Chart(chartLoadTimeplot, - chartFiller, timeTracker); + ResourceLoadChartFiller chartFiller = new ResourceLoadChartFiller(generatedData); + loadChart = new Chart(chartLoadTimeplot, chartFiller, timeTracker); loadChart.setZoomLevel(timeTracker.getDetailLevel()); chartFiller.initializeResources(); - if (resourcesLoadPanel.isVisibleChart()) { + if ( resourcesLoadPanel.isVisibleChart() ) { loadChart.fillChart(); } + return chartLoadTimeplot; } - private IZoomLevelChangedListener fillOnZoomChange( - final ResourcesLoadPanel resourcesLoadPanel) { - - IZoomLevelChangedListener zoomListener = new IZoomLevelChangedListener() { - + private IZoomLevelChangedListener fillOnZoomChange(final ResourcesLoadPanel resourcesLoadPanel) { + return new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel detailLevel) { - if (loadChart == null) { + if ( loadChart == null ) { return; } + loadChart.setZoomLevel(detailLevel); - if (resourcesLoadPanel.isVisibleChart()) { + if ( resourcesLoadPanel.isVisibleChart() ) { loadChart.fillChart(); } adjustZoomPositionScroll(resourcesLoadPanel); } }; - - return zoomListener; } } @@ -1034,6 +1038,7 @@ public class ResourceLoadController implements Composer { private Timeplot createEmptyTimeplot() { Timeplot timeplot = new Timeplot(); timeplot.appendChild(new Plotinfo()); + return timeplot; } @@ -1054,10 +1059,9 @@ public class ResourceLoadController implements Composer { @Override protected ILoadChartData getDataOn(Interval interval) { - List assignments = generatedData - .getDayAssignmentsConsidered(); - return new ResourceLoadChartData(assignments, - resources, interval.getStart(), interval.getFinish()); + List assignments = generatedData.getDayAssignmentsConsidered(); + + return new ResourceLoadChartData(assignments, resources, interval.getStart(), interval.getFinish()); } private void initializeResources() { @@ -1068,10 +1072,9 @@ public class ResourceLoadController implements Composer { } private static class ListenerTracker { - private final List trackedListeners = new ArrayList(); + private final List trackedListeners = new ArrayList<>(); - public void addListeners(ResourcesLoadPanel panel, - Iterable listeners) { + public void addListeners(ResourcesLoadPanel panel, Iterable listeners) { for (IListenerAdder each : listeners) { Object listener = each.addAndReturnListener(panel); trackedListeners.add(listener); @@ -1080,13 +1083,12 @@ public class ResourceLoadController implements Composer { } private void addCommands(ResourcesLoadPanel resourcesLoadPanel) { - resourcesLoadPanel.add(commands.toArray(new IToolbarCommand[commands - .size()])); + resourcesLoadPanel.add(commands.toArray(new IToolbarCommand[commands.size()])); } private BankHolidaysMarker createBankHolidaysMarker() { - BaseCalendar defaultCalendar = configurationDAO.getConfiguration() - .getDefaultCalendar(); + BaseCalendar defaultCalendar = configurationDAO.getConfiguration().getDefaultCalendar(); + return BankHolidaysMarker.create(defaultCalendar); } @@ -1095,19 +1097,15 @@ public class ResourceLoadController implements Composer { } PlanningState createPlanningState(final Order order) { - return transactionService - .runOnReadOnlyTransaction(new IOnTransaction() { - - @Override - public PlanningState execute() { - return planningStateCreator.retrieveOrCreate( - parent.getDesktop(), order); - } - }); + return transactionService.runOnReadOnlyTransaction(new IOnTransaction() { + @Override + public PlanningState execute() { + return planningStateCreator.retrieveOrCreate(parent.getDesktop(), order); + } + }); } - public void setPlanningControllerEntryPoints( - IOrderPlanningGate planningControllerEntryPoints) { + public void setPlanningControllerEntryPoints(IOrderPlanningGate planningControllerEntryPoints) { this.planningControllerEntryPoints = planningControllerEntryPoints; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java index e3e6782ed..dea71defa 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java @@ -42,10 +42,8 @@ import java.util.Set; import java.util.concurrent.Callable; import org.joda.time.LocalDate; -import org.libreplan.business.calendars.daos.IBaseCalendarDAO; import org.libreplan.business.calendars.entities.ResourceCalendar; import org.libreplan.business.common.BaseEntity; -import org.libreplan.business.common.IAdHocTransactionService; import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.orders.daos.IOrderDAO; import org.libreplan.business.orders.entities.Order; @@ -118,27 +116,25 @@ public class ResourceLoadModel implements IResourceLoadModel { @Autowired private IScenarioManager scenarioManager; - @Autowired - private IBaseCalendarDAO baseCalendarDAO; - - @Autowired - private IAdHocTransactionService transactionService; - @Override @Transactional(readOnly = true) - public ResourceLoadDisplayData calculateDataToDisplay( - ResourceLoadParameters parameters) { + public ResourceLoadDisplayData calculateDataToDisplay(ResourceLoadParameters parameters) { PlanningState planningState = parameters.getPlanningState(); - if (planningState != null) { + + if ( planningState != null ) { planningState.reattach(); planningState.reassociateResourcesWithSession(); } + ResourceAllocationsFinder allocationsFinder = create(parameters); List loadTimeLines = allocationsFinder.buildTimeLines(); - return new ResourceLoadDisplayData(loadTimeLines, + + return new ResourceLoadDisplayData( + loadTimeLines, parameters.getInitDateFilter(), - parameters.getEndDateFilter(), allocationsFinder.getPaginator(), + parameters.getEndDateFilter(), + allocationsFinder.getPaginator(), allocationsFinder.lazilyGetResourcesIncluded(), allocationsFinder.lazilyGetAssignmentsShown()); } @@ -147,26 +143,24 @@ public class ResourceLoadModel implements IResourceLoadModel { @Override @Transactional(readOnly = true) public Order getOrderByTask(TaskElement task) { - Order result = orderDAO.loadOrderAvoidingProxyFor(task - .getOrderElement()); + Order result = orderDAO.loadOrderAvoidingProxyFor(task.getOrderElement()); result.useSchedulingDataFor(scenarioManager.getCurrent()); + return result; } @Override @Transactional(readOnly = true) public boolean userCanRead(Order order, String loginName) { - if (SecurityUtils.isSuperuserOrUserInRoles( - UserRole.ROLE_READ_ALL_PROJECTS, - UserRole.ROLE_EDIT_ALL_PROJECTS)) { + if ( SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_READ_ALL_PROJECTS, UserRole.ROLE_EDIT_ALL_PROJECTS)) { return true; } + try { User user = userDAO.findByLoginName(loginName); - for (OrderAuthorization authorization : orderAuthorizationDAO - .listByOrderUserAndItsProfiles(order, user)) { - if (authorization.getAuthorizationType() == OrderAuthorizationType.READ_AUTHORIZATION - || authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION) { + for (OrderAuthorization authorization : orderAuthorizationDAO.listByOrderUserAndItsProfiles(order, user)) { + if ( authorization.getAuthorizationType() == OrderAuthorizationType.READ_AUTHORIZATION || + authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION ) { return true; } } @@ -175,12 +169,12 @@ public class ResourceLoadModel implements IResourceLoadModel { // isn't a logged user // anyway, if it happenned we don't allow the user to pass } + return false; } public ResourceAllocationsFinder create(ResourceLoadParameters parameters) { - return parameters.isFilterByResources() ? new ByResourceFinder( - parameters) : new ByCriterionFinder(parameters); + return parameters.isFilterByResources() ? new ByResourceFinder(parameters) : new ByCriterionFinder(parameters); } private abstract class ResourceAllocationsFinder { @@ -205,6 +199,7 @@ public class ResourceLoadModel implements IResourceLoadModel { BaseCalendarModel.forceLoadBaseCalendar(calendar); resource.getAssignments().size(); } + return resources; } @@ -215,7 +210,6 @@ public class ResourceLoadModel implements IResourceLoadModel { public Callable> lazilyGetAssignmentsShown() { return new Callable>() { - @Override public List call() throws Exception { return getAssignmentsShown(); @@ -225,15 +219,16 @@ public class ResourceLoadModel implements IResourceLoadModel { } private List getAssignmentsShown() { - Set result = new HashSet(); + Set result = new HashSet<>(); Map>> foundAllocations = getFoundAllocations(); - for (Entry>> each : foundAllocations - .entrySet()) { + + for (Entry>> each : foundAllocations.entrySet()) { for (ResourceAllocation eachAllocation : each.getValue()) { result.addAll(eachAllocation.getAssignments()); } } - return new ArrayList(result); + + return new ArrayList<>(result); } abstract List buildTimeLines(); @@ -244,25 +239,25 @@ public class ResourceLoadModel implements IResourceLoadModel { Scenario getCurrentScenario() { PlanningState state = parameters.getPlanningState(); - if (state != null) { + if ( state != null ) { return state.getCurrentScenario(); } + return scenarioManager.getCurrent(); } Collection> doReplacementsIfNeeded( - Collection> allocations, - IAllocationCriteria criteria) { - if (parameters.getPlanningState() == null) { + Collection> allocations, IAllocationCriteria criteria) { + + if ( parameters.getPlanningState() == null ) { return allocations; } - return parameters.getPlanningState().replaceByCurrentOnes( - allocations, criteria); + + return parameters.getPlanningState().replaceByCurrentOnes(allocations, criteria); } protected IAllocationCriteria onInterval() { - return new TaskOnInterval(parameters.getInitDateFilter(), - parameters.getEndDateFilter()); + return new TaskOnInterval(parameters.getInitDateFilter(), parameters.getEndDateFilter()); } } @@ -275,8 +270,7 @@ public class ResourceLoadModel implements IResourceLoadModel { public ByResourceFinder(ResourceLoadParameters parameters) { super(parameters); this.resources = resourcesToShow(); - this.allocationsByResource = eachWithAllocations(this.resources - .getForCurrentPage()); + this.allocationsByResource = eachWithAllocations(this.resources.getForCurrentPage()); } @Override @@ -296,17 +290,16 @@ public class ResourceLoadModel implements IResourceLoadModel { @Override List buildTimeLines() { - return new ByResourceLoadTimesLinesBuilder(parameters) - .buildGroupsByResource(getFoundAllocations()); + return new ByResourceLoadTimesLinesBuilder(parameters).buildGroupsByResource(getFoundAllocations()); } private Paginator resourcesToShow() { - return parameters.getEntities(Resource.class, + return parameters.getEntities( + Resource.class, new Callable>() { - @Override public List call() throws Exception { - if (parameters.thereIsCurrentOrder()) { + if ( parameters.thereIsCurrentOrder() ) { return resourcesForActiveTasks(); } else { return allResourcesActiveBetween( @@ -316,56 +309,55 @@ public class ResourceLoadModel implements IResourceLoadModel { } private List resourcesForActiveTasks() { - return Resource.sortByName(parameters - .getPlanningState() - .getResourcesRelatedWithAllocations()); + return Resource.sortByName( + parameters + .getPlanningState() + .getResourcesRelatedWithAllocations()); } - private List allResourcesActiveBetween( - LocalDate startDate, LocalDate endDate) { + private List allResourcesActiveBetween(LocalDate startDate, LocalDate endDate) { List allResources = allResources(); - if (startDate == null && endDate == null) { + if ( startDate == null && endDate == null ) { return allResources; } - List resources = new ArrayList(); + List resources = new ArrayList<>(); for (Resource resource : allResources) { - if (resource - .isActiveBetween(startDate, endDate)) { + if ( resource.isActiveBetween(startDate, endDate) ) { resources.add(resource); } } + return resources; } private List allResources() { - return Resource.sortByName(resourcesDAO - .list(Resource.class)); + return Resource.sortByName(resourcesDAO.list(Resource.class)); } - }, new IReattacher() { - + }, + new IReattacher() { @Override public Resource reattach(Resource entity) { - return resourcesDAO.findExistingEntity(entity - .getId()); + return resourcesDAO.findExistingEntity(entity.getId()); } }); } - private Map>> eachWithAllocations( - List allResources) { - Map>> result = new LinkedHashMap>>(); + private Map>> eachWithAllocations(List allResources) { + Map>> result = new LinkedHashMap<>(); for (Resource resource : allResources) { - IAllocationCriteria criteria = and(onInterval(), - relatedToResource(resource)); - result.put(resource, ResourceAllocation - .sortedByStartDate(doReplacementsIfNeeded( - resourceAllocationDAO.findAllocationsRelatedTo( - getCurrentScenario(), resource, - parameters.getInitDateFilter(), - parameters.getEndDateFilter()), - criteria))); + IAllocationCriteria criteria = and(onInterval(), relatedToResource(resource)); + result.put(resource, + ResourceAllocation.sortedByStartDate( + doReplacementsIfNeeded( + resourceAllocationDAO.findAllocationsRelatedTo( + getCurrentScenario(), + resource, + parameters.getInitDateFilter(), + parameters.getEndDateFilter()), + criteria))); } + return result; } @@ -384,8 +376,7 @@ public class ResourceLoadModel implements IResourceLoadModel { public ByCriterionFinder(ResourceLoadParameters parameters) { super(parameters); this.criterions = findCriterions(); - this.allocationsByCriterion = allocationsByCriterion(this.criterions - .getForCurrentPage()); + this.allocationsByCriterion = allocationsByCriterion(this.criterions.getForCurrentPage()); } @Override @@ -395,14 +386,14 @@ public class ResourceLoadModel implements IResourceLoadModel { @Override List getResourcesIncluded() { - Set result = new HashSet(); - for (List> each : getFoundAllocations() - .values()) { + Set result = new HashSet<>(); + for (List> each : getFoundAllocations().values()) { for (ResourceAllocation eachAllocation : each) { result.addAll(eachAllocation.getAssociatedResources()); } } - return new ArrayList(result); + + return new ArrayList<>(result); } @Override @@ -412,112 +403,109 @@ public class ResourceLoadModel implements IResourceLoadModel { @Override List buildTimeLines() { - return new ByCriterionLoadTimesLinesBuilder(parameters) - .buildGroupsByCriterion(getFoundAllocations()); + return new ByCriterionLoadTimesLinesBuilder(parameters).buildGroupsByCriterion(getFoundAllocations()); } private Paginator findCriterions() { - return parameters.getEntities(Criterion.class, - criterionRetriever(), new IReattacher() { - - @Override - public Criterion reattach(Criterion entity) { - criterionDAO.reattachUnmodifiedEntity(entity); - return entity; - } - }); + return parameters.getEntities(Criterion.class, criterionRetriever(), new IReattacher() { + @Override + public Criterion reattach(Criterion entity) { + criterionDAO.reattachUnmodifiedEntity(entity); + return entity; + } + }); } Callable> criterionRetriever() { return new Callable>() { - @Override public List call() throws Exception { - return Criterion - .sortByInclusionTypeAndName(findCriterions()); + return Criterion.sortByInclusionTypeAndName(findCriterions()); } private Collection findCriterions() { - if (parameters.thereIsCurrentOrder()) { + if ( parameters.thereIsCurrentOrder() ) { + List tasks = justTasks(parameters .getCurrentOrder() .getAllChildrenAssociatedTaskElements()); + return getCriterionsOn(tasks); } else { return findAllocationsGroupedByCriteria().keySet(); } } - private List getCriterionsOn( - Collection tasks) { - Set result = new LinkedHashSet(); + private List getCriterionsOn(Collection tasks) { + Set result = new LinkedHashSet<>(); for (Task eachTask : tasks) { result.addAll(getCriterionsOn(eachTask)); } - return new ArrayList(result); + + return new ArrayList<>(result); } private Set getCriterionsOn(Task task) { - Set result = new LinkedHashSet(); - for (GenericResourceAllocation eachAllocation : onlyGeneric(task - .getSatisfiedResourceAllocations())) { + Set result = new LinkedHashSet<>(); + + for (GenericResourceAllocation eachAllocation : onlyGeneric(task.getSatisfiedResourceAllocations())) result.addAll(eachAllocation.getCriterions()); - } + return result; } }; } - private Map>> allocationsByCriterion( - List criterions) { - return withAssociatedSpecific(findAllocationsGroupedByCriteria( - scenarioManager.getCurrent(), criterions)); + private Map>> allocationsByCriterion(List criterions) { + return withAssociatedSpecific(findAllocationsGroupedByCriteria(criterions)); } private Map>> findAllocationsGroupedByCriteria( - Scenario onScenario, List relatedWith) { - Map>> result = new LinkedHashMap>>(); + List relatedWith) { + + Map>> result = new LinkedHashMap<>(); for (Criterion criterion : relatedWith) { - IAllocationCriteria criteria = and(onInterval(), - new RelatedWith(criterion)); + IAllocationCriteria criteria = and(onInterval(), new RelatedWith(criterion)); + result.put( criterion, ResourceAllocation.sortedByStartDate(doReplacementsIfNeeded( - resourceAllocationDAO - .findGenericAllocationsRelatedToCriterion( - getCurrentScenario(), - criterion, asDate(parameters - .getInitDateFilter()), - asDate(parameters - .getEndDateFilter())), + resourceAllocationDAO.findGenericAllocationsRelatedToCriterion( + getCurrentScenario(), + criterion, + asDate(parameters.getInitDateFilter()), + asDate(parameters.getEndDateFilter())), criteria))); } + return result; } private Map>> withAssociatedSpecific( Map>> genericAllocationsByCriterion) { - Map>> result = new HashMap>>(); - for (Entry>> each : genericAllocationsByCriterion - .entrySet()) { - List> both = new ArrayList>(); + + Map>> result = new HashMap<>(); + for (Entry>> each : genericAllocationsByCriterion.entrySet()) { + List> both = new ArrayList<>(); both.addAll(each.getValue()); - both.addAll(doReplacementsIfNeeded(resourceAllocationDAO - .findSpecificAllocationsRelatedTo(getCurrentScenario(), + + both.addAll(doReplacementsIfNeeded( + resourceAllocationDAO.findSpecificAllocationsRelatedTo( + getCurrentScenario(), each.getKey(), asDate(parameters.getInitDateFilter()), asDate(parameters.getEndDateFilter())), and(onInterval(), specificRelatedTo(each.getKey())))); result.put(each.getKey(), both); } + return result; } private IAllocationCriteria specificRelatedTo(Criterion key) { - return new SpecificRelatedWithCriterionOnInterval(key, - parameters.getInitDateFilter(), - parameters.getEndDateFilter()); + return new SpecificRelatedWithCriterionOnInterval( + key, parameters.getInitDateFilter(), parameters.getEndDateFilter()); } private Map> findAllocationsGroupedByCriteria() { @@ -530,22 +518,23 @@ public class ResourceLoadModel implements IResourceLoadModel { private Map> doReplacementsIfNeeded( Map> map) { - if (!parameters.thereIsCurrentOrder()) { + + if ( !parameters.thereIsCurrentOrder() ) { return map; } - Map> result = new HashMap>(); - for (Entry> each : map - .entrySet()) { - IAllocationCriteria criteria = and(onInterval(), - new RelatedWith(each.getKey())); - List> replaced = parameters - .getPlanningState().replaceByCurrentOnes( - each.getValue(), criteria); - if (!replaced.isEmpty()) { - result.put(each.getKey(), ResourceAllocation.getOfType( - GenericResourceAllocation.class, replaced)); + + Map> result = new HashMap<>(); + for (Entry> each : map.entrySet()) { + IAllocationCriteria criteria = and(onInterval(), new RelatedWith(each.getKey())); + + List> replaced = + parameters.getPlanningState().replaceByCurrentOnes(each.getValue(), criteria); + + if ( !replaced.isEmpty() ) { + result.put(each.getKey(), ResourceAllocation.getOfType(GenericResourceAllocation.class, replaced)); } } + return result; } @@ -558,46 +547,49 @@ public class ResourceLoadModel implements IResourceLoadModel { public LoadTimeLinesBuilder(ResourceLoadParameters parameters) { this.parameters = parameters; - this.periodBuilderFactory = new PeriodBuilderFactory( - parameters.getInitDateFilter(), - parameters.getEndDateFilter()); + this.periodBuilderFactory = + new PeriodBuilderFactory(parameters.getInitDateFilter(), parameters.getEndDateFilter()); } TimeLineRole getCurrentTimeLineRole(BaseEntity entity) { - return new TimeLineRole(entity); + return new TimeLineRole<>(entity); } - LoadTimeLine buildGroupFor(Resource resource, - List> sortedByStartDate) { + LoadTimeLine buildGroupFor(Resource resource, List> sortedByStartDate) { + TimeLineRole role = getCurrentTimeLineRole(resource); - LoadTimeLine result = new LoadTimeLine(buildTimeLine(resource, - resource.getName(), sortedByStartDate, "resource", role), + + LoadTimeLine result = new LoadTimeLine( + buildTimeLine(resource, resource.getName(), sortedByStartDate, "resource", role), buildSecondLevel(resource, sortedByStartDate)); + return result; } - private List buildSecondLevel(Resource resource, - List> sortedByStartDate) { - List result = new ArrayList(); + private List buildSecondLevel( + Resource resource, List> sortedByStartDate) { + + List result = new ArrayList<>(); Map>> byOrder = byOrder(sortedByStartDate); - if (thereIsCurrentOrder()) { - List> forCurrentOrder = byOrder - .get(getCurrentOrder()); - if (forCurrentOrder != null) { - result.addAll(buildTimeLinesForOrder(resource, - forCurrentOrder)); + if ( thereIsCurrentOrder() ) { + List> forCurrentOrder = byOrder.get(getCurrentOrder()); + + if ( forCurrentOrder != null ) { + result.addAll(buildTimeLinesForOrder(resource, forCurrentOrder)); } + byOrder.remove(getCurrentOrder()); // build time lines for other orders - LoadTimeLine lineOthersOrders = buildTimeLinesForOtherOrders( - resource, byOrder); - if (lineOthersOrders != null) { + LoadTimeLine lineOthersOrders = buildTimeLinesForOtherOrders(resource, byOrder); + + if ( lineOthersOrders != null ) { result.add(lineOthersOrders); } } else { result.addAll(buildTimeLinesGroupForOrder(resource, byOrder)); } + return result; } @@ -609,133 +601,139 @@ public class ResourceLoadModel implements IResourceLoadModel { return parameters.thereIsCurrentOrder(); } - private List buildTimeLinesForOrder(Resource resource, - List> sortedByStartDate) { - List result = new ArrayList(); - result.addAll(buildTimeLinesForEachTask(resource, - onlySpecific(sortedByStartDate))); - result.addAll(buildTimeLinesForEachCriterion(resource, - onlyGeneric(sortedByStartDate))); + private List buildTimeLinesForOrder( + Resource resource, List> sortedByStartDate) { + + List result = new ArrayList<>(); + result.addAll(buildTimeLinesForEachTask(resource, onlySpecific(sortedByStartDate))); + result.addAll(buildTimeLinesForEachCriterion(resource, onlyGeneric(sortedByStartDate))); Collections.sort(result, LoadTimeLine.byStartAndEndDate()); + return result; } - private List buildTimeLinesForEachTask(Resource resource, - List sortedByStartDate) { + private List buildTimeLinesForEachTask( + Resource resource, List sortedByStartDate) { - List> listOnlySpecific = new ArrayList>( - sortedByStartDate); - Map>> byTask = ResourceAllocation - .byTask(listOnlySpecific); + List> listOnlySpecific = new ArrayList>(sortedByStartDate); + Map>> byTask = ResourceAllocation.byTask(listOnlySpecific); - List secondLevel = new ArrayList(); - for (Entry>> entry : byTask - .entrySet()) { + List secondLevel = new ArrayList<>(); + for (Entry>> entry : byTask.entrySet()) { Task task = entry.getKey(); TimeLineRole role = getCurrentTimeLineRole(task); - LoadTimeLine timeLine = buildTimeLine(resource, task.getName(), - entry.getValue(), "specific", role); - if (!timeLine.isEmpty()) { + LoadTimeLine timeLine = buildTimeLine(resource, task.getName(), entry.getValue(), "specific", role); + if ( !timeLine.isEmpty() ) { secondLevel.add(timeLine); } } + return secondLevel; } private List buildTimeLinesForEachCriterion( - Resource resource, - List sortdByStartDate) { - Map, List> byCriterions = GenericResourceAllocation - .byCriterions(sortdByStartDate); + Resource resource, List sortdByStartDate) { - List result = new ArrayList(); - for (Entry, List> entry : byCriterions - .entrySet()) { + Map, List> byCriterions = + GenericResourceAllocation.byCriterions(sortdByStartDate); - Map>> byTask = ResourceAllocation - .byTask(new ArrayList>(entry - .getValue())); + List result = new ArrayList<>(); + for (Entry, List> entry : byCriterions.entrySet()) { - for (Entry>> entryTask : byTask - .entrySet()) { + Map>> byTask = + ResourceAllocation.byTask(new ArrayList>(entry.getValue())); + + for (Entry>> entryTask : byTask.entrySet()) { Task task = entryTask.getKey(); - List resouceAllocations = onlyGeneric(entryTask - .getValue()); + List resouceAllocations = onlyGeneric(entryTask.getValue()); TimeLineRole role = getCurrentTimeLineRole(task); - LoadTimeLine timeLine = buildTimeLine(entry.getKey(), task, - resource, "generic", resouceAllocations, role); - if (!timeLine.isEmpty()) { + + LoadTimeLine timeLine = + buildTimeLine(entry.getKey(), task, resource, "generic", resouceAllocations, role); + + if ( !timeLine.isEmpty() ) { result.add(timeLine); } } } + return result; } private LoadTimeLine buildTimeLine(Collection criterions, - Task task, Resource resource, String type, - List allocationsSortedByStartDate, - TimeLineRole role) { - LoadPeriodGeneratorFactory periodGeneratorFactory = LoadPeriodGenerator - .onResourceSatisfying(resource, criterions); - List loadPeriods = periodBuilderFactory.build( - periodGeneratorFactory, allocationsSortedByStartDate); - return new LoadTimeLine(getName(criterions, task), loadPeriods, - type, role); + Task task, Resource resource, + String type, + List allocationsSortedByStartDate, + TimeLineRole role) { + + LoadPeriodGeneratorFactory periodGeneratorFactory = + LoadPeriodGenerator.onResourceSatisfying(resource, criterions); + + List loadPeriods = + periodBuilderFactory.build(periodGeneratorFactory, allocationsSortedByStartDate); + + return new LoadTimeLine(getName(criterions, task), loadPeriods, type, role); } String getName(Collection criterions, Task task) { String prefix = task.getName(); + return (prefix + " :: " + Criterion.getCaptionFor(criterions)); } - private LoadTimeLine buildTimeLinesForOtherOrders(Resource resource, - Map>> byOrder) { + private LoadTimeLine buildTimeLinesForOtherOrders( + Resource resource, Map>> byOrder) { + List> resourceAllocations = getAllSortedValues(byOrder); - if (resourceAllocations.isEmpty()) { + if ( resourceAllocations.isEmpty() ) { return null; } + TimeLineRole role = getCurrentTimeLineRole(null); - LoadTimeLine group = new LoadTimeLine( - buildTimeLine(resource, _("Other projects"), - resourceAllocations, "resource", role), + + LoadTimeLine group = new LoadTimeLine(buildTimeLine( + resource, _("Other projects"), resourceAllocations, "resource", role), buildTimeLinesGroupForOrder(resource, byOrder)); + return group; } - List> getAllSortedValues( - Map>> byOrder) { - List> resourceAllocations = new ArrayList>(); + List> getAllSortedValues(Map>> byOrder) { + List> resourceAllocations = new ArrayList<>(); for (List> listAllocations : byOrder.values()) { resourceAllocations.addAll(listAllocations); } + return ResourceAllocation.sortedByStartDate(resourceAllocations); } private List buildTimeLinesGroupForOrder( - Resource resource, - Map>> byOrder) { - List result = new ArrayList(); + Resource resource, Map>> byOrder) { + + List result = new ArrayList<>(); for (Order order : byOrder.keySet()) { TimeLineRole role = getCurrentTimeLineRole(order); - result.add(new LoadTimeLine(buildTimeLine(resource, - order.getName(), byOrder.get(order), "resource", role), + result.add(new LoadTimeLine(buildTimeLine( + resource, order.getName(), byOrder.get(order), "resource", role), buildTimeLinesForOrder(resource, byOrder.get(order)))); } Collections.sort(result, LoadTimeLine.byStartAndEndDate()); + return result; } - LoadTimeLine buildTimeLine(Resource resource, String name, - List> sortedByStartDate, - String type, TimeLineRole role) { + LoadTimeLine buildTimeLine(Resource resource, + String name, + List> sortedByStartDate, + String type, + TimeLineRole role) { + + List loadPeriods = + periodBuilderFactory.build(LoadPeriodGenerator.onResource(resource), sortedByStartDate); - List loadPeriods = periodBuilderFactory - .build(LoadPeriodGenerator.onResource(resource), - sortedByStartDate); return new LoadTimeLine(name, loadPeriods, type, role); } @@ -747,14 +745,13 @@ public class ResourceLoadModel implements IResourceLoadModel { super(parameters); } - List buildGroupsByResource( - Map>> map) { - List result = new ArrayList(); - for (Entry>> each : map - .entrySet()) { + List buildGroupsByResource(Map>> map) { + List result = new ArrayList<>(); + for (Entry>> each : map.entrySet()) { LoadTimeLine l = buildGroupFor(each.getKey(), each.getValue()); result.add(l); } + return result; } @@ -762,235 +759,249 @@ public class ResourceLoadModel implements IResourceLoadModel { class ByCriterionLoadTimesLinesBuilder extends LoadTimeLinesBuilder { - public ByCriterionLoadTimesLinesBuilder( - ResourceLoadParameters parameters) { + public ByCriterionLoadTimesLinesBuilder(ResourceLoadParameters parameters) { super(parameters); } - List buildGroupsByCriterion( - Map>> map) { + List buildGroupsByCriterion(Map>> map) { return groupsFor(map); } - private List groupsFor( - Map>> allocationsByCriterion) { - List result = new ArrayList(); - for (Entry>> each : allocationsByCriterion - .entrySet()) { + private List groupsFor(Map>> allocationsByCriterion) { + List result = new ArrayList<>(); + for (Entry>> each : allocationsByCriterion.entrySet()) { Criterion criterion = each.getKey(); - List> allocations = ResourceAllocation - .sortedByStartDate(each.getValue()); - if (allocations == null) { + List> allocations = ResourceAllocation.sortedByStartDate(each.getValue()); + + if ( allocations == null ) { continue; } + TimeLineRole role = getCurrentTimeLineRole(criterion); - LoadTimeLine group = new LoadTimeLine(createMain(criterion, - allocations, role), buildSecondaryLevels(criterion, - allocations)); - if (!group.isEmpty()) { + + LoadTimeLine group = new LoadTimeLine( + createMain(criterion, allocations, role), + buildSecondaryLevels(criterion, allocations)); + + if ( !group.isEmpty() ) { result.add(group); } } + return result; } private LoadTimeLine createMain(Criterion criterion, - List> orderedAllocations, - TimeLineRole role) { - return new LoadTimeLine(criterion.getType().getName() + ": " - + criterion.getName(), createPeriods(criterion, - orderedAllocations), "global-generic", role); + List> orderedAllocations, + TimeLineRole role) { + + return new LoadTimeLine( + criterion.getType().getName() + ": " + criterion.getName(), + createPeriods(criterion, orderedAllocations), "global-generic", role); } - private List createPeriods(Criterion criterion, - List> value) { - return periodBuilderFactory.build(LoadPeriodGenerator.onCriterion( - criterion, resourcesSearchModel), value); + private List createPeriods(Criterion criterion, List> value) { + return periodBuilderFactory.build(LoadPeriodGenerator.onCriterion(criterion, resourcesSearchModel), value); } - private List buildSecondaryLevels(Criterion criterion, - List> allocations) { - List result = new ArrayList(); - result.addAll(buildSubLevels(criterion, ResourceAllocation - .getOfType(GenericResourceAllocation.class, allocations))); + private List buildSecondaryLevels( + Criterion criterion, List> allocations) { + + List result = new ArrayList<>(); + + result.addAll(buildSubLevels( + criterion, ResourceAllocation.getOfType(GenericResourceAllocation.class, allocations))); + result.add(buildRelatedSpecificAllocations(criterion, allocations)); Collections.sort(result, LoadTimeLine.byStartAndEndDate()); + return result; } - private List buildSubLevels(Criterion criterion, - List> allocations) { - List result = new ArrayList(); - Map>> byOrder = byOrder(new ArrayList>( - allocations)); + private List buildSubLevels( + Criterion criterion, List> allocations) { - if (thereIsCurrentOrder()) { - List> allocationsForCurrent = byOrder - .get(getCurrentOrder()); - if (allocationsForCurrent != null) { - result.addAll(buildTimeLinesForOrder(getCurrentOrder(), - criterion, allocationsForCurrent)); + List result = new ArrayList<>(); + Map>> byOrder = byOrder(new ArrayList<>(allocations)); + + if ( thereIsCurrentOrder() ) { + List> allocationsForCurrent = byOrder.get(getCurrentOrder()); + + if ( allocationsForCurrent != null ) { + result.addAll(buildTimeLinesForOrder(getCurrentOrder(), criterion, allocationsForCurrent)); } + byOrder.remove(getCurrentOrder()); // build time lines for other orders - LoadTimeLine lineOthersOrders = buildTimeLinesForOtherOrders( - criterion, byOrder); - if (lineOthersOrders != null) { + LoadTimeLine lineOthersOrders = buildTimeLinesForOtherOrders(criterion, byOrder); + if ( lineOthersOrders != null ) { result.add(lineOthersOrders); } } else { result.addAll(buildTimeLinesGroupForOrder(criterion, byOrder)); } + return result; } - private LoadTimeLine buildTimeLinesForOtherOrders(Criterion criterion, - Map>> byOrder) { + private LoadTimeLine buildTimeLinesForOtherOrders( + Criterion criterion, Map>> byOrder) { + List> allocations = getAllSortedValues(byOrder); - if (allocations.isEmpty()) { + if ( allocations.isEmpty() ) { return null; } - LoadTimeLine group = new LoadTimeLine(buildTimeLine(criterion, - "Other projects", "global-generic", allocations, - getCurrentTimeLineRole(null)), buildTimeLinesGroupForOrder( - criterion, byOrder)); + LoadTimeLine group = new LoadTimeLine( + buildTimeLine( + criterion, + "Other projects", "global-generic", + allocations, getCurrentTimeLineRole(null)), + buildTimeLinesGroupForOrder(criterion, byOrder)); + return group; } private List buildTimeLinesGroupForOrder( - Criterion criterion, - Map>> byOrder) { - List result = new ArrayList(); + Criterion criterion, Map>> byOrder) { + + List result = new ArrayList<>(); for (Order order : byOrder.keySet()) { - if (byOrder.get(order) == null) { + if ( byOrder.get(order) == null ) { // no allocations found for order continue; } + TimeLineRole role = getCurrentTimeLineRole(order); - result.add(new LoadTimeLine(buildTimeLine(criterion, - order.getName(), "global-generic", byOrder.get(order), - role), buildTimeLinesForOrder(order, criterion, - byOrder.get(order)))); + result.add(new LoadTimeLine(buildTimeLine( + criterion, order.getName(), "global-generic", byOrder.get(order), role), + buildTimeLinesForOrder(order, criterion, byOrder.get(order)))); } + return result; } - LoadTimeLine buildTimeLine(Criterion criterion, String name, - String type, List> allocations, - TimeLineRole role) { + LoadTimeLine buildTimeLine(Criterion criterion, + String name, String type, + List> allocations, + TimeLineRole role) { + List generics = onlyGeneric(allocations); - return new LoadTimeLine(name, createPeriods(criterion, generics), - type, role); + + return new LoadTimeLine(name, createPeriods(criterion, generics), type, role); } - private List buildTimeLinesForOrder(Order order, - Criterion criterion, List> allocations) { - List result = new ArrayList(); - result.addAll(buildTimeLinesForEachTask(criterion, - onlyGeneric(allocations))); - result.addAll(buildTimeLinesForEachResource(criterion, + private List buildTimeLinesForOrder( + Order order, Criterion criterion, List> allocations) { + + List result = new ArrayList<>(); + result.addAll(buildTimeLinesForEachTask(criterion, onlyGeneric(allocations))); + + result.addAll(buildTimeLinesForEachResource( onlySpecific(allocations), getCurrentTimeLineRole(order))); + Collections.sort(result, LoadTimeLine.byStartAndEndDate()); + return result; } private List buildTimeLinesForEachTask( Criterion criterion, List allocations) { - Map> byTask = ResourceAllocation - .byTask(allocations); - List secondLevel = new ArrayList(); - for (Entry> entry : byTask - .entrySet()) { + Map> byTask = ResourceAllocation.byTask(allocations); + + List secondLevel = new ArrayList<>(); + for (Entry> entry : byTask.entrySet()) { Task task = entry.getKey(); - Map, List> mapSameCriteria = getAllocationsWithSameCriteria((entry - .getValue())); - for (Entry, List> entrySameCriteria : mapSameCriteria - .entrySet()) { + Set, List>> setSameCriteria = + getAllocationsWithSameCriteria((entry.getValue())).entrySet(); + + + for (Entry, List> entrySameCriteria : setSameCriteria) { Set criterions = entrySameCriteria.getKey(); - List genericAllocations = entrySameCriteria - .getValue(); - List> resourceAllocations = new ArrayList>( - genericAllocations); + List genericAllocations = entrySameCriteria.getValue(); + + List> resourceAllocations = + new ArrayList>(genericAllocations); + TimeLineRole role = getCurrentTimeLineRole(task); /** * Each resource line has the same role than its allocated * task, so that link with the resource allocation screen */ - LoadTimeLine timeLine = new LoadTimeLine(buildTimeLine( - criterions, task, criterion, "global-generic", - resourceAllocations, role), - buildTimeLinesForEachResource(criterion, - genericAllocations, role)); - if (!timeLine.isEmpty()) { + LoadTimeLine timeLine = new LoadTimeLine( + buildTimeLine(criterions, task, criterion, "global-generic", resourceAllocations, role), + buildTimeLinesForEachResource(genericAllocations, role)); + if ( !timeLine.isEmpty() ) { secondLevel.add(timeLine); } } } + return secondLevel; } private List buildTimeLinesForEachResource( - Criterion criterion, - List> allocations, - TimeLineRole role) { - Map>> byResource = ResourceAllocation - .byResource(allocations); + List> allocations, TimeLineRole role) { - List secondLevel = new ArrayList(); - for (Entry>> entry : byResource - .entrySet()) { + Map>> byResource = ResourceAllocation.byResource(allocations); + + List secondLevel = new ArrayList<>(); + for (Entry>> entry : byResource.entrySet()) { Resource resource = entry.getKey(); - List> resourceAllocations = entry - .getValue(); + List> resourceAllocations = entry.getValue(); String descriptionTimeLine = resource.getShortDescription(); - LoadTimeLine timeLine = buildTimeLine(resource, - descriptionTimeLine, resourceAllocations, "generic", - role); - if (!timeLine.isEmpty()) { + LoadTimeLine timeLine = + buildTimeLine(resource, descriptionTimeLine, resourceAllocations, "generic", role); + if ( !timeLine.isEmpty() ) { secondLevel.add(timeLine); } } + return secondLevel; } private LoadTimeLine buildTimeLine(Collection criterions, - Task task, Criterion criterion, String type, - List> allocations, - TimeLineRole role) { - return buildTimeLine(criterion, getName(criterions, task), type, - allocations, role); + Task task, + Criterion criterion, + String type, + List> allocations, + TimeLineRole role) { + + return buildTimeLine(criterion, getName(criterions, task), type, allocations, role); } private LoadTimeLine buildRelatedSpecificAllocations( - Criterion criterion, - List> allocations) { - List specific = ResourceAllocation - .getOfType(SpecificResourceAllocation.class, allocations); + Criterion criterion, List> allocations) { - LoadTimeLine main = new LoadTimeLine(_("Specific Allocations"), - createPeriods(criterion, specific), "related-specific", + List specific = + ResourceAllocation.getOfType(SpecificResourceAllocation.class, allocations); + + LoadTimeLine main = new LoadTimeLine( + _("Specific Allocations"), + createPeriods(criterion, specific), + "related-specific", getCurrentTimeLineRole(criterion)); - List children = buildGroupsFor(ResourceAllocation - .byResource(new ArrayList>(specific))); + + List children = + buildGroupsFor(ResourceAllocation.byResource(new ArrayList>(specific))); + return new LoadTimeLine(main, children); } - private List buildGroupsFor( - Map>> map) { - List result = new ArrayList(); - for (Entry>> each : map - .entrySet()) { + private List buildGroupsFor(Map>> map) { + List result = new ArrayList<>(); + for (Entry>> each : map.entrySet()) { LoadTimeLine l = buildGroupFor(each.getKey(), each.getValue()); - if (!l.isEmpty()) { + if ( !l.isEmpty() ) { result.add(l); } } + return result; } @@ -998,57 +1009,56 @@ public class ResourceLoadModel implements IResourceLoadModel { public static Date asDate(LocalDate date) { - if (date == null) { + if ( date == null ) { return null; } + return date.toDateTimeAtStartOfDay().toDate(); } public static LocalDate toLocal(Date date) { - if (date == null) { + if ( date == null ) { return null; } + return LocalDate.fromDateFields(date); } private Map, List> getAllocationsWithSameCriteria( List genericAllocations) { + return GenericResourceAllocation.byCriterions(genericAllocations); } - private Map>> byOrder( - Collection> allocations) { - Map>> result = new HashMap>>(); + private Map>> byOrder(Collection> allocations) { + Map>> result = new HashMap<>(); + for (ResourceAllocation resourceAllocation : allocations) { - if ((resourceAllocation.isSatisfied()) - && (resourceAllocation.getTask() != null)) { - OrderElement orderElement = resourceAllocation.getTask() - .getOrderElement(); + if ( (resourceAllocation.isSatisfied()) && (resourceAllocation.getTask() != null) ) { + OrderElement orderElement = resourceAllocation.getTask().getOrderElement(); Order order = orderDAO.loadOrderAvoidingProxyFor(orderElement); initializeIfNeeded(result, order); result.get(order).add(resourceAllocation); } } + return result; } - private void initializeIfNeeded( - Map>> result, Order order) { - if (!result.containsKey(order)) { + private void initializeIfNeeded(Map>> result, Order order) { + if ( !result.containsKey(order) ) { result.put(order, new ArrayList>()); } } private static List onlyGeneric( Collection> sortedByStartDate) { - return ResourceAllocation.getOfType(GenericResourceAllocation.class, - sortedByStartDate); + + return ResourceAllocation.getOfType(GenericResourceAllocation.class, sortedByStartDate); } - private static List onlySpecific( - List> sortedByStartDate) { - return ResourceAllocation.getOfType(SpecificResourceAllocation.class, - sortedByStartDate); + private static List onlySpecific(List> sortedByStartDate) { + return ResourceAllocation.getOfType(SpecificResourceAllocation.class, sortedByStartDate); } @Override @@ -1057,11 +1067,11 @@ public class ResourceLoadModel implements IResourceLoadModel { User user; try { - user = this.userDAO.findByLoginName(SecurityUtils - .getSessionUserLoginName()); + user = this.userDAO.findByLoginName(SecurityUtils.getSessionUserLoginName()); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } + return user.isExpandResourceLoadViewCharts(); } @@ -1070,15 +1080,16 @@ public class ResourceLoadModel implements IResourceLoadModel { public User getUser() { User user; try { - user = this.userDAO.findByLoginName(SecurityUtils - .getSessionUserLoginName()); + user = this.userDAO.findByLoginName(SecurityUtils.getSessionUserLoginName()); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } + // Attach filter bandbox elements - if (user.getResourcesLoadFilterCriterion() != null) { + if ( user.getResourcesLoadFilterCriterion() != null ) { user.getResourcesLoadFilterCriterion().getFinderPattern(); } + return user; } @@ -1093,8 +1104,10 @@ class PeriodBuilderFactory { this.endDateFilter = endDateFilter; } - public List build(LoadPeriodGeneratorFactory factory, List> sortedByStartDate){ - if (initDateFilter == null && endDateFilter == null) { + public List build( + LoadPeriodGeneratorFactory factory, List> sortedByStartDate){ + + if ( initDateFilter == null && endDateFilter == null ) { return PeriodsBuilder.build(factory, sortedByStartDate); } else { return PeriodsBuilder.build(factory, sortedByStartDate, asDate(initDateFilter), asDate(endDateFilter)); @@ -1111,50 +1124,59 @@ class PeriodsBuilder { private final List> sortedByStartDate; - private final List loadPeriodsGenerators = new LinkedList(); + private final List loadPeriodsGenerators = new LinkedList<>(); private final LoadPeriodGeneratorFactory factory; - private PeriodsBuilder(LoadPeriodGeneratorFactory factory, - List> sortedByStartDate) { + private PeriodsBuilder( + LoadPeriodGeneratorFactory factory, List> sortedByStartDate) { + this.factory = factory; this.sortedByStartDate = sortedByStartDate; } - public static List build(LoadPeriodGeneratorFactory factory, - List> sortedByStartDate) { + public static List build( + LoadPeriodGeneratorFactory factory, List> sortedByStartDate) { + return new PeriodsBuilder(factory, sortedByStartDate).buildPeriods(); } public static List build(LoadPeriodGeneratorFactory factory, - List> sortedByStartDate, - Date startDateFilter, Date endDateFilter) { + List> sortedByStartDate, + Date startDateFilter, + Date endDateFilter) { + List list = new PeriodsBuilder(factory, sortedByStartDate).buildPeriods(); - List toReturn = new ArrayList(); + List toReturn = new ArrayList<>(); for (LoadPeriod loadPeriod : list) { final GanttDate finalStartDate; - if (startDateFilter != null) { - finalStartDate = GanttDate.max(GanttDate - .createFrom(new LocalDate(startDateFilter.getTime())), + if ( startDateFilter != null ) { + + finalStartDate = GanttDate.max( + GanttDate.createFrom(new LocalDate(startDateFilter.getTime())), loadPeriod.getStart()); } else { finalStartDate = loadPeriod.getStart(); } final GanttDate finalEndDate; - if (endDateFilter != null) { - finalEndDate = GanttDate.min(loadPeriod.getEnd(), GanttDate - .createFrom(new LocalDate(endDateFilter.getTime()))); + if ( endDateFilter != null ) { + finalEndDate = GanttDate.min( + loadPeriod.getEnd(), + GanttDate.createFrom(new LocalDate(endDateFilter.getTime()))); } else { finalEndDate = loadPeriod.getEnd(); } - if (finalStartDate.compareTo(finalEndDate) < 0) { - toReturn.add(new LoadPeriod(finalStartDate, finalEndDate, + if ( finalStartDate.compareTo(finalEndDate) < 0 ) { + toReturn.add(new LoadPeriod( + finalStartDate, finalEndDate, loadPeriod.getAvailableEffort(), - loadPeriod.getAssignedEffort(), loadPeriod.getLoadLevel())); + loadPeriod.getAssignedEffort(), + loadPeriod.getLoadLevel())); } } + return toReturn; } @@ -1163,40 +1185,42 @@ class PeriodsBuilder { loadPeriodsGenerators.add(factory.create(resourceAllocation)); } joinPeriodGenerators(); + return toGenerators(loadPeriodsGenerators); } private List toGenerators(List generators) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (LoadPeriodGenerator loadPeriodGenerator : generators) { LoadPeriod period = loadPeriodGenerator.build(); - if (period != null) { + if ( period != null ) { result.add(period); } } + return result; } private void joinPeriodGenerators() { - ListIterator iterator = loadPeriodsGenerators - .listIterator(); + ListIterator iterator = loadPeriodsGenerators.listIterator(); while (iterator.hasNext()) { final LoadPeriodGenerator current = findNextOneOverlapping(iterator); - if (current != null) { + + if ( current != null ) { rewind(iterator, current); iterator.remove(); LoadPeriodGenerator next = iterator.next(); iterator.remove(); List generated = current.join(next); final LoadPeriodGenerator positionToComeBack = generated.get(0); - final List remaining = loadPeriodsGenerators - .subList(iterator.nextIndex(), loadPeriodsGenerators - .size()); - List generatorsSortedByStartDate = mergeListsKeepingByStartSortOrder( - generated, remaining); - final int takenFromRemaining = generatorsSortedByStartDate - .size() - - generated.size(); + + final List remaining = + loadPeriodsGenerators.subList(iterator.nextIndex(), loadPeriodsGenerators.size()); + + List generatorsSortedByStartDate = + mergeListsKeepingByStartSortOrder(generated, remaining); + + final int takenFromRemaining = generatorsSortedByStartDate.size() - generated.size(); removeNextElements(iterator, takenFromRemaining); addAtCurrentPosition(iterator, generatorsSortedByStartDate); rewind(iterator, positionToComeBack); @@ -1204,56 +1228,56 @@ class PeriodsBuilder { } } - private LoadPeriodGenerator findNextOneOverlapping( - ListIterator iterator) { + private LoadPeriodGenerator findNextOneOverlapping(ListIterator iterator) { while (iterator.hasNext()) { LoadPeriodGenerator current = iterator.next(); - if (!iterator.hasNext()) { + + if ( !iterator.hasNext() ) { return null; } + LoadPeriodGenerator next = peekNext(iterator); - if (current.overlaps(next)) { + if ( current.overlaps(next) ) { return current; } } + return null; } private void addAtCurrentPosition( - ListIterator iterator, - List sortedByStartDate) { + ListIterator iterator, List sortedByStartDate) { + for (LoadPeriodGenerator l : sortedByStartDate) { iterator.add(l); } } - private void removeNextElements(ListIterator iterator, - final int elementsNumber) { + private void removeNextElements(ListIterator iterator, final int elementsNumber) { for (int i = 0; i < elementsNumber; i++) { iterator.next(); iterator.remove(); } } - private void rewind(ListIterator iterator, - LoadPeriodGenerator nextOne) { + private void rewind(ListIterator iterator, LoadPeriodGenerator nextOne) { while (peekNext(iterator) != nextOne) { iterator.previous(); } } private List mergeListsKeepingByStartSortOrder( - List joined, - List remaining) { - List result = new ArrayList(); - ListIterator joinedIterator = joined - .listIterator(); - ListIterator remainingIterator = remaining - .listIterator(); + List joined, List remaining) { + + List result = new ArrayList<>(); + ListIterator joinedIterator = joined.listIterator(); + ListIterator remainingIterator = remaining.listIterator(); + while (joinedIterator.hasNext() && remainingIterator.hasNext()) { LoadPeriodGenerator fromJoined = peekNext(joinedIterator); LoadPeriodGenerator fromRemaining = peekNext(remainingIterator); - if (fromJoined.getStart().compareTo(fromRemaining.getStart()) <= 0) { + + if ( fromJoined.getStart().compareTo(fromRemaining.getStart()) <= 0 ) { result.add(fromJoined); joinedIterator.next(); } else { @@ -1261,20 +1285,21 @@ class PeriodsBuilder { remainingIterator.next(); } } - if (joinedIterator.hasNext()) { - result.addAll(joined.subList(joinedIterator.nextIndex(), joined - .size())); + if ( joinedIterator.hasNext() ) { + result.addAll(joined.subList(joinedIterator.nextIndex(), joined.size())); } + return result; } - private LoadPeriodGenerator peekNext( - ListIterator iterator) { - if (!iterator.hasNext()) { + private LoadPeriodGenerator peekNext(ListIterator iterator) { + if ( !iterator.hasNext() ) { return null; } + LoadPeriodGenerator result = iterator.next(); iterator.previous(); + return result; } diff --git a/pom.xml b/pom.xml index 7fe06aa7b..d46315b9e 100644 --- a/pom.xml +++ b/pom.xml @@ -388,14 +388,14 @@ jdk15 - + - commons-collections - commons-collections - 3.2 - + org.apache.commons + commons-collections4 + 4.1 + - + org.apache.commons commons-lang3