Merge pull request #77 from skylow95/master

Change deprecated methods and update EasyMock
This commit is contained in:
Jeroen Baten 2016-05-05 13:53:29 +02:00
commit 403fba6946
23 changed files with 976 additions and 1070 deletions

View file

@ -45,6 +45,7 @@ Changes
* Update JGraphT
* Update DBUnit
* Update Log4j
* Update JodaTime
* Remove Ezmorph

View file

@ -82,7 +82,7 @@ public class OnColumnsRowRendererTest {
private void givenDetailItems() {
detailItems = new ArrayList<>();
start = new LocalDate(2010, 1, 1).toDateMidnight().toDateTime();
start = new LocalDate(2010, 1, 1).toDateTimeAtStartOfDay().toDateTime();
DateTime current = start;
Period period = Period.months(2);

View file

@ -137,6 +137,11 @@
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<profiles>

View file

@ -66,31 +66,28 @@ public abstract class DayAssignment extends BaseEntity {
public abstract boolean accepts(DayAssignment each);
}
public static List<DayAssignment> filter(
Collection<? extends DayAssignment> assignments,
FilterType filter) {
public static List<DayAssignment> filter(Collection<? extends DayAssignment> assignments,
FilterType filter) {
if (filter == null || filter.equals(FilterType.KEEP_ALL)) {
return new ArrayList<DayAssignment>(assignments);
return new ArrayList<>(assignments);
}
List<DayAssignment> result = new ArrayList<DayAssignment>();
for (DayAssignment each : assignments) {
if (filter.accepts(each)) {
if ( filter.accepts(each) ) {
result.add(each);
}
}
return result;
}
public static <T extends DayAssignment> List<T> getAtInterval(
List<T> orderedAssignments, LocalDate startInclusive,
LocalDate endExclusive) {
public static <T extends DayAssignment> List<T> getAtInterval(List<T> orderedAssignments, LocalDate startInclusive,
LocalDate endExclusive) {
int position = findFirstAfterOrEqual(orderedAssignments, startInclusive);
List<T> couldBeIncluded = orderedAssignments.subList(position, Math
.max(
orderedAssignments.size(), position));
List<T> result = new ArrayList<T>();
List<T> couldBeIncluded = orderedAssignments.subList(position,
Math.max(orderedAssignments.size(), position));
List<T> result = new ArrayList<>();
for (T each : couldBeIncluded) {
if (each.getDay().compareTo(endExclusive) >= 0) {
if ( each.getDay().compareTo(endExclusive) >= 0 ) {
break;
}
assert each.includedIn(startInclusive, endExclusive);
@ -101,9 +98,9 @@ public abstract class DayAssignment extends BaseEntity {
public static <T extends DayAssignment> List<T> withConsolidatedValue(
Collection<? extends T> assignments, boolean consolidated) {
List<T> result = new ArrayList<T>();
List<T> result = new ArrayList<>();
for (T each : assignments) {
if (each.isConsolidated() == consolidated) {
if ( each.isConsolidated() == consolidated ) {
result.add(each);
}
}
@ -116,8 +113,7 @@ public abstract class DayAssignment extends BaseEntity {
int end = orderedAssignments.size() - 1;
while (start <= end) {
int middle = start + (end - start) / 2;
if (orderedAssignments.get(middle).getDay().compareTo(
startInclusive) < 0) {
if ( orderedAssignments.get(middle).getDay().compareTo(startInclusive) < 0 ) {
start = middle + 1;
} else {
end = middle - 1;
@ -126,8 +122,7 @@ public abstract class DayAssignment extends BaseEntity {
return start;
}
public static EffortDuration sum(
Collection<? extends DayAssignment> assignments) {
public static EffortDuration sum(Collection<? extends DayAssignment> assignments) {
EffortDuration result = zero();
for (DayAssignment each : assignments) {
result = result.plus(each.getDuration());
@ -144,8 +139,7 @@ public abstract class DayAssignment extends BaseEntity {
return result;
}
public static <T extends DayAssignment> Map<Resource, List<T>> byResource(
Collection<? extends T> assignments) {
public static <T extends DayAssignment> Map<Resource, List<T>> byResource(Collection<? extends T> assignments) {
Map<Resource, List<T>> result = new HashMap<Resource, List<T>>();
for (T assignment : assignments) {
Resource resource = assignment.getResource();
@ -157,12 +151,11 @@ public abstract class DayAssignment extends BaseEntity {
return result;
}
public static <T extends DayAssignment> Map<LocalDate, List<T>> byDay(
Collection<? extends T> assignments) {
public static <T extends DayAssignment> Map<LocalDate, List<T>> byDay(Collection<? extends T> assignments) {
Map<LocalDate, List<T>> result = new HashMap<LocalDate, List<T>>();
for (T t : assignments) {
LocalDate day = t.getDay();
if (!result.containsKey(day)) {
if ( !result.containsKey(day) ) {
result.put(day, new ArrayList<T>());
}
result.get(day).add(t);
@ -170,8 +163,7 @@ public abstract class DayAssignment extends BaseEntity {
return result;
}
public static Set<Resource> getAllResources(
Collection<? extends DayAssignment> assignments) {
public static Set<Resource> getAllResources(Collection<? extends DayAssignment> assignments) {
Set<Resource> result = new HashSet<Resource>();
for (DayAssignment dayAssignment : assignments) {
result.add(dayAssignment.getResource());
@ -181,7 +173,7 @@ public abstract class DayAssignment extends BaseEntity {
public static <T extends DayAssignment> List<T> getOfType(Class<T> klass,
Collection<? extends DayAssignment> dayAssignments) {
List<T> result = new ArrayList<T>();
List<T> result = new ArrayList<>();
for (DayAssignment each : dayAssignments) {
if (klass.isInstance(each)) {
result.add(klass.cast(each));
@ -211,6 +203,7 @@ public abstract class DayAssignment extends BaseEntity {
return result;
}
@NotNull
private EffortDuration duration;
@NotNull
@ -226,8 +219,7 @@ public abstract class DayAssignment extends BaseEntity {
}
protected DayAssignment(LocalDate day, EffortDuration duration,
Resource resource) {
protected DayAssignment(LocalDate day, EffortDuration duration, Resource resource) {
Validate.notNull(day);
Validate.notNull(duration);
Validate.notNull(resource);
@ -236,15 +228,12 @@ public abstract class DayAssignment extends BaseEntity {
this.resource = resource;
}
/**
* @deprecated Use {@link #getDuration()}
*/
@Deprecated
public int getHours() {
/* public int getHours() {
return duration.getHours();
}
*/
@NotNull
public EffortDuration getDuration() {
return duration;
}
@ -290,7 +279,7 @@ public abstract class DayAssignment extends BaseEntity {
public static <T extends DayAssignment> List<T> orderedByDay(
Collection<T> dayAssignments) {
List<T> result = new ArrayList<T>(dayAssignments);
List<T> result = new ArrayList<>(dayAssignments);
Collections.sort(result, byDayComparator());
return result;
}

View file

@ -20,8 +20,6 @@
*/
package org.libreplan.business.planner.entities;
import static org.libreplan.business.workingday.EffortDuration.hours;
import org.apache.commons.lang.Validate;
import javax.validation.constraints.NotNull;
import org.joda.time.LocalDate;
@ -40,18 +38,21 @@ import org.libreplan.business.workingday.EffortDuration;
*/
public class DerivedDayAssignment extends DayAssignment {
@Deprecated
/* @Deprecated
public static DerivedDayAssignment create(LocalDate day, int hours,
Resource resource, DerivedAllocation derivedAllocation) {
return create(new DerivedDayAssignment(day, hours(hours), resource,
derivedAllocation));
}*/
private static DerivedDayAssignment create(LocalDate day, EffortDuration hours, Resource resource,
DerivedDayAssignmentsContainer container) {
return create(new DerivedDayAssignment(day, hours, resource, container));
}
public static DerivedDayAssignment create(LocalDate day,
EffortDuration duration, Resource resource,
DerivedAllocation derivedAllocation) {
return create(new DerivedDayAssignment(day, duration, resource,
derivedAllocation));
public static DerivedDayAssignment create(LocalDate day, EffortDuration duration, Resource resource,
DerivedAllocation derivedAllocation) {
return create(new DerivedDayAssignment(day, duration, resource, derivedAllocation));
}
/**
@ -62,9 +63,10 @@ public class DerivedDayAssignment extends DayAssignment {
}
private abstract class ParentState {
protected abstract DerivedAllocation getAllocation();
protected abstract DerivedAllocation getAllocation();
public abstract Scenario getScenario();
}
private class TransientParentState extends ParentState {
@ -85,6 +87,7 @@ public class DerivedDayAssignment extends DayAssignment {
public Scenario getScenario() {
return null;
}
}
private class ContainerParentState extends ParentState {
@ -96,11 +99,11 @@ public class DerivedDayAssignment extends DayAssignment {
protected DerivedAllocation getAllocation() {
return container.getResourceAllocation();
}
@Override
public Scenario getScenario() {
return container.getScenario();
}
}
private class DetachedState extends ParentState {
@ -123,22 +126,19 @@ public class DerivedDayAssignment extends DayAssignment {
@OnCopy(Strategy.IGNORE)
private ParentState parentState;
private DerivedDayAssignment(LocalDate day, EffortDuration hours,
Resource resource) {
private DerivedDayAssignment(LocalDate day, EffortDuration hours, Resource resource) {
super(day, hours, resource);
Validate.isTrue(resource instanceof Worker);
}
private DerivedDayAssignment(LocalDate day, EffortDuration hours,
Resource resource,
DerivedAllocation derivedAllocation) {
private DerivedDayAssignment(LocalDate day, EffortDuration hours, Resource resource,
DerivedAllocation derivedAllocation) {
this(day, hours, resource);
this.parentState = new TransientParentState(derivedAllocation);
}
private DerivedDayAssignment(LocalDate day, EffortDuration hours,
Resource resource,
DerivedDayAssignmentsContainer container) {
private DerivedDayAssignment(LocalDate day, EffortDuration hours, Resource resource,
DerivedDayAssignmentsContainer container) {
this(day, hours, resource);
Validate.notNull(container);
this.container = container;
@ -150,19 +150,11 @@ public class DerivedDayAssignment extends DayAssignment {
}
DerivedDayAssignment copyAsChildOf(DerivedDayAssignmentsContainer container) {
return create(this.getDay(), this.getHours(), this.getResource(),
container);
}
private static DerivedDayAssignment create(LocalDate day, int hours,
Resource resource, DerivedDayAssignmentsContainer container) {
return create(new DerivedDayAssignment(day,
EffortDuration.hours(hours), resource, container));
return create(this.getDay(), this.getDuration(), this.getResource(), container);
}
DerivedDayAssignment copyAsChildOf(DerivedAllocation derivedAllocation) {
return create(this.getDay(), this.getHours(), this.getResource(),
derivedAllocation);
return create(this.getDay(), this.getDuration(), this.getResource(), derivedAllocation);
}
@Override

View file

@ -34,6 +34,7 @@ import java.util.TreeMap;
import java.util.Date;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.libreplan.business.advance.entities.AdvanceMeasurement;
import org.libreplan.business.advance.entities.DirectAdvanceAssignment;
import org.libreplan.business.planner.entities.DayAssignment.FilterType;
@ -69,7 +70,7 @@ public class HoursCostCalculator implements ICostCalculator {
(task.getOrderElement() != null) ? task.getOrderElement().getReportGlobalAdvanceAssignment() : null;
if ( advanceAssignment == null ) {
return new TreeMap<LocalDate, BigDecimal>();
return new TreeMap<>();
}
return calculateHoursPerDay(
@ -110,10 +111,9 @@ public class HoursCostCalculator implements ICostCalculator {
* MAX(BCWS) equals addition of all dayAssignments.
*/
@Override
public SortedMap<LocalDate, BigDecimal> getEstimatedCost(
Task task,
LocalDate filterStartDate,
LocalDate filterEndDate) {
public SortedMap<LocalDate, BigDecimal> getEstimatedCost(Task task,
LocalDate filterStartDate,
LocalDate filterEndDate) {
if ( task.isSubcontracted() ) {
return getAdvanceCost(task);
@ -130,30 +130,33 @@ public class HoursCostCalculator implements ICostCalculator {
for (DayAssignment dayAssignment : dayAssignments) {
LocalDate day = dayAssignment.getDay();
if( ( (filterStartDate == null) || day.compareTo(filterStartDate) >= 0) &&
( (filterEndDate == null) || day.compareTo(filterEndDate) <= 0) ) {
if( ((filterStartDate == null) || day.compareTo(filterStartDate) >= 0) &&
((filterEndDate == null) || day.compareTo(filterEndDate) <= 0) ) {
String currentTime = dayAssignment.getDuration().toFormattedString();
SimpleDateFormat format1 = new SimpleDateFormat("hh:mm");
SimpleDateFormat format2 = new SimpleDateFormat("hh");
Date date = null;
try {
if ( isParsableWithFormat1(currentTime) )
if ( isParsableWithFormat1(currentTime) ) {
date = format1.parse(currentTime);
else if ( isParsableWithFormat2(currentTime) )
} else if ( isParsableWithFormat2(currentTime) ) {
date = format2.parse(currentTime);
}
} catch (ParseException e) {
e.printStackTrace();
}
Time time = new Time(date.getTime());
assert date != null;
BigDecimal hours = new BigDecimal(time.getHours());
additionOfAllAssignmentsMinutes += time.getMinutes();
LocalTime time = new LocalTime(date.getTime());
// Time time = new Time(date.getTime());
BigDecimal hours = new BigDecimal(time.getHourOfDay());
additionOfAllAssignmentsMinutes += time.getMinuteOfHour();
if ( !result.containsKey(day) ) {
result.put(day, BigDecimal.ZERO);

View file

@ -71,27 +71,27 @@ public abstract class TaskElement extends BaseEntity {
private static final Log LOG = LogFactory.getLog(TaskElement.class);
public static List<Task> justTasks(Collection<? extends TaskElement> tasks) {
List<Task> result = new ArrayList<Task>();
List<Task> result = new ArrayList<>();
for (TaskElement taskElement : tasks) {
if (taskElement instanceof Task) {
if ( taskElement instanceof Task ) {
result.add((Task) taskElement);
}
}
return result;
}
public interface IDatesInterceptor {
public void setStartDate(IntraDayDate previousStart,
void setStartDate(IntraDayDate previousStart,
IntraDayDate previousEnd, IntraDayDate newStart);
public void setNewEnd(IntraDayDate previousEnd, IntraDayDate newEnd);
void setNewEnd(IntraDayDate previousEnd, IntraDayDate newEnd);
}
private static final IDatesInterceptor EMPTY_INTERCEPTOR = new IDatesInterceptor() {
@Override
public void setStartDate(IntraDayDate previousStart,
IntraDayDate previousEnd, IntraDayDate newStart) {
public void setStartDate(IntraDayDate previousStart, IntraDayDate previousEnd, IntraDayDate newStart) {
}
@Override
@ -108,6 +108,7 @@ public abstract class TaskElement extends BaseEntity {
return o1.getStartDate().compareTo(o2.getStartDate());
}
};
return result;
}
@ -128,10 +129,10 @@ public abstract class TaskElement extends BaseEntity {
*/
@SuppressWarnings("unchecked")
public LocalDate getBiggestAmongEndOrDeadline() {
if (this.getDeadline() != null) {
return Collections.max(asList(this.getDeadline(),
this.getEndAsLocalDate()));
if ( this.getDeadline() != null ) {
return Collections.max(asList(this.getDeadline(), this.getEndAsLocalDate()));
}
return this.getEndAsLocalDate();
}
@ -149,8 +150,7 @@ public abstract class TaskElement extends BaseEntity {
return create(taskElement);
}
protected static <T extends TaskElement> T createWithoutTaskSource(
T taskElement) {
protected static <T extends TaskElement> T createWithoutTaskSource(T taskElement) {
return create(taskElement);
}
@ -185,7 +185,7 @@ public abstract class TaskElement extends BaseEntity {
private Boolean updatedFromTimesheets = false;
public void initializeDatesIfNeeded() {
if (getIntraDayEndDate() == null || getIntraDayStartDate() == null) {
if ( getIntraDayEndDate() == null || getIntraDayStartDate() == null ) {
initializeDates();
}
}
@ -203,9 +203,10 @@ public abstract class TaskElement extends BaseEntity {
}
public Integer getWorkHours() {
if (taskSource == null) {
if ( taskSource == null ) {
return 0;
}
return taskSource.getTotalHours();
}
@ -236,7 +237,7 @@ public abstract class TaskElement extends BaseEntity {
}
protected void copyParenTo(TaskElement result) {
if (this.getParent() != null) {
if ( this.getParent() != null ) {
this.getParent().addTaskElement(result);
}
}
@ -259,7 +260,7 @@ public abstract class TaskElement extends BaseEntity {
public void setName(String name) {
this.name = name;
if (taskSource != null && taskSource.getOrderElement() != null) {
if ( taskSource != null && taskSource.getOrderElement() != null ) {
taskSource.getOrderElement().setName(name);
}
}
@ -273,9 +274,10 @@ public abstract class TaskElement extends BaseEntity {
}
public OrderElement getOrderElement() {
if (getTaskSource() == null) {
if ( getTaskSource() == null ) {
return null;
}
return getTaskSource().getOrderElement();
}
@ -288,18 +290,16 @@ public abstract class TaskElement extends BaseEntity {
}
public Set<Dependency> getDependenciesWithThisDestinationAndAllParents() {
Set<Dependency> result = new HashSet<Dependency>(
getDependenciesWithThisDestination());
if (parent != null) {
result.addAll(parent
.getDependenciesWithThisDestinationAndAllParents());
Set<Dependency> result = new HashSet<Dependency>(getDependenciesWithThisDestination());
if ( parent != null ) {
result.addAll(parent.getDependenciesWithThisDestinationAndAllParents());
}
return result;
}
public Date getStartDate() {
return startDate != null ? startDate.getDate().toDateTimeAtStartOfDay()
.toDate() : null;
return startDate != null ? startDate.getDate().toDateTimeAtStartOfDay().toDate() : null;
}
@NotNull
@ -419,26 +419,25 @@ public abstract class TaskElement extends BaseEntity {
public void setDeadline(LocalDate deadline) {
this.deadline = deadline;
if (taskSource != null && taskSource.getOrderElement() != null) {
if ( taskSource != null && taskSource.getOrderElement() != null ) {
taskSource.getOrderElement().setDeadline(
(deadline == null)? null : deadline.toDateMidnight().toDate());
(deadline == null)? null : deadline.toDateTimeAtStartOfDay().toDate());
}
}
public void add(Dependency dependency) {
if (this.equals(dependency.getOrigin())) {
if ( this.equals(dependency.getOrigin()) ) {
dependenciesWithThisOrigin.add(dependency);
}
if (this.equals(dependency.getDestination())) {
if ( this.equals(dependency.getDestination()) ) {
dependenciesWithThisDestination.add(dependency);
}
}
private void removeDependenciesWithThisOrigin(TaskElement origin, Type type) {
ArrayList<Dependency> toBeRemoved = new ArrayList<Dependency>();
ArrayList<Dependency> toBeRemoved = new ArrayList<>();
for (Dependency dependency : dependenciesWithThisDestination) {
if (dependency.getOrigin().equals(origin)
&& dependency.getType().equals(type)) {
if ( dependency.getOrigin().equals(origin) && dependency.getType().equals(type) ) {
toBeRemoved.add(dependency);
}
}
@ -448,8 +447,7 @@ public abstract class TaskElement extends BaseEntity {
public void removeDependencyWithDestination(TaskElement destination, Type type) {
ArrayList<Dependency> toBeRemoved = new ArrayList<Dependency>();
for (Dependency dependency : dependenciesWithThisOrigin) {
if (dependency.getDestination().equals(destination)
&& dependency.getType().equals(type)) {
if ( dependency.getDestination().equals(destination) && dependency.getType().equals(type) ) {
toBeRemoved.add(dependency);
}
}
@ -471,7 +469,7 @@ public abstract class TaskElement extends BaseEntity {
}
public void detachFromParent() {
if (parent != null) {
if ( parent != null ) {
parent.remove(this);
}
}
@ -487,22 +485,23 @@ public abstract class TaskElement extends BaseEntity {
}
private List<Dependency> getDependenciesWithDestination(TaskElement t) {
ArrayList<Dependency> result = new ArrayList<Dependency>();
ArrayList<Dependency> result = new ArrayList<>();
for (Dependency dependency : dependenciesWithThisOrigin) {
if (dependency.getDestination().equals(t)) {
if ( dependency.getDestination().equals(t) ) {
result.add(dependency);
}
}
return result;
}
private List<Dependency> getDependenciesWithOrigin(TaskElement t) {
ArrayList<Dependency> result = new ArrayList<Dependency>();
ArrayList<Dependency> result = new ArrayList<>();
for (Dependency dependency : dependenciesWithThisDestination) {
if (dependency.getOrigin().equals(t)) {
result.add(dependency);
if ( dependency.getOrigin().equals(t) ) {result.add(dependency);
}
}
return result;
}
@ -515,7 +514,7 @@ public abstract class TaskElement extends BaseEntity {
Set<TaskElement> tasksToNotify = new HashSet<TaskElement>();
for (Dependency dependency : dependenciesWithThisDestination) {
TaskElement origin = dependency.getOrigin();
if (origin != null) {
if ( origin != null ) {
tasksToNotify.add(origin);
}
}
@ -529,7 +528,7 @@ public abstract class TaskElement extends BaseEntity {
Set<TaskElement> tasksToNotify = new HashSet<TaskElement>();
for (Dependency dependency : dependenciesWithThisOrigin) {
TaskElement destination = dependency.getDestination();
if (destination != null) {
if ( destination != null ) {
tasksToNotify.add(destination);
}
}
@ -548,11 +547,11 @@ public abstract class TaskElement extends BaseEntity {
}
public BaseCalendar getCalendar() {
if (calendar == null) {
if ( calendar == null ) {
OrderElement orderElement = getOrderElement();
return orderElement != null ? orderElement.getOrder().getCalendar()
: null;
return orderElement != null ? orderElement.getOrder().getCalendar() : null;
}
return calendar;
}
@ -561,13 +560,13 @@ public abstract class TaskElement extends BaseEntity {
public abstract Set<ResourceAllocation<?>> getAllResourceAllocations();
public SortedMap<LocalDate, EffortDuration> getDurationsAssignedByDay() {
SortedMap<LocalDate, EffortDuration> result = new TreeMap<LocalDate, EffortDuration>();
SortedMap<LocalDate, EffortDuration> result = new TreeMap<>();
for (ResourceAllocation<?> resourceAllocation : getSatisfiedResourceAllocations()) {
for (DayAssignment each : resourceAllocation
.getAssignments()) {
for (DayAssignment each : resourceAllocation.getAssignments()) {
addToResult(result, each.getDay(), each.getDuration());
}
}
return result;
}
@ -577,7 +576,7 @@ public abstract class TaskElement extends BaseEntity {
}
public List<DayAssignment> getDayAssignments(DayAssignment.FilterType filter) {
List<DayAssignment> dayAssignments = new ArrayList<DayAssignment>();
List<DayAssignment> dayAssignments = new ArrayList<>();
Set<ResourceAllocation<?>> resourceAllocations = getSatisfiedResourceAllocations();
for (ResourceAllocation<?> resourceAllocation : resourceAllocations) {
@ -623,6 +622,7 @@ public abstract class TaskElement extends BaseEntity {
while (result.getParent() != null) {
result = result.getParent();
}
return result;
}
@ -641,30 +641,33 @@ public abstract class TaskElement extends BaseEntity {
//simplified calculation has only two states:
//unassigned, when hours allocated is zero, and
//assigned otherwise
if (getSumOfAssignedEffort().isZero()) {
if ( getSumOfAssignedEffort().isZero() ) {
return "unassigned";
}
return "assigned";
}
Set<ResourceAllocation<?>> resourceAllocations = getSatisfiedResourceAllocations();
if (resourceAllocations.isEmpty()) {
if ( resourceAllocations.isEmpty() ) {
return "unassigned";
}
for (ResourceAllocation<?> resourceAllocation : resourceAllocations) {
final ResourcesPerDay resourcesPerDay = resourceAllocation.getResourcesPerDay();
if (resourcesPerDay != null && resourcesPerDay.isZero()) {
if ( resourcesPerDay != null && resourcesPerDay.isZero() ) {
return "partially-assigned";
}
}
return "assigned";
}
public Boolean belongsClosedProject() {
EnumSet<OrderStatusEnum> CLOSED = EnumSet.of(OrderStatusEnum.CANCELLED,
OrderStatusEnum.FINISHED, OrderStatusEnum.STORED);
OrderStatusEnum.FINISHED,
OrderStatusEnum.STORED);
Order order = getOrderElement().getOrder();
if(CLOSED.contains(order.getState())) {
if( CLOSED.contains(order.getState()) ) {
return true;
}
@ -686,8 +689,7 @@ public abstract class TaskElement extends BaseEntity {
}
public BigDecimal getAdvancePercentage() {
return (advancePercentage == null) ? BigDecimal.ZERO
: advancePercentage;
return (advancePercentage == null) ? BigDecimal.ZERO : advancePercentage;
}
/**
@ -697,10 +699,10 @@ public abstract class TaskElement extends BaseEntity {
* depending on parameter
*/
public BigDecimal getAdvancePercentage(ProgressType progressType) {
if (progressType != null
&& progressType.equals(ProgressType.SPREAD_PROGRESS)) {
if ( progressType != null && progressType.equals(ProgressType.SPREAD_PROGRESS) ) {
return advancePercentage;
}
return BigDecimal.ZERO;
}
@ -716,7 +718,7 @@ public abstract class TaskElement extends BaseEntity {
}
public EffortDuration getSumOfAssignedEffort() {
if (this.getParent() == null) {
if ( this.getParent() == null ) {
//it's an order, we use the cached value
return sumOfAssignedEffort;
}
@ -746,6 +748,7 @@ public abstract class TaskElement extends BaseEntity {
result.add(child);
result.addAll(child.getAllChildren());
}
return result;
}
@ -753,12 +756,13 @@ public abstract class TaskElement extends BaseEntity {
public BigDecimal getTheoreticalAdvancePercentageUntilDate(Date date) {
EffortDuration totalAllocatedTime = AggregateOfDayAssignments.create(
this.getDayAssignments(FilterType.KEEP_ALL)).getTotalTime();
this.getDayAssignments(FilterType.KEEP_ALL)).getTotalTime();
EffortDuration totalTheoreticalCompletedTime = this.getTheoreticalCompletedTimeUntilDate(date);
if (totalAllocatedTime.isZero() || totalTheoreticalCompletedTime.isZero()) {
if ( totalAllocatedTime.isZero() || totalTheoreticalCompletedTime.isZero() ) {
return BigDecimal.ZERO;
}
Validate.isTrue(totalTheoreticalCompletedTime.getSeconds() <= totalAllocatedTime.getSeconds());
return totalTheoreticalCompletedTime.dividedByAndResultAsBigDecimal(totalAllocatedTime);
}
@ -779,16 +783,18 @@ public abstract class TaskElement extends BaseEntity {
}
public BigDecimal getBudget() {
if ((taskSource != null) && (taskSource.getOrderElement() != null)) {
if ( (taskSource != null) && (taskSource.getOrderElement() != null) ) {
return taskSource.getOrderElement().getBudget();
}
return null;
}
public BigDecimal getResourcesBudget() {
if ((taskSource != null) && (taskSource.getOrderElement() != null)) {
if ( (taskSource != null) && (taskSource.getOrderElement() != null) ) {
return taskSource.getOrderElement().getResourcesBudget();
}
return null;
}
@ -800,52 +806,53 @@ public abstract class TaskElement extends BaseEntity {
public TaskDeadlineViolationStatusEnum getDeadlineViolationStatus() {
LocalDate deadline = this.getDeadline();
if (deadline == null) {
if ( deadline == null ) {
return TaskDeadlineViolationStatusEnum.NO_DEADLINE;
} else if (this.getEndAsLocalDate().isAfter(deadline)) {
} else if ( this.getEndAsLocalDate().isAfter(deadline) ) {
return TaskDeadlineViolationStatusEnum.DEADLINE_VIOLATED;
} else {
return TaskDeadlineViolationStatusEnum.ON_SCHEDULE;
}
}
public static IntraDayDate maxDate(
Collection<? extends TaskElement> tasksToSave) {
public static IntraDayDate maxDate(Collection<? extends TaskElement> tasksToSave) {
List<IntraDayDate> endDates = toEndDates(tasksToSave);
return endDates.isEmpty() ? null : Collections.max(endDates);
}
private static List<IntraDayDate> toEndDates(
Collection<? extends TaskElement> tasksToSave) {
List<IntraDayDate> result = new ArrayList<IntraDayDate>();
private static List<IntraDayDate> toEndDates(Collection<? extends TaskElement> tasksToSave) {
List<IntraDayDate> result = new ArrayList<>();
for (TaskElement taskElement : tasksToSave) {
IntraDayDate endDate = taskElement.getIntraDayEndDate();
if (endDate != null) {
if ( endDate != null ) {
result.add(endDate);
} else {
LOG.warn("the task" + taskElement + " has null end date");
}
}
return result;
}
public static IntraDayDate minDate(
Collection<? extends TaskElement> tasksToSave) {
public static IntraDayDate minDate(Collection<? extends TaskElement> tasksToSave) {
List<IntraDayDate> startDates = toStartDates(tasksToSave);
return startDates.isEmpty() ? null : Collections.min(startDates);
}
private static List<IntraDayDate> toStartDates(
Collection<? extends TaskElement> tasksToSave) {
List<IntraDayDate> result = new ArrayList<IntraDayDate>();
private static List<IntraDayDate> toStartDates(Collection<? extends TaskElement> tasksToSave) {
List<IntraDayDate> result = new ArrayList<>();
for (TaskElement taskElement : tasksToSave) {
IntraDayDate startDate = taskElement.getIntraDayStartDate();
if (startDate != null) {
if ( startDate != null ) {
result.add(startDate);
} else {
LOG.warn("the task" + taskElement + " has null start date");
}
}
return result;
}

View file

@ -73,8 +73,7 @@ public class LimitingResourceAllocator {
@Override
protected boolean hasNext(boolean currentDateIsLessThanEnd) {
return currentDateIsLessThanEnd
|| currentDuration.compareTo(goal) <= 0;
return currentDateIsLessThanEnd || currentDuration.compareTo(goal) <= 0;
}
public void setCurrent(EffortDuration currentDuration) {
@ -88,8 +87,7 @@ public class LimitingResourceAllocator {
}
private final static ResourcesPerDay ONE_RESOURCE_PER_DAY = ResourcesPerDay
.amount(new BigDecimal(1));
private final static ResourcesPerDay ONE_RESOURCE_PER_DAY = ResourcesPerDay.amount(new BigDecimal(1));
/**
* Returns first valid gap in queue for element
@ -103,12 +101,10 @@ public class LimitingResourceAllocator {
* @param element element to fit into queue
* @return
*/
public static Gap getFirstValidGap(
LimitingResourceQueue queue, LimitingResourceQueueElement element) {
public static Gap getFirstValidGap(LimitingResourceQueue queue, LimitingResourceQueueElement element) {
final Resource resource = queue.getResource();
final List<LimitingResourceQueueElement> elements = new LinkedList<LimitingResourceQueueElement>(
queue.getLimitingResourceQueueElements());
final List<LimitingResourceQueueElement> elements = new LinkedList<>(queue.getLimitingResourceQueueElements());
final int size = elements.size();
final DateAndHour startTime = getStartTimeBecauseOfGantt(element);
@ -119,10 +115,11 @@ public class LimitingResourceAllocator {
Gap gap = getGapInQueueAtPosition(
resource, elements, startTime, pos++);
if (gap != null) {
List<Gap> subgaps = getFittingSubgaps(
element, gap, resource);
if (!subgaps.isEmpty()) {
if ( gap != null ) {
List<Gap> subgaps = getFittingSubgaps(element, gap, resource);
if ( !subgaps.isEmpty() ) {
return subgaps.get(0);
}
}
@ -133,42 +130,42 @@ public class LimitingResourceAllocator {
return null;
}
private static List<Gap> getFittingSubgaps(
LimitingResourceQueueElement element,
final Gap gap, final Resource resource) {
private static List<Gap> getFittingSubgaps(LimitingResourceQueueElement element,
final Gap gap,
final Resource resource) {
List<Gap> result = new ArrayList<Gap>();
List<Gap> result = new ArrayList<>();
if (isSpecific(element) && gap.canFit(element)) {
if ( isSpecific(element) && gap.canFit(element) ) {
result.add(gap);
} else if (isGeneric(element)) {
final List<Gap> gaps = gap.splitIntoGapsSatisfyingCriteria(
resource, element.getCriteria());
} else if ( isGeneric(element) ) {
final List<Gap> gaps = gap.splitIntoGapsSatisfyingCriteria(resource, element.getCriteria());
for (Gap subgap : gaps) {
if (subgap.canFit(element)) {
if ( subgap.canFit(element) ) {
result.add(subgap);
}
}
}
return result;
}
public static Gap getFirstValidGapSince(
LimitingResourceQueueElement element, LimitingResourceQueue queue,
DateAndHour since) {
public static Gap getFirstValidGapSince(LimitingResourceQueueElement element,
LimitingResourceQueue queue,
DateAndHour since) {
List<Gap> gaps = getValidGapsForElementSince(element, queue, since);
return (!gaps.isEmpty()) ? gaps.get(0) : null;
}
public static List<Gap> getValidGapsForElementSince(
LimitingResourceQueueElement element, LimitingResourceQueue queue,
DateAndHour since) {
public static List<Gap> getValidGapsForElementSince(LimitingResourceQueueElement element,
LimitingResourceQueue queue,
DateAndHour since) {
List<Gap> result = new ArrayList<Gap>();
List<Gap> result = new ArrayList<>();
final Resource resource = queue.getResource();
final List<LimitingResourceQueueElement> elements = new LinkedList<LimitingResourceQueueElement>(
queue.getLimitingResourceQueueElements());
final List<LimitingResourceQueueElement> elements = new LinkedList<>(queue.getLimitingResourceQueueElements());
final int size = elements.size();
int pos = moveUntil(elements, since);
@ -180,9 +177,8 @@ public class LimitingResourceAllocator {
// The queue cannot hold this element (queue.resource
// doesn't meet element.criteria)
if (gap != null) {
List<Gap> subgaps = getFittingSubgaps(
element, gap, resource);
if ( gap != null ) {
List<Gap> subgaps = getFittingSubgaps(element, gap, resource);
result.addAll(subgaps);
}
}
@ -193,7 +189,7 @@ public class LimitingResourceAllocator {
private static int moveUntil(List<LimitingResourceQueueElement> elements, DateAndHour until) {
int pos = 0;
if (elements.size() > 0) {
if ( elements.size() > 0 ) {
// Space between until and first element start time
LimitingResourceQueueElement first = elements.get(0);
if (until.isBefore(first.getStartTime())) {
@ -203,7 +199,8 @@ public class LimitingResourceAllocator {
for (pos = 1; pos < elements.size(); pos++) {
final LimitingResourceQueueElement each = elements.get(pos);
final DateAndHour startTime = each.getStartTime();
if (until.isBefore(startTime) || until.isEquals(startTime)) {
if ( until.isBefore(startTime) || until.isEquals(startTime) ) {
return pos;
}
}
@ -221,46 +218,45 @@ public class LimitingResourceAllocator {
public static DateAndHour getFirstElementTime(List<DayAssignment> dayAssignments) {
final DayAssignment start = dayAssignments.get(0);
return new DateAndHour(start.getDay(), start.getHours());
return new DateAndHour(start.getDay(), start.getDuration().getHours());
}
public static DateAndHour getLastElementTime(List<DayAssignment> dayAssignments) {
final DayAssignment end = dayAssignments.get(dayAssignments.size() - 1);
return new DateAndHour(end.getDay(), end.getHours());
return new DateAndHour(end.getDay(), end.getDuration().getHours());
}
private static Gap getGapInQueueAtPosition(
Resource resource, List<LimitingResourceQueueElement> elements,
DateAndHour startTimeBecauseOfGantt, int pos) {
private static Gap getGapInQueueAtPosition(Resource resource,
List<LimitingResourceQueueElement> elements,
DateAndHour startTimeBecauseOfGantt,
int pos) {
final int size = elements.size();
// No elements in queue
if (size == 0) {
if ( size == 0 ) {
return createLastGap(startTimeBecauseOfGantt, null, resource);
}
// Last element
if (pos == size) {
if ( pos == size ) {
return createLastGap(startTimeBecauseOfGantt, elements.get(size - 1), resource);
}
LimitingResourceQueueElement next = elements.get(pos);
// First element
if (pos == 0
&& startTimeBecauseOfGantt.getDate().isBefore(
next.getStartDate())) {
return Gap.create(resource,
startTimeBecauseOfGantt, next.getStartTime());
if ( pos == 0 && startTimeBecauseOfGantt.getDate().isBefore(next.getStartDate()) ) {
return Gap.create(resource, startTimeBecauseOfGantt, next.getStartTime());
}
// In the middle of two elements
if (pos > 0) {
LimitingResourceQueueElement previous = elements.get(pos - 1);
return Gap.create(resource, DateAndHour
.max(previous.getEndTime(), startTimeBecauseOfGantt), next
.getStartTime());
return Gap.create(resource,
DateAndHour.max(previous.getEndTime(),
startTimeBecauseOfGantt),
next.getStartTime());
}
return null;
@ -270,15 +266,14 @@ public class LimitingResourceAllocator {
return new DateAndHour(new LocalDate(element.getEarliestStartDateBecauseOfGantt()), 0);
}
private static Gap createLastGap(
DateAndHour _startTime, LimitingResourceQueueElement lastElement,
Resource resource) {
private static Gap createLastGap(DateAndHour _startTime,
LimitingResourceQueueElement lastElement,
Resource resource) {
final DateAndHour queueEndTime = (lastElement != null) ? lastElement
.getEndTime() : null;
final DateAndHour queueEndTime = (lastElement != null) ? lastElement.getEndTime() : null;
DateAndHour startTime = DateAndHour.max(_startTime, queueEndTime);
return Gap
.create(resource, startTime, null);
return Gap.create(resource, startTime, null);
}
/**
@ -295,44 +290,38 @@ public class LimitingResourceAllocator {
* @param startTime
* @return
*/
public static List<DayAssignment> generateDayAssignments(
ResourceAllocation<?> resourceAllocation,
Resource resource,
DateAndHour startTime, DateAndHour endsAfter) {
public static List<DayAssignment> generateDayAssignments(ResourceAllocation<?> resourceAllocation,
Resource resource,
DateAndHour startTime,
DateAndHour endsAfter) {
List<DayAssignment> assignments = new LinkedList<DayAssignment>();
List<DayAssignment> assignments = new LinkedList<>();
ResourceCalendar calendar = resource.getCalendar();
final EffortDuration totalEffort = hours(resourceAllocation
.getIntendedTotalHours());
final EffortDuration totalEffort = hours(resourceAllocation.getIntendedTotalHours());
EffortDuration effortAssigned = zero();
UntilEndAndEffort condition = new UntilEndAndEffort(
endsAfter.toIntraDayDate(), totalEffort);
UntilEndAndEffort condition = new UntilEndAndEffort(endsAfter.toIntraDayDate(), totalEffort);
for (PartialDay each : startTime.toIntraDayDate().daysUntil(condition)) {
EffortDuration effortForDay = EffortDuration.min(
calendar.asDurationOn(each,
ONE_RESOURCE_PER_DAY), totalEffort);
DayAssignment dayAssignment = createDayAssignment(
resourceAllocation, resource, each.getDate(), effortForDay);
effortAssigned = effortAssigned.plus(addDayAssignment(assignments,
dayAssignment));
EffortDuration effortForDay = EffortDuration.min(calendar.asDurationOn(each, ONE_RESOURCE_PER_DAY),
totalEffort);
DayAssignment dayAssignment = createDayAssignment(resourceAllocation, resource, each.getDate(),
effortForDay);
effortAssigned = effortAssigned.plus(addDayAssignment(assignments, dayAssignment));
condition.setCurrent(effortAssigned);
}
if (effortAssigned.compareTo(totalEffort) > 0) {
stripStartAssignments(assignments,
effortAssigned.minus(totalEffort));
if ( effortAssigned.compareTo(totalEffort) > 0 ) {
stripStartAssignments(assignments, effortAssigned.minus(totalEffort));
}
return new ArrayList<DayAssignment>(assignments);
return new ArrayList<>(assignments);
}
private static void stripStartAssignments(List<DayAssignment> assignments,
EffortDuration durationSurplus) {
private static void stripStartAssignments(List<DayAssignment> assignments, EffortDuration durationSurplus) {
ListIterator<DayAssignment> listIterator = assignments.listIterator();
while (listIterator.hasNext() && durationSurplus.compareTo(zero()) > 0) {
DayAssignment current = listIterator.next();
EffortDuration durationTaken = min(durationSurplus,
current.getDuration());
EffortDuration durationTaken = min(durationSurplus, current.getDuration());
durationSurplus = durationSurplus.minus(durationTaken);
if (durationTaken.compareTo(current.getDuration()) == 0) {
if ( durationTaken.compareTo(current.getDuration()) == 0 ) {
listIterator.remove();
} else {
listIterator.set(current.withDuration(durationTaken));
@ -341,72 +330,70 @@ public class LimitingResourceAllocator {
}
private static List<DayAssignment> generateDayAssignmentsStartingFromEnd(ResourceAllocation<?> resourceAllocation,
Resource resource,
DateAndHour endTime) {
Resource resource,
DateAndHour endTime) {
ResourceCalendar calendar = resource.getCalendar();
List<DayAssignment> result = new ArrayList<DayAssignment>();
List<DayAssignment> result = new ArrayList<>();
LocalDate date = endTime.getDate();
EffortDuration totalIntended = hours(resourceAllocation
.getIntendedTotalHours());
EffortDuration totalIntended = hours(resourceAllocation.getIntendedTotalHours());
// Generate last day assignment
PartialDay firstDay = new PartialDay(IntraDayDate.startOfDay(date),
IntraDayDate.create(date, hours(endTime.getHour())));
EffortDuration effortCanAllocate = min(totalIntended,
calendar.asDurationOn(firstDay, ONE_RESOURCE_PER_DAY));
IntraDayDate.create(date, hours(endTime.getHour())));
EffortDuration effortCanAllocate = min(totalIntended, calendar.asDurationOn(firstDay, ONE_RESOURCE_PER_DAY));
if (effortCanAllocate.compareTo(zero()) > 0) {
DayAssignment dayAssignment = createDayAssignment(
resourceAllocation, resource, date, effortCanAllocate);
totalIntended = totalIntended.minus(addDayAssignment(result,
dayAssignment));
DayAssignment dayAssignment = createDayAssignment(resourceAllocation, resource, date, effortCanAllocate);
totalIntended = totalIntended.minus(addDayAssignment(result, dayAssignment));
}
// Generate rest of day assignments
for (date = date.minusDays(1); totalIntended.compareTo(zero()) > 0; date = date
.minusDays(1)) {
EffortDuration duration = min(totalIntended, calendar.asDurationOn(
PartialDay.wholeDay(date), ONE_RESOURCE_PER_DAY));
DayAssignment dayAssigment = createDayAssignment(
resourceAllocation, resource, date, duration);
totalIntended = totalIntended.minus(addDayAssignment(result,
dayAssigment));
for (date = date.minusDays(1); totalIntended.compareTo(zero()) > 0; date = date.minusDays(1)) {
EffortDuration duration = min(totalIntended,
calendar.asDurationOn(PartialDay.wholeDay(date),
ONE_RESOURCE_PER_DAY));
DayAssignment dayAssigment = createDayAssignment(resourceAllocation, resource, date, duration);
totalIntended = totalIntended.minus(addDayAssignment(result, dayAssigment));
}
return result;
}
private static DayAssignment createDayAssignment(
ResourceAllocation<?> resourceAllocation, Resource resource,
LocalDate date, EffortDuration toAllocate) {
if (resourceAllocation instanceof SpecificResourceAllocation) {
private static DayAssignment createDayAssignment(ResourceAllocation<?> resourceAllocation,
Resource resource,
LocalDate date,
EffortDuration toAllocate) {
if ( resourceAllocation instanceof SpecificResourceAllocation ) {
return SpecificDayAssignment.create(date, toAllocate, resource);
} else if (resourceAllocation instanceof GenericResourceAllocation) {
} else if ( resourceAllocation instanceof GenericResourceAllocation ) {
return GenericDayAssignment.create(date, toAllocate, resource);
}
return null;
}
private static EffortDuration addDayAssignment(List<DayAssignment> list,
DayAssignment dayAssignment) {
if (dayAssignment != null) {
private static EffortDuration addDayAssignment(List<DayAssignment> list, DayAssignment dayAssignment) {
if ( dayAssignment != null ) {
list.add(dayAssignment);
return dayAssignment.getDuration();
}
return zero();
}
public static DateAndHour startTimeToAllocateStartingFromEnd(
ResourceAllocation<?> resourceAllocation, Resource resource,
Gap gap) {
public static DateAndHour startTimeToAllocateStartingFromEnd(ResourceAllocation<?> resourceAllocation,
Resource resource,
Gap gap) {
// Last element, time is end of last element (gap.starttime)
if (gap.getEndTime() == null) {
if ( gap.getEndTime() == null ) {
return gap.getStartTime();
}
final List<DayAssignment> dayAssignments = LimitingResourceAllocator
.generateDayAssignmentsStartingFromEnd(resourceAllocation,
resource, gap.getEndTime());
.generateDayAssignmentsStartingFromEnd(resourceAllocation, resource, gap.getEndTime());
return LimitingResourceAllocator.getLastElementTime(dayAssignments);
}

View file

@ -66,9 +66,10 @@ public class CompletedEstimatedHoursPerTaskDTO {
public String getTaskName(Task task) {
String result = task.getName();
if (result == null || result.isEmpty()) {
if ( result == null || result.isEmpty() ) {
result = task.getOrderElement().getName();
}
return result;
}
@ -76,15 +77,16 @@ public class CompletedEstimatedHoursPerTaskDTO {
Integer result = new Integer(0);
final List<DayAssignment> dayAssignments = task.getDayAssignments(FilterType.WITHOUT_DERIVED);
if (dayAssignments.isEmpty()) {
if ( dayAssignments.isEmpty() ) {
return result;
}
for (DayAssignment dayAssignment : dayAssignments) {
if (date == null || dayAssignment.getDay().compareTo(date) <= 0) {
result += dayAssignment.getHours();
if ( date == null || dayAssignment.getDay().compareTo(date) <= 0 ) {
result += dayAssignment.getDuration().getHours();
}
}
return result;
}
@ -93,16 +95,17 @@ public class CompletedEstimatedHoursPerTaskDTO {
final List<WorkReportLine> workReportLines = workReportLineDAO
.findByOrderElementAndChildren(task.getOrderElement());
if (workReportLines.isEmpty()) {
if ( workReportLines.isEmpty() ) {
return result;
}
for (WorkReportLine workReportLine : workReportLines) {
final LocalDate workReportLineDate = new LocalDate(workReportLine.getDate());
if (date == null || workReportLineDate.compareTo(date) <= 0) {
if ( date == null || workReportLineDate.compareTo(date) <= 0 ) {
result = EffortDuration.sum(result, workReportLine.getEffort());
}
}
return result;
}

View file

@ -83,27 +83,28 @@ public class WorkingProgressPerTaskDTO {
this.realHours = calculateRealHours(task, date);
this.averageProgress = task.getOrderElement().getAdvancePercentage(date);
this.imputedProgress = (totalPlannedHours != 0) ? new Double(
realHours
.toHoursAsDecimalWithScale(2).doubleValue()
/ totalPlannedHours.doubleValue())
this.imputedProgress = (totalPlannedHours != 0) ?
new Double(realHours.toHoursAsDecimalWithScale(2).doubleValue() / totalPlannedHours.doubleValue())
: new Double(0);
this.plannedProgress = (totalPlannedHours != 0) ?
new Double(partialPlannedHours / totalPlannedHours.doubleValue())
: new Double(0);
this.plannedProgress = (totalPlannedHours != 0) ? new Double(partialPlannedHours / totalPlannedHours.doubleValue()) : new Double(0);
this.costDifference = calculateCostDifference(averageProgress,
new BigDecimal(totalPlannedHours),
realHours.toHoursAsDecimalWithScale(2));
new BigDecimal(totalPlannedHours),
realHours.toHoursAsDecimalWithScale(2));
this.planningDifference = calculatePlanningDifference(averageProgress,
new BigDecimal(totalPlannedHours), new BigDecimal(
partialPlannedHours));
new BigDecimal(totalPlannedHours),
new BigDecimal(partialPlannedHours));
this.ratioCostDifference = calculateRatioCostDifference(averageProgress, imputedProgress);
this.ratioPlanningDifference = calculateRatioPlanningDifference(averageProgress, plannedProgress);
}
public String getTaskName(Task task) {
String result = task.getName();
if (result == null || result.isEmpty()) {
if ( result == null || result.isEmpty() ) {
result = task.getOrderElement().getName();
}
return result;
}
@ -111,13 +112,13 @@ realHours
Integer result = new Integer(0);
final List<DayAssignment> dayAssignments = task.getDayAssignments(FilterType.WITHOUT_DERIVED);
if (dayAssignments.isEmpty()) {
if ( dayAssignments.isEmpty() ) {
return result;
}
for (DayAssignment dayAssignment : dayAssignments) {
if (date == null || dayAssignment.getDay().compareTo(date) <= 0) {
result += dayAssignment.getHours();
if ( date == null || dayAssignment.getDay().compareTo(date) <= 0 ) {
result += dayAssignment.getDuration().getHours();
}
}
return result;
@ -128,13 +129,13 @@ realHours
final List<WorkReportLine> workReportLines = workReportLineDAO
.findByOrderElementAndChildren(task.getOrderElement());
if (workReportLines.isEmpty()) {
if ( workReportLines.isEmpty() ) {
return result;
}
for (WorkReportLine workReportLine : workReportLines) {
final LocalDate workReportLineDate = new LocalDate(workReportLine.getDate());
if (date == null || workReportLineDate.compareTo(date) <= 0) {
if ( date == null || workReportLineDate.compareTo(date) <= 0 ) {
result = EffortDuration.sum(result, workReportLine.getEffort());
}
}
@ -206,30 +207,36 @@ realHours
}
public BigDecimal calculateCostDifference(BigDecimal averageProgress,
BigDecimal totalPlannedHours, BigDecimal realHours) {
BigDecimal totalPlannedHours,
BigDecimal realHours) {
BigDecimal result = averageProgress;
result = result.multiply(totalPlannedHours);
return result.subtract(realHours);
}
public BigDecimal calculatePlanningDifference(BigDecimal averageProgress,
BigDecimal totalPlannedHours, BigDecimal partialPlannedHours) {
BigDecimal totalPlannedHours,
BigDecimal partialPlannedHours) {
BigDecimal result = averageProgress;
result = result.multiply(totalPlannedHours);
return result.subtract(partialPlannedHours);
}
public BigDecimal calculateRatioCostDifference(BigDecimal averageProgress, Double imputedProgress) {
if (imputedProgress.doubleValue() == 0) {
if ( imputedProgress.doubleValue() == 0 ) {
return new BigDecimal(0);
}
return averageProgress.divide(new BigDecimal(imputedProgress), 2, RoundingMode.HALF_UP);
}
public BigDecimal calculateRatioPlanningDifference(BigDecimal averageProgress, Double plannedProgress) {
if (plannedProgress.doubleValue() == 0) {
if ( plannedProgress.doubleValue() == 0 ) {
return new BigDecimal(0);
}
return averageProgress.divide(new BigDecimal(plannedProgress), 2, RoundingMode.HALF_UP);
}

View file

@ -49,9 +49,9 @@ public class DayAssignmentMatchers {
@Override
final public boolean matches(Object value) {
if (value instanceof List) {
List<DayAssignment> dayAssignments = new ArrayList<DayAssignment>(
(List<DayAssignment>) value);
if ( value instanceof List ) {
List<DayAssignment> dayAssignments = new ArrayList<>((List<DayAssignment>) value);
return matches(dayAssignments);
}
return false;
@ -70,48 +70,48 @@ public class DayAssignmentMatchers {
@Override
public void describeTo(Description description) {
description.appendText("the first assignment must be at date"
+ start);
description.appendText("the first assignment must be at date" + start);
}
public CombinableMatcher<List<? extends DayAssignment>> consecutiveDays(
int days) {
return both(this).and(
DayAssignmentMatchers.consecutiveDays(days));
public CombinableMatcher<List<? extends DayAssignment>> consecutiveDays(int days) {
return both(this).and(DayAssignmentMatchers.consecutiveDays(days));
}
@Override
protected boolean matches(List<DayAssignment> assignments) {
return !assignments.isEmpty()
&& assignments.get(0).getDay().equals(start);
return !assignments.isEmpty() && assignments.get(0).getDay().equals(start);
}
}
public static final Matcher<List<? extends DayAssignment>> haveHours(
final int... hours) {
public static final Matcher<List<? extends DayAssignment>> haveHours(final int... hours) {
return new BaseMatcher<List<? extends DayAssignment>>() {
@Override
public boolean matches(Object value) {
if (value instanceof List) {
if ( value instanceof List ) {
List<? extends DayAssignment> assignments = (List<? extends DayAssignment>) value;
if (assignments.size() != hours.length) {
if ( assignments.size() != hours.length ) {
return false;
}
for (int i = 0; i < hours.length; i++) {
if (hours[i] != assignments.get(i).getHours()) {
if ( hours[i] != assignments.get(i).getDuration().getHours() ) {
return false;
}
}
return true;
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("must have hours: "
+ Arrays.toString(hours));
description.appendText("must have hours: " + Arrays.toString(hours));
}
};
}
@ -121,15 +121,17 @@ public class DayAssignmentMatchers {
@Override
public boolean matches(List<DayAssignment> assignments) {
if (assignments.size() != days) {
if ( assignments.size() != days ) {
return false;
}
if (days == 0) {
if ( days == 0 ) {
return true;
}
LocalDate current = assignments.get(0).getDay();
for (DayAssignment d : assignments) {
if (!d.getDay().equals(current)) {
if ( !d.getDay().equals(current) ) {
return false;
}
current = current.plusDays(1);
@ -139,8 +141,7 @@ public class DayAssignmentMatchers {
@Override
public void describeTo(Description description) {
description.appendText("it must have " + days
+ " days consecutive ");
description.appendText("it must have " + days + " days consecutive ");
}
};
}
@ -160,27 +161,32 @@ public class DayAssignmentMatchers {
@Override
protected boolean matches(List<DayAssignment> assignments) {
for (DayAssignment dayAssignment : assignments) {
if (dayAssignment instanceof GenericDayAssignment) {
if ( dayAssignment instanceof GenericDayAssignment ) {
GenericDayAssignment generic = (GenericDayAssignment) dayAssignment;
if (!allocation.equals(generic
.getGenericResourceAllocation())) {
if ( !allocation.equals(generic.getGenericResourceAllocation()) ) {
return false;
}
} else if (dayAssignment instanceof SpecificDayAssignment) {
} else if ( dayAssignment instanceof SpecificDayAssignment ) {
SpecificDayAssignment specific = (SpecificDayAssignment) dayAssignment;
if (!allocation.equals(specific
.getSpecificResourceAllocation())) {
if ( !allocation.equals(specific.getSpecificResourceAllocation()) ) {
return false;
}
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("all must belong to allocation "
+ allocation);
description.appendText("all must belong to allocation " + allocation);
}
};
}

View file

@ -59,6 +59,7 @@ import org.libreplan.business.resources.entities.MachineWorkersConfigurationUnit
import org.libreplan.business.resources.entities.Resource;
import org.libreplan.business.resources.entities.Worker;
import org.libreplan.business.scenarios.bootstrap.IScenariosBootstrap;
import org.libreplan.business.workingday.EffortDuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -67,8 +68,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Óscar González Fernández <ogonzalez@igalia.com>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE, BUSINESS_SPRING_CONFIG_TEST_FILE })
public class DerivedAllocationGeneratorTest {
@Autowired
@ -95,7 +95,7 @@ public class DerivedAllocationGeneratorTest {
@SuppressWarnings("unchecked")
private void givenFinder(Worker... workers) {
IWorkerFinder result = createNiceMock(IWorkerFinder.class);
Collection<? extends Criterion> argument = (Collection<? extends Criterion>) anyObject();
Collection<? extends Criterion> argument = anyObject();
expect(result.findWorkersMatching(argument)).andReturn(
Arrays.asList(workers)).anyTimes();
replay(result);
@ -118,36 +118,34 @@ public class DerivedAllocationGeneratorTest {
configurationUnit = result;
}
private Set<MachineWorkerAssignment> assignmentsFor(
MachineWorkersConfigurationUnit unit, Worker[] workers) {
Set<MachineWorkerAssignment> result = new HashSet<MachineWorkerAssignment>();
private Set<MachineWorkerAssignment> assignmentsFor(MachineWorkersConfigurationUnit unit, Worker[] workers) {
Set<MachineWorkerAssignment> result = new HashSet<>();
for (Worker each : workers) {
MachineWorkerAssignment assignment = workerAssignment(unit,each);
result.add(assignment);
}
return result;
}
private MachineWorkerAssignment workerAssignment(
MachineWorkersConfigurationUnit unit, Worker each) {
private MachineWorkerAssignment workerAssignment(MachineWorkersConfigurationUnit unit, Worker each) {
MachineWorkerAssignment result = createNiceMock(MachineWorkerAssignment.class);
expect(result.getMachineWorkersConfigurationUnit()).andReturn(unit)
.anyTimes();
expect(result.getMachineWorkersConfigurationUnit()).andReturn(unit).anyTimes();
expect(result.getWorker()).andReturn(each);
expect(result.getStartDate()).andReturn(
asDate(new LocalDate(2000, 1, 1))).anyTimes();
expect(result.getStartDate()).andReturn(asDate(new LocalDate(2000, 1, 1))).anyTimes();
expect(result.getFinishDate()).andReturn(null).anyTimes();
replay(result);
return result;
}
private Worker workerWithAlwaysAssignedHours(int assignedHours){
Worker result = createNiceMock(Worker.class);
expect(
result.getAssignedDurationDiscounting(isA(Map.class),
isA(LocalDate.class))).andReturn(hours(assignedHours))
expect(result.getAssignedDurationDiscounting(isA(Map.class), isA(LocalDate.class)))
.andReturn(hours(assignedHours))
.anyTimes();
replay(result);
return result;
}
@ -156,26 +154,28 @@ public class DerivedAllocationGeneratorTest {
}
private void givenDayAssignments() {
dayAssignments = new ArrayList<DayAssignment>();
dayAssignments = new ArrayList<>();
}
private void givenDayAssignments(LocalDate start, int... hours) {
dayAssignments = new ArrayList<DayAssignment>();
dayAssignments = new ArrayList<>();
for (int i = 0; i < hours.length; i++) {
dayAssignments.add(createAssignment(start.plusDays(i), machine,
hours[i]));
}
}
private DayAssignment createAssignment(LocalDate day, Machine machine,
int hours) {
private DayAssignment createAssignment(LocalDate day, Machine machine, int hours) {
DayAssignment dayAssignment = createNiceMock(DayAssignment.class);
expect(dayAssignment.getHours()).andReturn(hours).anyTimes();
// expect(dayAssignment.getHours()).andReturn(hours).anyTimes();
expect(dayAssignment.getDuration()).andReturn(hours(hours)).anyTimes();
expect(dayAssignment.getResource()).andReturn(machine).anyTimes();
expect(dayAssignment.getDay()).andReturn(day).anyTimes();
expect(dayAssignment.isAssignedTo(machine)).andReturn(true).anyTimes();
replay(dayAssignment);
return dayAssignment;
}
@ -184,8 +184,7 @@ public class DerivedAllocationGeneratorTest {
givenFinder();
givenConfigurationUnit();
givenDayAssignments();
DerivedAllocationGenerator.generate(derivedFrom, finder,
configurationUnit, dayAssignments);
DerivedAllocationGenerator.generate(derivedFrom, finder, configurationUnit, dayAssignments);
}
@Test(expected = IllegalArgumentException.class)
@ -193,8 +192,7 @@ public class DerivedAllocationGeneratorTest {
givenDerivedFrom();
givenConfigurationUnit();
givenDayAssignments();
DerivedAllocationGenerator.generate(derivedFrom, finder,
configurationUnit, dayAssignments);
DerivedAllocationGenerator.generate(derivedFrom, finder, configurationUnit, dayAssignments);
}
@Test(expected = IllegalArgumentException.class)
@ -202,8 +200,7 @@ public class DerivedAllocationGeneratorTest {
givenDerivedFrom();
givenFinder();
givenDayAssignments();
DerivedAllocationGenerator.generate(derivedFrom, finder,
configurationUnit, dayAssignments);
DerivedAllocationGenerator.generate(derivedFrom, finder, configurationUnit, dayAssignments);
}
@Test(expected = IllegalArgumentException.class)
@ -211,8 +208,7 @@ public class DerivedAllocationGeneratorTest {
givenDerivedFrom();
givenFinder();
givenConfigurationUnit();
DerivedAllocationGenerator.generate(derivedFrom, finder,
configurationUnit, dayAssignments);
DerivedAllocationGenerator.generate(derivedFrom, finder, configurationUnit, dayAssignments);
}
@Test
@ -222,10 +218,8 @@ public class DerivedAllocationGeneratorTest {
givenConfigurationUnit(new BigDecimal(1.5), new Worker());
givenDayAssignments(new LocalDate(2009, 10, 20), 8, 8, 8, 4);
DerivedAllocation derivedAllocation = DerivedAllocationGenerator
.generate(derivedFrom, finder, configurationUnit,
dayAssignments);
List<DerivedDayAssignment> assignments = derivedAllocation
.getAssignments();
.generate(derivedFrom, finder, configurationUnit, dayAssignments);
List<DerivedDayAssignment> assignments = derivedAllocation.getAssignments();
assertThat(assignments, haveHours(12, 12, 12, 6));
}
@ -238,14 +232,11 @@ public class DerivedAllocationGeneratorTest {
givenDayAssignments(start, 8, 8, 8, 4);
Machine otherMachine = Machine.create();
dayAssignments
.add(createAssignment(start.plusDays(5), otherMachine, 8));
dayAssignments.add(createAssignment(start.plusDays(5), otherMachine, 8));
DerivedAllocation derivedAllocation = DerivedAllocationGenerator
.generate(derivedFrom, finder, configurationUnit,
dayAssignments);
List<DerivedDayAssignment> assignments = derivedAllocation
.getAssignments();
.generate(derivedFrom, finder, configurationUnit, dayAssignments);
List<DerivedDayAssignment> assignments = derivedAllocation.getAssignments();
assertThat(assignments.size(), equalTo(4));
}
@ -258,12 +249,9 @@ public class DerivedAllocationGeneratorTest {
givenConfigurationUnit(new BigDecimal(1.5));
givenDayAssignments(new LocalDate(2009, 10, 20), 8, 8, 8, 4);
DerivedAllocation derivedAllocation = DerivedAllocationGenerator
.generate(derivedFrom, finder, configurationUnit,
dayAssignments);
List<DerivedDayAssignment> assignments = derivedAllocation
.getAssignments();
Map<Resource, List<DerivedDayAssignment>> byResource = DayAssignment
.byResourceAndOrdered(assignments);
.generate(derivedFrom, finder, configurationUnit, dayAssignments);
List<DerivedDayAssignment> assignments = derivedAllocation.getAssignments();
Map<Resource, List<DerivedDayAssignment>> byResource = DayAssignment.byResourceAndOrdered(assignments);
assertThat(byResource.get(worker1), haveHours(7, 7, 7, 4));
assertThat(byResource.get(worker2), haveHours(5, 5, 5, 2));
}

View file

@ -50,6 +50,7 @@ import org.libreplan.business.resources.entities.Machine;
import org.libreplan.business.resources.entities.MachineWorkersConfigurationUnit;
import org.libreplan.business.resources.entities.Resource;
import org.libreplan.business.resources.entities.Worker;
import org.libreplan.business.workingday.EffortDuration;
/**
* @author Óscar González Fernández <ogonzalez@igalia.com>
@ -81,21 +82,20 @@ public class DerivedAllocationTest {
private void givenADerivedAllocation() {
givenDerivedFrom();
givenConfigurationUnit();
derivedAllocation = DerivedAllocation.create(derivedFrom,
configurationUnit);
derivedAllocation = DerivedAllocation.create(derivedFrom, configurationUnit);
}
private void givenDayAssignments(LocalDate start, Resource resource, int... hours) {
givenDayAssignments(derivedAllocation, start, resource, hours);
}
private void givenDayAssignments(DerivedAllocation derivedAllocation,
LocalDate start, Resource resource, int... hours) {
dayAssignments = new ArrayList<DerivedDayAssignment>();
private void givenDayAssignments(DerivedAllocation derivedAllocation, LocalDate start,
Resource resource, int... hours) {
dayAssignments = new ArrayList<>();
for (int i = 0; i < hours.length; i++) {
LocalDate current = start.plusDays(i);
DerivedDayAssignment d = DerivedDayAssignment.create(current,
hours[i], resource, derivedAllocation);
DerivedDayAssignment d = DerivedDayAssignment.create(current, EffortDuration.hours(hours[i]),
resource, derivedAllocation);
dayAssignments.add(d);
}
}
@ -116,8 +116,7 @@ public class DerivedAllocationTest {
private void givenGenericDerivedFrom(Resource... resources) {
derivedFrom = createNiceMock(GenericResourceAllocation.class);
GenericResourceAllocation generic = (GenericResourceAllocation) derivedFrom;
expect(generic.getAssociatedResources()).andReturn(
Arrays.asList(resources));
expect(generic.getAssociatedResources()).andReturn(Arrays.asList(resources));
replay(derivedFrom);
}
@ -129,8 +128,7 @@ public class DerivedAllocationTest {
public void aDerivedAllocationHasAMachineWorkerConfigurationUnitAndAResourceAllocation() {
givenConfigurationUnit();
givenDerivedFrom();
DerivedAllocation result = DerivedAllocation.create(derivedFrom,
configurationUnit);
DerivedAllocation result = DerivedAllocation.create(derivedFrom, configurationUnit);
assertNotNull(result);
assertThat(result.getConfigurationUnit(), equalTo(configurationUnit));
assertEquals(result.getDerivedFrom(), derivedFrom);
@ -166,8 +164,7 @@ public class DerivedAllocationTest {
public void aJustCreatedDerivedAllocationIsANewObject() {
givenDerivedFrom();
givenConfigurationUnit();
DerivedAllocation result = DerivedAllocation.create(derivedFrom,
configurationUnit);
DerivedAllocation result = DerivedAllocation.create(derivedFrom, configurationUnit);
assertTrue(result.isNewObject());
}
@ -176,8 +173,7 @@ public class DerivedAllocationTest {
givenADerivedAllocation();
givenDayAssignments(new LocalDate(2008, 12, 1), worker, 8, 8, 8, 8);
derivedAllocation.resetAssignmentsTo(dayAssignments);
assertThat(derivedAllocation.getAssignments(),
compareValuesExceptParent(dayAssignments));
assertThat(derivedAllocation.getAssignments(), compareValuesExceptParent(dayAssignments));
}
private Matcher<List<DerivedDayAssignment>> compareValuesExceptParent(
@ -185,46 +181,47 @@ public class DerivedAllocationTest {
return compareValuesExceptParent(Arrays.asList(derivedDayAssignments));
}
private Matcher<List<DerivedDayAssignment>> compareValuesExceptParent(
final List<DerivedDayAssignment> expected) {
private Matcher<List<DerivedDayAssignment>> compareValuesExceptParent(final List<DerivedDayAssignment> expected) {
return new BaseMatcher<List<DerivedDayAssignment>>() {
@Override
public boolean matches(Object object) {
if (!(object instanceof Collection<?>)) {
if ( !(object instanceof Collection<?>) ) {
return false;
}
Collection<DerivedDayAssignment> arg = (Collection<DerivedDayAssignment>) object;
if (arg.size() != expected.size()) {
if ( arg.size() != expected.size() ) {
return false;
}
Iterator<DerivedDayAssignment> argIterator = arg.iterator();
Iterator<DerivedDayAssignment> expectedIterator = expected
.iterator();
Iterator<DerivedDayAssignment> expectedIterator = expected.iterator();
while (argIterator.hasNext()) {
DerivedDayAssignment dayAssignment = argIterator.next();
DerivedDayAssignment expectedAssignment = expectedIterator.next();
Resource resource = dayAssignment.getResource();
Resource expectedResource = expectedAssignment
.getResource();
Resource expectedResource = expectedAssignment.getResource();
LocalDate day = dayAssignment.getDay();
LocalDate expectedDay = expectedAssignment.getDay();
int hours = dayAssignment.getHours();
int expectedHours = expectedAssignment
.getHours();
if (!resource.equals(expectedResource)
|| !day.equals(expectedDay)
|| hours != expectedHours) {
int hours = dayAssignment.getDuration().getHours();
int expectedHours = expectedAssignment.getDuration().getHours();
if ( !resource.equals(expectedResource) || !day.equals(expectedDay)
|| hours != expectedHours ) {
return false;
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("must have the same values than "
+ expected);
description.appendText("must have the same values than " + expected);
}
};
}
@ -233,19 +230,17 @@ public class DerivedAllocationTest {
public void theDerivedDayAssignmentsMustBeForTheSameMachine() {
givenADerivedAllocation();
final Machine otherMachine = Machine.create();
givenDayAssignments(new LocalDate(2008, 12, 1), otherMachine, 8, 8,
8);
givenDayAssignments(new LocalDate(2008, 12, 1), otherMachine, 8, 8, 8);
derivedAllocation.resetAssignmentsTo(dayAssignments);
}
@Test
public void whenResettingAssignmentsTheParentIsChanged() {
givenADerivedAllocation();
DerivedAllocation another = DerivedAllocation.create(derivedFrom,
configurationUnit);
givenDayAssignments(another, new LocalDate(2008, 12, 1), worker, 8, 8,
8);
DerivedAllocation another = DerivedAllocation.create(derivedFrom, configurationUnit);
givenDayAssignments(another, new LocalDate(2008, 12, 1), worker, 8, 8, 8);
derivedAllocation.resetAssignmentsTo(dayAssignments);
for (DerivedDayAssignment each : derivedAllocation.getAssignments()) {
assertTrue(each.belongsTo(derivedAllocation));
}
@ -259,13 +254,11 @@ public class DerivedAllocationTest {
derivedAllocation.resetAssignmentsTo(dayAssignments);
final LocalDate startInterval = start.plusDays(2);
final LocalDate finishInterval = start.plusDays(4);
DerivedDayAssignment newAssignment = DerivedDayAssignment.create(
startInterval, 3, worker, derivedAllocation);
derivedAllocation.resetAssignmentsTo(startInterval, finishInterval,
Arrays.asList(newAssignment));
assertThat(derivedAllocation.getAssignments(),
compareValuesExceptParent(dayAssignments.get(0), dayAssignments
.get(1), newAssignment));
DerivedDayAssignment newAssignment = DerivedDayAssignment.create(startInterval, EffortDuration.hours(3),
worker, derivedAllocation);
derivedAllocation.resetAssignmentsTo(startInterval, finishInterval, Arrays.asList(newAssignment));
assertThat(derivedAllocation.getAssignments(), compareValuesExceptParent(
dayAssignments.get(0), dayAssignments.get(1), newAssignment));
}
@Test
@ -274,10 +267,9 @@ public class DerivedAllocationTest {
LocalDate start = new LocalDate(2008, 12, 1);
givenDayAssignments(start, worker, 8, 8, 8, 8);
derivedAllocation.resetAssignmentsTo(dayAssignments);
DerivedDayAssignment newAssignment = DerivedDayAssignment.create(start
.minusDays(1), 3, worker, derivedAllocation);
derivedAllocation.resetAssignmentsTo(start, start.plusDays(4), Arrays
.asList(newAssignment));
DerivedDayAssignment newAssignment = DerivedDayAssignment.create(
start.minusDays(1), EffortDuration.hours(3), worker, derivedAllocation);
derivedAllocation.resetAssignmentsTo(start, start.plusDays(4), Arrays.asList(newAssignment));
assertTrue(derivedAllocation.getAssignments().isEmpty());
}
@ -291,10 +283,8 @@ public class DerivedAllocationTest {
@Test
public void asDerivedFromChangesTheDerivedFromProperty() {
givenADerivedAllocation();
ResourceAllocation<?> newDerivedFrom = GenericResourceAllocation
.create();
DerivedAllocation modified = derivedAllocation
.asDerivedFrom(newDerivedFrom);
ResourceAllocation<?> newDerivedFrom = GenericResourceAllocation.create();
DerivedAllocation modified = derivedAllocation.asDerivedFrom(newDerivedFrom);
assertEquals(newDerivedFrom, modified.getDerivedFrom());
}

View file

@ -496,7 +496,7 @@ public class GenericResourceAllocationTest {
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(2));
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(orderedAssignmentsFor.get(0).getHours(), equalTo(standardHoursPerDay * 2));
assertThat(orderedAssignmentsFor.get(0).getDuration().getHours(), equalTo(standardHoursPerDay * 2));
}
@Test
@ -531,7 +531,7 @@ public class GenericResourceAllocationTest {
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assigmments = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assigmments.get(0).getHours(), equalTo(defaultWorkableHours));
assertThat(assigmments.get(0).getDuration().getHours(), equalTo(defaultWorkableHours));
}
@Test

View file

@ -64,18 +64,15 @@ import org.zkoss.zul.impl.XulElement;
* This class wraps ResourceLoad data inside an specific HTML Div component.
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
*/
public class QueueComponent extends XulElement implements
AfterCompose {
public class QueueComponent extends XulElement implements AfterCompose {
private static final int DEADLINE_MARK_HALF_WIDTH = 5;
public static QueueComponent create(
QueueListComponent queueListComponent,
TimeTracker timeTracker,
LimitingResourceQueue limitingResourceQueue) {
public static QueueComponent create(QueueListComponent queueListComponent,
TimeTracker timeTracker,
LimitingResourceQueue limitingResourceQueue) {
return new QueueComponent(queueListComponent, timeTracker,
limitingResourceQueue);
return new QueueComponent(queueListComponent, timeTracker, limitingResourceQueue);
}
private final QueueListComponent queueListComponent;
@ -86,12 +83,11 @@ public class QueueComponent extends XulElement implements
private LimitingResourceQueue limitingResourceQueue;
private List<QueueTask> queueTasks = new ArrayList<QueueTask>();
private List<QueueTask> queueTasks = new ArrayList<>();
private QueueComponent(
final QueueListComponent queueListComponent,
final TimeTracker timeTracker,
final LimitingResourceQueue limitingResourceQueue) {
private QueueComponent(final QueueListComponent queueListComponent,
final TimeTracker timeTracker,
final LimitingResourceQueue limitingResourceQueue) {
this.queueListComponent = queueListComponent;
this.limitingResourceQueue = limitingResourceQueue;
@ -106,6 +102,7 @@ public class QueueComponent extends XulElement implements
createChildren(limitingResourceQueue, timeTracker.getMapper());
}
};
this.timeTracker.addZoomListener(zoomChangedListener);
}
@ -122,10 +119,8 @@ public class QueueComponent extends XulElement implements
this.limitingResourceQueue = limitingResourceQueue;
}
private void createChildren(LimitingResourceQueue limitingResourceQueue,
IDatesMapper mapper) {
List<QueueTask> queueTasks = createQueueTasks(mapper,
limitingResourceQueue.getLimitingResourceQueueElements());
private void createChildren(LimitingResourceQueue limitingResourceQueue, IDatesMapper mapper) {
List<QueueTask> queueTasks = createQueueTasks(mapper, limitingResourceQueue.getLimitingResourceQueueElements());
appendQueueTasks(queueTasks);
}
@ -165,41 +160,50 @@ public class QueueComponent extends XulElement implements
removeChild(queueTask);
}
private List<QueueTask> createQueueTasks(IDatesMapper datesMapper,
Set<LimitingResourceQueueElement> list) {
private List<QueueTask> createQueueTasks(IDatesMapper datesMapper, Set<LimitingResourceQueueElement> list) {
List<QueueTask> result = new ArrayList<QueueTask>();
List<QueueTask> result = new ArrayList<>();
org.zkoss.ganttz.util.Interval interval = null;
if (timeTracker.getFilter() != null) {
if ( timeTracker.getFilter() != null ) {
timeTracker.getFilter().resetInterval();
interval = timeTracker.getFilter().getCurrentPaginationInterval();
}
for (LimitingResourceQueueElement each : list) {
if (interval != null) {
if (each.getEndDate().toDateMidnight()
.isAfter(interval.getStart().toDateMidnight())
&& each.getStartDate().toDateMidnight()
.isBefore(interval.getFinish().toDateMidnight())) {
if ( interval != null ) {
if ( each.getEndDate().toDateTimeAtStartOfDay().isAfter(interval.getStart().toDateTimeAtStartOfDay()) &&
each.getStartDate().toDateTimeAtStartOfDay()
.isBefore(interval.getFinish().toDateTimeAtStartOfDay()) ) {
result.add(createQueueTask(datesMapper, each));
}
} else {
result.add(createQueueTask(datesMapper, each));
}
}
return result;
}
private static QueueTask createQueueTask(IDatesMapper datesMapper, LimitingResourceQueueElement element) {
validateQueueElement(element);
return createDivForElement(datesMapper, element);
}
private static OrderElement getRootOrder(Task task) {
OrderElement order = task.getOrderElement();
while (order.getParent() != null) {
order = order.getParent();
}
return order;
}
@ -213,15 +217,19 @@ public class QueueComponent extends XulElement implements
result.append(_("Completed: {0}%", element.getAdvancePercentage().multiply(new BigDecimal(100))) + " ");
final ResourceAllocation<?> resourceAllocation = element.getResourceAllocation();
if (resourceAllocation instanceof SpecificResourceAllocation) {
if ( resourceAllocation instanceof SpecificResourceAllocation ) {
final SpecificResourceAllocation specific = (SpecificResourceAllocation) resourceAllocation;
result.append(_("Resource: {0}", specific.getResource().getName()) + " ");
} else if (resourceAllocation instanceof GenericResourceAllocation) {
} else if ( resourceAllocation instanceof GenericResourceAllocation ) {
final GenericResourceAllocation generic = (GenericResourceAllocation) resourceAllocation;
result.append(_("Criteria: {0}", Criterion.getCaptionFor(generic.getCriterions())) + " ");
}
result.append(_("Allocation: [{0},{1}]", element.getStartDate()
.toString(), element.getEndDate()));
result.append(_("Allocation: [{0},{1}]", element.getStartDate().toString(), element.getEndDate()));
return result.toString();
}
@ -234,32 +242,39 @@ public class QueueComponent extends XulElement implements
*/
private static DateAndHour getAdvanceEndDate(LimitingResourceQueueElement element) {
int hoursWorked = 0;
final List<? extends DayAssignment> dayAssignments = element.getDayAssignments();
if (element.hasDayAssignments()) {
if ( element.hasDayAssignments() ) {
final int estimatedWorkedHours = estimatedWorkedHours(element.getIntentedTotalHours(), element.getAdvancePercentage());
for (DayAssignment each: dayAssignments) {
hoursWorked += each.getHours();
if (hoursWorked >= estimatedWorkedHours) {
int hourSlot = each.getHours() - (hoursWorked - estimatedWorkedHours);
hoursWorked += each.getDuration().getHours();
if ( hoursWorked >= estimatedWorkedHours ) {
int hourSlot = each.getDuration().getHours() - (hoursWorked - estimatedWorkedHours);
return new DateAndHour(each.getDay(), hourSlot);
}
}
}
if (hoursWorked != 0) {
if ( hoursWorked != 0 ) {
DayAssignment lastDayAssignment = dayAssignments.get(dayAssignments.size() - 1);
return new DateAndHour(lastDayAssignment.getDay(), lastDayAssignment.getHours());
return new DateAndHour(lastDayAssignment.getDay(), lastDayAssignment.getDuration().getHours());
}
return null;
}
private static int estimatedWorkedHours(Integer totalHours, BigDecimal percentageWorked) {
return (totalHours != null && percentageWorked != null) ? percentageWorked.multiply(
new BigDecimal(totalHours)).intValue() : 0;
boolean bool = totalHours != null && percentageWorked != null;
return bool ? percentageWorked.multiply(new BigDecimal(totalHours)).intValue() : 0;
}
private static QueueTask createDivForElement(IDatesMapper datesMapper,
LimitingResourceQueueElement queueElement) {
private static QueueTask createDivForElement(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) {
final Task task = queueElement.getResourceAllocation().getTask();
final OrderElement order = getRootOrder(task);
@ -270,12 +285,14 @@ public class QueueComponent extends XulElement implements
int startPixels = getStartPixels(datesMapper, queueElement);
result.setLeft(forCSS(startPixels));
if (startPixels < 0) {
if ( startPixels < 0 ) {
cssClass += " truncated-start ";
}
int taskWidth = getWidthPixels(datesMapper, queueElement);
if ((startPixels + taskWidth) > datesMapper.getHorizontalSize()) {
if ( (startPixels + taskWidth) > datesMapper.getHorizontalSize() ) {
taskWidth = datesMapper.getHorizontalSize() - startPixels;
cssClass += " truncated-end ";
} else {
@ -286,138 +303,142 @@ public class QueueComponent extends XulElement implements
LocalDate deadlineDate = task.getDeadline();
boolean isOrderDeadline = false;
if (deadlineDate == null) {
if ( deadlineDate == null ) {
Date orderDate = order.getDeadline();
if (orderDate != null) {
if ( orderDate != null ) {
deadlineDate = LocalDate.fromDateFields(orderDate);
isOrderDeadline = true;
}
}
if (deadlineDate != null) {
if ( deadlineDate != null ) {
int deadlinePosition = getDeadlinePixels(datesMapper, deadlineDate);
if (deadlinePosition < datesMapper.getHorizontalSize()) {
if ( deadlinePosition < datesMapper.getHorizontalSize() ) {
Div deadline = new Div();
deadline.setSclass(isOrderDeadline ? "deadline order-deadline"
: "deadline");
deadline
.setLeft((deadlinePosition - startPixels - DEADLINE_MARK_HALF_WIDTH)
+ "px");
deadline.setSclass(isOrderDeadline ? "deadline order-deadline" : "deadline");
deadline.setLeft((deadlinePosition - startPixels - DEADLINE_MARK_HALF_WIDTH) + "px");
result.appendChild(deadline);
result.appendChild(generateNonWorkableShade(datesMapper,
queueElement));
result.appendChild(generateNonWorkableShade(datesMapper, queueElement));
}
if (deadlineDate.isBefore(queueElement.getEndDate())) {
if ( deadlineDate.isBefore(queueElement.getEndDate()) ) {
cssClass += " unmet-deadline ";
}
}
result.setClass(cssClass);
result.appendChild(generateCompletionShade(datesMapper, queueElement));
Component progressBar = generateProgressBar(datesMapper, queueElement,
task, startPixels);
if (progressBar != null) {
Component progressBar = generateProgressBar(datesMapper, queueElement, task, startPixels);
if ( progressBar != null ) {
result.appendChild(progressBar);
}
return result;
}
private static Component generateProgressBar(IDatesMapper datesMapper,
LimitingResourceQueueElement queueElement, Task task,
int startPixels) {
LimitingResourceQueueElement queueElement,
Task task,
int startPixels) {
DateAndHour advancementEndDate = getAdvanceEndDate(queueElement);
if (advancementEndDate == null) {
if ( advancementEndDate == null ) {
return null;
}
Duration durationBetween = new Duration(queueElement.getStartTime()
.toDateTime().getMillis(), advancementEndDate.toDateTime().getMillis());
Duration durationBetween = new Duration(queueElement.getStartTime().toDateTime().getMillis(),
advancementEndDate.toDateTime().getMillis());
Div progressBar = new Div();
if (!queueElement.getStartDate().isEqual(advancementEndDate.getDate())) {
if ( !queueElement.getStartDate().isEqual(advancementEndDate.getDate()) ) {
progressBar.setWidth(datesMapper.toPixels(durationBetween) + "px");
progressBar.setSclass("queue-progress-bar");
}
return progressBar;
}
private static Div generateNonWorkableShade(IDatesMapper datesMapper,
LimitingResourceQueueElement queueElement) {
private static Div generateNonWorkableShade(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) {
int workableHours = queueElement.getLimitingResourceQueue()
.getResource().getCalendar()
int workableHours = queueElement
.getLimitingResourceQueue()
.getResource()
.getCalendar()
.getCapacityOn(PartialDay.wholeDay(queueElement.getEndDate()))
.roundToHours();
int shadeWidth = Long.valueOf(
(24 - workableHours)
* DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel()).intValue();
int shadeWidth = Long
.valueOf((24 - workableHours) * DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel())
.intValue();
int shadeLeft = Long.valueOf(
(workableHours - queueElement.getEndHour())
* DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel()).intValue()
+ shadeWidth;
;
int shadeLeft = Long
.valueOf((workableHours - queueElement.getEndHour()) * DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel()).intValue() + shadeWidth;
Div notWorkableHoursShade = new Div();
notWorkableHoursShade
.setTooltiptext(_("Workable capacity for this period ")
+ workableHours + _(" hours"));
notWorkableHoursShade.setTooltiptext(_("Workable capacity for this period ") + workableHours + _(" hours"));
notWorkableHoursShade.setContext("");
notWorkableHoursShade.setSclass("not-workable-hours");
notWorkableHoursShade.setStyle("left: " + shadeLeft + "px; width: " + shadeWidth + "px;");
notWorkableHoursShade.setStyle("left: " + shadeLeft + "px; width: "
+ shadeWidth + "px;");
return notWorkableHoursShade;
}
private static Div generateCompletionShade(IDatesMapper datesMapper,
LimitingResourceQueueElement queueElement) {
private static Div generateCompletionShade(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) {
int workableHours = queueElement.getLimitingResourceQueue()
.getResource().getCalendar()
int workableHours = queueElement
.getLimitingResourceQueue()
.getResource()
.getCalendar()
.getCapacityOn(PartialDay.wholeDay(queueElement.getEndDate()))
.roundToHours();
int shadeWidth = new Long((24 - workableHours)
* DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel()).intValue();
int shadeWidth = new Long((24 - workableHours) * DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel())
.intValue();
int shadeLeft = new Long((workableHours - queueElement.getEndHour())
* DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel()).intValue()
+ shadeWidth;
int shadeLeft = new Long((workableHours - queueElement.getEndHour()) * DatesMapperOnInterval.MILISECONDS_PER_HOUR
/ datesMapper.getMilisecondsPerPixel())
.intValue() + shadeWidth;
Div notWorkableHoursShade = new Div();
notWorkableHoursShade.setContext("");
notWorkableHoursShade.setSclass("limiting-completion");
notWorkableHoursShade.setStyle("left: " + shadeLeft + "px; width: " + shadeWidth + "px;");
notWorkableHoursShade.setStyle("left: " + shadeLeft + "px; width: "
+ shadeWidth + "px;");
return notWorkableHoursShade;
}
private static int getWidthPixels(IDatesMapper datesMapper,
LimitingResourceQueueElement queueElement) {
private static int getWidthPixels(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) {
return datesMapper.toPixels(queueElement.getLengthBetween());
}
private static int getDeadlinePixels(IDatesMapper datesMapper,
LocalDate deadlineDate) {
private static int getDeadlinePixels(IDatesMapper datesMapper, LocalDate deadlineDate) {
// Deadline date is considered inclusively
return datesMapper.toPixelsAbsolute(deadlineDate.plusDays(1)
.toDateMidnight().getMillis());
return datesMapper.toPixelsAbsolute(deadlineDate.plusDays(1).toDateTimeAtStartOfDay().getMillis());
}
private static String forCSS(int pixels) {
return String.format("%dpx", pixels);
}
private static int getStartPixels(IDatesMapper datesMapper,
LimitingResourceQueueElement queueElement) {
return datesMapper.toPixelsAbsolute((queueElement.getStartDate()
.toDateMidnight().getMillis() + queueElement.getStartHour()
* DatesMapperOnInterval.MILISECONDS_PER_HOUR));
private static int getStartPixels(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) {
return datesMapper.toPixelsAbsolute(
(queueElement.getStartDate().toDateTimeAtStartOfDay().getMillis()
+ queueElement.getStartHour() * DatesMapperOnInterval.MILISECONDS_PER_HOUR)
);
}
public void appendQueueElements(SortedSet<LimitingResourceQueueElement> elements) {
@ -435,17 +456,18 @@ public class QueueComponent extends XulElement implements
public void removeQueueElement(LimitingResourceQueueElement element) {
QueueTask queueTask = findQueueTaskByElement(element);
if (queueTask != null) {
if ( queueTask != null ) {
removeQueueTask(queueTask);
}
}
private QueueTask findQueueTaskByElement(LimitingResourceQueueElement element) {
for (QueueTask each: queueTasks) {
if (each.getLimitingResourceQueueElement().getId().equals(element.getId())) {
if ( each.getLimitingResourceQueueElement().getId().equals(element.getId()) ) {
return each;
}
}
return null;
}
@ -462,40 +484,37 @@ public class QueueComponent extends XulElement implements
return limitingResourceQueue.getResource().getName();
}
private static void validateQueueElement(
LimitingResourceQueueElement queueElement) {
if ((queueElement.getStartDate() == null)
|| (queueElement.getEndDate() == null)) {
private static void validateQueueElement(LimitingResourceQueueElement queueElement) {
if ( (queueElement.getStartDate() == null ) || ( queueElement.getEndDate() == null) ) {
throw new ValidationException(_("Invalid queue element"));
}
}
private void appendMenu(QueueTask divElement) {
if (divElement.getPage() != null) {
MenuBuilder<QueueTask> menuBuilder = MenuBuilder.on(divElement
.getPage(), divElement);
if ( divElement.getPage() != null ) {
MenuBuilder<QueueTask> menuBuilder = MenuBuilder.on(divElement.getPage(), divElement);
menuBuilder.item(_("Edit"), "/common/img/ico_editar.png",
new ItemAction<QueueTask>() {
menuBuilder.item(_("Edit"), "/common/img/ico_editar.png", new ItemAction<QueueTask>() {
@Override
public void onEvent(QueueTask choosen, Event event) {
editResourceAllocation(choosen);
}
});
menuBuilder.item(_("Unassign"), "/common/img/ico_borrar.png",
new ItemAction<QueueTask>() {
menuBuilder.item(_("Unassign"), "/common/img/ico_borrar.png", new ItemAction<QueueTask>() {
@Override
public void onEvent(QueueTask choosen, Event event) {
unnasign(choosen);
}
});
menuBuilder.item(_("Move"), "",
new ItemAction<QueueTask>() {
menuBuilder.item(_("Move"), "", new ItemAction<QueueTask>() {
@Override
public void onEvent(QueueTask choosen, Event event) {
moveQueueTask(choosen);
}
});
divElement.setContext(menuBuilder.createWithoutSettingContext());
}
}

View file

@ -192,7 +192,7 @@ public class AdvancedAllocationController extends GenericForwardComposer {
}
private static Date asDate(LocalDate start) {
return start.toDateMidnight().toDate();
return start.toDateTimeAtStartOfDay().toDate();
}
}

View file

@ -80,7 +80,7 @@ public class CompanyPlanningController implements Composer {
@Autowired
private ICompanyPlanningModel model;
private List<ICommandOnTask<TaskElement>> additional = new ArrayList<ICommandOnTask<TaskElement>>();
private List<ICommandOnTask<TaskElement>> additional = new ArrayList<>();
private Planner planner;
@ -108,46 +108,36 @@ public class CompanyPlanningController implements Composer {
public void doAfterCompose(org.zkoss.zk.ui.Component comp) {
planner = (Planner) comp;
String zoomLevelParameter = null;
if ((parameters != null) && (parameters.get("zoom") != null)
&& !(parameters.isEmpty())) {
if ( (parameters != null) && (parameters.get("zoom") != null)
&& !(parameters.isEmpty()) ) {
zoomLevelParameter = parameters.get("zoom")[0];
}
if (zoomLevelParameter != null) {
planner.setInitialZoomLevel(ZoomLevel
.getFromString(zoomLevelParameter));
if ( zoomLevelParameter != null ) {
planner.setInitialZoomLevel(ZoomLevel.getFromString(zoomLevelParameter));
}
planner.setAreContainersExpandedByDefault(Planner
.guessContainersExpandedByDefault(parameters));
planner.setAreContainersExpandedByDefault(Planner.guessContainersExpandedByDefault(parameters));
initializeListboxProgressTypes();
planner.setAreShownAdvancesByDefault(Planner
.guessShowAdvancesByDefault(parameters));
planner.setAreShownAdvancesByDefault(Planner.guessShowAdvancesByDefault(parameters));
planner.setAreShownReportedHoursByDefault(Planner
.guessShowReportedHoursByDefault(parameters));
planner.setAreShownMoneyCostBarByDefault(Planner
.guessShowMoneyCostBarByDefault(parameters));
planner.setAreShownReportedHoursByDefault(Planner.guessShowReportedHoursByDefault(parameters));
planner.setAreShownMoneyCostBarByDefault(Planner.guessShowMoneyCostBarByDefault(parameters));
orderFilter = (Vbox) planner.getFellow("orderFilter");
// Configuration of the order filter
Component filterComponent = Executions.createComponents(
"/orders/_orderFilter.zul", orderFilter,
new HashMap<String, String>());
Component filterComponent = Executions.createComponents("/orders/_orderFilter.zul", orderFilter,
new HashMap<String, String>());
filterComponent.setVariable("orderFilterController", this, true);
filterStartDate = (Datebox) filterComponent
.getFellow("filterStartDate");
filterFinishDate = (Datebox) filterComponent
.getFellow("filterFinishDate");
filterStartDate = (Datebox) filterComponent.getFellow("filterStartDate");
filterFinishDate = (Datebox) filterComponent.getFellow("filterFinishDate");
filterProjectName = (Textbox) filterComponent.getFellow("filterProjectName");
bdFilters = (BandboxMultipleSearch) filterComponent
.getFellow("bdFilters");
bdFilters = (BandboxMultipleSearch) filterComponent.getFellow("bdFilters");
bdFilters.setFinder("taskGroupsMultipleFiltersFinder");
loadPredefinedBandboxFilter();
checkIncludeOrderElements = (Checkbox) filterComponent
.getFellow("checkIncludeOrderElements");
checkIncludeOrderElements = (Checkbox) filterComponent.getFellow("checkIncludeOrderElements");
filterComponent.setVisible(true);
checkCreationPermissions();
@ -155,33 +145,30 @@ public class CompanyPlanningController implements Composer {
private void loadPredefinedBandboxFilter() {
User user = model.getUser();
List<FilterPair> sessionFilterPairs = FilterUtils
.readProjectsParameters();
if (sessionFilterPairs != null) {
List<FilterPair> sessionFilterPairs = FilterUtils.readProjectsParameters();
if ( sessionFilterPairs != null ) {
bdFilters.addSelectedElements(sessionFilterPairs);
} else if ((user != null) && (user.getProjectsFilterLabel() != null)) {
} else if ( (user != null) && (user.getProjectsFilterLabel() != null) ) {
bdFilters.clear();
bdFilters.addSelectedElement(new FilterPair(
TaskGroupFilterEnum.Label, user.getProjectsFilterLabel()
.getFinderPattern(), user
.getProjectsFilterLabel()));
bdFilters.addSelectedElement(new FilterPair(TaskGroupFilterEnum.Label, user.getProjectsFilterLabel()
.getFinderPattern(),
user.getProjectsFilterLabel()) );
}
// Calculate filter based on user preferences
if (user != null) {
if ((filterStartDate.getValue() == null)
&& !FilterUtils.hasProjectsStartDateChanged()
&& (user.getProjectsFilterPeriodSince() != null)) {
if ( (filterStartDate.getValue() == null) && !FilterUtils.hasProjectsStartDateChanged() &&
(user.getProjectsFilterPeriodSince() != null) ) {
filterStartDate.setValue(new LocalDate()
.minusMonths(user.getProjectsFilterPeriodSince())
.toDateTimeAtStartOfDay().toDate());
.toDateTimeAtStartOfDay()
.toDate());
}
if (filterFinishDate.getValue() == null
&& !FilterUtils.hasProjectsEndDateChanged()
&& (user.getProjectsFilterPeriodTo() != null)) {
filterFinishDate.setValue(new LocalDate()
.plusMonths(user.getProjectsFilterPeriodTo())
.toDateMidnight().toDate());
if ( filterFinishDate.getValue() == null && !FilterUtils.hasProjectsEndDateChanged() &&
(user.getProjectsFilterPeriodTo() != null) ) {
filterFinishDate.setValue(new LocalDate().plusMonths(user.getProjectsFilterPeriodTo())
.toDateTimeAtStartOfDay()
.toDate());
}
filterProjectName.setValue(FilterUtils.readProjectsName());
}
@ -193,21 +180,19 @@ public class CompanyPlanningController implements Composer {
* the create buttons accordingly.
*/
private void checkCreationPermissions() {
if (!SecurityUtils
.isSuperuserOrUserInRoles(UserRole.ROLE_CREATE_PROJECTS)) {
Button createOrderButton = (Button) planner.getPage().getFellow(
"createOrderButton");
if (createOrderButton != null) {
if ( !SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_CREATE_PROJECTS) ) {
Button createOrderButton = (Button) planner.getPage().getFellow("createOrderButton");
if ( createOrderButton != null ) {
createOrderButton.setDisabled(true);
}
}
}
private void initializeListboxProgressTypes() {
if (cbProgressTypes == null) {
if ( cbProgressTypes == null ) {
cbProgressTypes = (Combobox) planner.getFellow("cbProgressTypes");
}
if (btnShowAdvances == null) {
if ( btnShowAdvances == null ) {
btnShowAdvances = (Button) planner.getFellow("showAdvances");
}
@ -232,7 +217,7 @@ public class CompanyPlanningController implements Composer {
cbProgressTypes.setVisible(true);
ProgressType progressType = getProgressTypeFromConfiguration();
if (progressType != null) {
if ( progressType != null ) {
planner.updateCompletion(progressType.toString());
}
@ -247,8 +232,8 @@ public class CompanyPlanningController implements Composer {
item.setLabel(_(progressType.getValue()));
ProgressType configuredProgressType = getProgressTypeFromConfiguration();
if ((configuredProgressType != null)
&& configuredProgressType.equals(progressType)) {
if ( (configuredProgressType != null) &&
configuredProgressType.equals(progressType) ) {
cbProgressTypes.setSelectedItem(item);
}
}
@ -260,9 +245,7 @@ public class CompanyPlanningController implements Composer {
public void setConfigurationForPlanner() {
// Added predicate
model
.setConfigurationToPlanner(planner, additional,
doubleClickCommand, createPredicate());
model.setConfigurationToPlanner(planner, additional, doubleClickCommand, createPredicate());
model.setTabsController(tabsController);
planner.updateSelectedZoomLevel();
planner.invalidate();
@ -274,8 +257,7 @@ public class CompanyPlanningController implements Composer {
this.additional = additional;
}
public void setDoubleClickCommand(
ICommandOnTask<TaskElement> doubleClickCommand) {
public void setDoubleClickCommand(ICommandOnTask<TaskElement> doubleClickCommand) {
this.doubleClickCommand = doubleClickCommand;
}
@ -293,13 +275,10 @@ public class CompanyPlanningController implements Composer {
public void validate(Component comp, Object value)
throws WrongValueException {
Date finishDate = (Date) value;
if ((finishDate != null)
&& (filterStartDate.getRawValue() != null)
&& (finishDate.compareTo((Date)
filterStartDate.getRawValue()) < 0)) {
if ( (finishDate != null) && (filterStartDate.getRawValue() != null) &&
(finishDate.compareTo((Date) filterStartDate.getRawValue()) < 0)) {
filterFinishDate.setValue(null);
throw new WrongValueException(comp,
_("must be after start date"));
throw new WrongValueException(comp, _("must be after start date"));
}
}
};
@ -311,13 +290,10 @@ public class CompanyPlanningController implements Composer {
public void validate(Component comp, Object value)
throws WrongValueException {
Date startDate = (Date) value;
if ((startDate != null)
&& (filterFinishDate.getRawValue() != null)
&& (startDate.compareTo((Date)
filterFinishDate.getRawValue()) > 0)) {
if ( (startDate != null) && (filterFinishDate.getRawValue() != null) &&
(startDate.compareTo((Date) filterFinishDate.getRawValue()) > 0)) {
filterStartDate.setValue(null);
throw new WrongValueException(comp,
_("must be lower than end date"));
throw new WrongValueException(comp, _("must be lower than end date"));
}
}
};
@ -332,8 +308,9 @@ public class CompanyPlanningController implements Composer {
public void onApplyFilter() {
FilterUtils.writeProjectsFilter(filterStartDate.getValue(),
filterFinishDate.getValue(), bdFilters.getSelectedElements(),
filterProjectName.getValue());
filterFinishDate.getValue(),
bdFilters.getSelectedElements(),
filterProjectName.getValue());
FilterUtils.writeProjectPlanningFilterChanged(true);
filterByPredicate(createPredicate());
}
@ -343,8 +320,7 @@ public class CompanyPlanningController implements Composer {
}
private TaskGroupPredicate createPredicate() {
List<FilterPair> listFilters = (List<FilterPair>) bdFilters
.getSelectedElements();
List<FilterPair> listFilters = (List<FilterPair>) bdFilters.getSelectedElements();
Date startDate = filterStartDate.getValue();
Date finishDate = filterFinishDate.getValue();
Boolean includeOrderElements = checkIncludeOrderElements.isChecked();
@ -353,16 +329,13 @@ public class CompanyPlanningController implements Composer {
filterProjectName.setValue(name);
if (startDate == null && finishDate == null) {
TaskGroupPredicate predicate = model
.getDefaultPredicate(includeOrderElements);
if ( startDate == null && finishDate == null ) {
TaskGroupPredicate predicate = model.getDefaultPredicate(includeOrderElements);
//show filter dates calculated by default on screen
if (model.getFilterStartDate() != null
&& !FilterUtils.hasProjectsStartDateChanged()) {
if ( model.getFilterStartDate() != null && !FilterUtils.hasProjectsStartDateChanged()) {
filterStartDate.setValue(model.getFilterStartDate());
}
if (model.getFilterFinishDate() != null
&& !FilterUtils.hasProjectsEndDateChanged()) {
if (model.getFilterFinishDate() != null && !FilterUtils.hasProjectsEndDateChanged()) {
filterFinishDate.setValue(model.getFilterFinishDate());
}
@ -370,21 +343,18 @@ public class CompanyPlanningController implements Composer {
return predicate;
}
return new TaskGroupPredicate(listFilters, startDate, finishDate,
includeOrderElements, name);
return new TaskGroupPredicate(listFilters, startDate, finishDate, includeOrderElements, name);
}
private void filterByPredicate(TaskGroupPredicate predicate) {
// Recalculate predicate
model.setConfigurationToPlanner(planner, additional,
doubleClickCommand, predicate);
model.setConfigurationToPlanner(planner, additional, doubleClickCommand, predicate);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setPredicate() {
model.setConfigurationToPlanner(planner, additional,
doubleClickCommand, createPredicate());
model.setConfigurationToPlanner(planner, additional, doubleClickCommand, createPredicate());
}
public void setTabsController(MultipleTabsPlannerController tabsController) {

View file

@ -200,10 +200,9 @@ public class CompanyPlanningModel implements ICompanyPlanningModel {
@Override
@Transactional(readOnly = true)
public void setConfigurationToPlanner(final Planner planner,
Collection<ICommandOnTask<TaskElement>> additional,
ICommandOnTask<TaskElement> doubleClickCommand,
TaskGroupPredicate predicate) {
public void setConfigurationToPlanner(final Planner planner, Collection<ICommandOnTask<TaskElement>> additional,
ICommandOnTask<TaskElement> doubleClickCommand,
TaskGroupPredicate predicate) {
currentScenario = scenarioManager.getCurrent();
final PlannerConfiguration<TaskElement> configuration = createConfiguration(predicate);
@ -862,8 +861,7 @@ public class CompanyPlanningModel implements ICompanyPlanningModel {
}
@Override
public Date getFilterFinishDate() {
return ((filterStartDate == null) ? null : filterFinishDate
.toDateMidnight().toDate());
return ((filterStartDate == null) ? null : filterFinishDate.toDateTimeAtStartOfDay().toDate());
}
private AvailabilityTimeLine.Interval getFilterInterval() {

View file

@ -88,8 +88,7 @@ public class SubcontractModel implements ISubcontractModel {
if (subcontractedTaskData == null) {
this.subcontractedTaskData = SubcontractedTaskData.create(task);
if (task.getDeadline() != null) {
this.addDeliverDate(task.getDeadline().toDateMidnight()
.toDate());
this.addDeliverDate(task.getDeadline().toDateTimeAtStartOfDay().toDate());
} else {
this.addDeliverDate(task.getEndDate());
}

View file

@ -69,7 +69,7 @@ public abstract class LibrePlanReportController extends GenericForwardComposer {
jasperreport.setParameters(getParameters());
jasperreport.setType(type);
if (type.equals(HTML)) {
if ( type.equals(HTML) ) {
URItext.setStyle("display: none");
Executions.getCurrent().sendRedirect(jasperreport.getReportUrl(), "_blank");
} else {
@ -85,10 +85,12 @@ public abstract class LibrePlanReportController extends GenericForwardComposer {
}
protected Map<String, Object> getParameters() {
Map<String, Object> parameters = new HashMap<String, Object>();
Map<String, Object> parameters = new HashMap<>();
String companyLogo = Registry.getConfigurationDAO()
.getConfigurationWithReadOnlyTransaction().getCompanyLogoURL();
if (StringUtils.isBlank(companyLogo)) {
.getConfigurationWithReadOnlyTransaction()
.getCompanyLogoURL();
if ( StringUtils.isBlank(companyLogo) ) {
companyLogo = "/logos/logo.png";
}
parameters.put("logo", companyLogo);

View file

@ -189,7 +189,7 @@ public class ResourceLoadController implements Composer {
if (listenersToAdd != null) {
return listenersToAdd;
}
List<IListenerAdder> result = new ArrayList<IListenerAdder>();
List<IListenerAdder> result = new ArrayList<>();
for (VisualizationModifier each : getVisualizationModifiers()) {
if (each instanceof IListenerAdder) {
result.add((IListenerAdder) each);
@ -222,8 +222,7 @@ 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);
}
@ -236,9 +235,11 @@ public class ResourceLoadController implements Composer {
listeners.addListeners(resourcesLoadPanel, getListenersToAdd());
parent.getChildren().clear();
parent.appendChild(resourcesLoadPanel);
for (VisualizationModifier each : getVisualizationModifiers()) {
each.setup(resourcesLoadPanel);
}
} else {
resourcesLoadPanel.init(dataToShow.getLoadTimeLines(),
timeTracker);
@ -256,9 +257,9 @@ public class ResourceLoadController implements Composer {
private TimeTracker buildTimeTracker(ResourceLoadDisplayData dataToShow) {
ZoomLevel zoomLevel = getZoomLevel(dataToShow);
TimeTracker result = new TimeTracker(dataToShow.getViewInterval(),
zoomLevel, SeveralModificators.create(),
SeveralModificators.create(createBankHolidaysMarker()),
parent);
zoomLevel, SeveralModificators.create(),
SeveralModificators.create(createBankHolidaysMarker()),
parent);
setupZoomLevelListener(result);
return result;
}
@ -276,6 +277,7 @@ public class ResourceLoadController implements Composer {
if (sessionZoom != null) {
return sessionZoom;
}
return dataToShow.getInitialZoomLevel();
}
@ -310,58 +312,51 @@ public class ResourceLoadController implements Composer {
}
private List<VisualizationModifier> buildVisualizationModifiers() {
List<VisualizationModifier> result = new ArrayList<VisualizationModifier>();
FilterTypeChanger filterTypeChanger = new FilterTypeChanger(onChange,
filterBy);
List<VisualizationModifier> 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) {
LocalDate startDate = FilterUtils.readResourceLoadsStartDate();
LocalDate endDate = FilterUtils.readResourceLoadsEndDate();
if ( filterBy == null ) {
LocalDate startDate = FilterUtils.readResourceLoadsStartDate();
LocalDate endDate = FilterUtils.readResourceLoadsEndDate();
User user = resourceLoadModel.getUser();
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());
} else {
// Default filter start
startDate = new LocalDate().minusDays(1);
// Calculate filter based on user preferences
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<FilterPair> 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()));
}
}
result.add(new ByDatesFilter(onChange, filterBy, startDate, endDate));
WorkersOrCriteriaBandbox bandbox = new WorkersOrCriteriaBandbox(onChange, filterBy, filterTypeChanger,
resourcesSearcher, filterPairs);
List<FilterPair> filterPairs = (List<FilterPair>) FilterUtils
.readResourceLoadsBandbox();
if ((filterPairs == null || filterPairs.isEmpty())
&& user.getResourcesLoadFilterCriterion() != null) {
filterPairs = new ArrayList<FilterPair>();
filterPairs.add(new FilterPair(
ResourceAllocationFilterEnum.Criterion, user
.getResourcesLoadFilterCriterion()
.getFinderPattern(), user
.getResourcesLoadFilterCriterion()));
}
WorkersOrCriteriaBandbox bandbox = new WorkersOrCriteriaBandbox(
onChange, filterBy, filterTypeChanger, resourcesSearcher, filterPairs);
result.add(bandbox);
result.add(new ByNamePaginator(onChange, filterBy, filterTypeChanger,
bandbox));
result.add(bandbox);
result.add(new ByNamePaginator(onChange, filterBy, filterTypeChanger, bandbox));
}
result.add(new LoadChart(onChange, filterBy));
return result;
@ -369,7 +364,7 @@ public class ResourceLoadController implements Composer {
public interface IListenerAdder {
public Object addAndReturnListener(ResourcesLoadPanel panel);
Object addAndReturnListener(ResourcesLoadPanel panel);
}
private class GoToScheduleListener implements IListenerAdder {
@ -480,7 +475,7 @@ public class ResourceLoadController implements Composer {
@Override
public void filterChanged(boolean newValue) {
if (filterByResources != newValue) {
if ( filterByResources != newValue ) {
filterByResources = newValue;
notifyChange();
}
@ -501,19 +496,17 @@ 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();
: startDate.toDateTimeAtStartOfDay().toLocalDate();
endDateValue = (endDate == null) ? null : endDate.toDateTimeAtStartOfDay().toLocalDate();
}
@Override
void setup(ResourcesLoadPanel panel) {
if (isAppliedToOrder()) {
if ( isAppliedToOrder() ) {
return;
}
panel.setFirstOptionalFilter(buildTimeFilter());
@ -526,7 +519,7 @@ public class ResourceLoadController implements Composer {
@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();
@ -540,7 +533,7 @@ public class ResourceLoadController implements Composer {
@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();
@ -565,15 +558,13 @@ 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 +576,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 +597,16 @@ public class ResourceLoadController implements Composer {
private Label label = new Label();
private WorkersOrCriteriaBandbox(Runnable onChange,
PlanningState filterBy, FilterTypeChanger filterType,
IResourcesSearcher resourcesSearcher,
List<FilterPair> selectedFilters) {
PlanningState filterBy,
FilterTypeChanger filterType,
IResourcesSearcher resourcesSearcher,
List<FilterPair> 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,7 +616,7 @@ public class ResourceLoadController implements Composer {
@Override
void setup(ResourcesLoadPanel panel) {
if (isAppliedToOrder()) {
if ( isAppliedToOrder() ) {
return;
}
panel.setSecondOptionalFilter(buildBandboxFilterer());
@ -663,7 +655,7 @@ public class ResourceLoadController implements Composer {
}
private void updateLabelValue() {
if (isFilteringByResource()) {
if ( isFilteringByResource() ) {
label.setValue(_("Resources or criteria") + ":");
} else {
label.setValue(_("Criteria") + ":");
@ -671,7 +663,7 @@ public class ResourceLoadController implements Composer {
}
private String getFinderToUse() {
if (isFilteringByResource()) {
if ( isFilteringByResource() ) {
return "resourceMultipleFiltersFinderByResourceAndCriterion";
} else {
return "criterionMultipleFiltersFinder";
@ -680,7 +672,7 @@ public class ResourceLoadController implements Composer {
@Override
protected void filterTypeChanged() {
if (isAppliedToOrder()) {
if ( isAppliedToOrder() ) {
return;
}
entitiesSelected = null;
@ -690,32 +682,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<Resource> calculateResourcesToShow() {
List<Resource> resources = new ArrayList<Resource>();
List<Criterion> criteria = new ArrayList<Criterion>();
List<Resource> resources = new ArrayList<>();
List<Criterion> 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 +716,19 @@ public class ResourceLoadController implements Composer {
}
private List<Object> getSelected() {
List<Object> result = new ArrayList<Object>();
List<Object> result = new ArrayList<>();
@SuppressWarnings("unchecked")
List<FilterPair> 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 +738,10 @@ public class ResourceLoadController implements Composer {
private List<? extends BaseEntity> 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();
@ -778,7 +769,7 @@ public class ResourceLoadController implements Composer {
@Override
void checkDependencies() {
super.checkDependencies();
if (bandbox.hasEntitiesSelected()) {
if ( bandbox.hasEntitiesSelected() ) {
this.currentPosition = ALL;
}
}
@ -797,40 +788,38 @@ public class ResourceLoadController implements Composer {
@Override
void updateUI(ResourcesLoadPanel panel, ResourceLoadDisplayData generatedData) {
panel.setInternalPaginationDisabled(bandbox.hasEntitiesSelected());
Paginator<? extends BaseEntity> paginator = generatedData
.getPaginator();
Paginator<? extends BaseEntity> paginator = generatedData.getPaginator();
List<? extends BaseEntity> 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()));
pagesByName(this.allEntitiesShown,
paginator.getPageSize()));
}
}
private boolean equivalent(List<? extends BaseEntity> a,
List<? extends BaseEntity> b) {
if (a == null || b == null) {
private boolean equivalent(List<? extends BaseEntity> a, List<? extends BaseEntity> 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<Comboitem> pages) {
if (filterByNameCombo == null) {
private void updatePages(Combobox filterByNameCombo, List<Comboitem> pages) {
if ( filterByNameCombo == null ) {
return;
}
filterByNameCombo.getChildren().clear();
@ -845,10 +834,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,11 +844,11 @@ public class ResourceLoadController implements Composer {
}
private List<Comboitem> pagesByName(List<?> list, int pageSize) {
if (list.isEmpty()) {
return new ArrayList<Comboitem>();
if ( list.isEmpty() ) {
return new ArrayList<>();
}
Object first = list.get(0);
if (first instanceof Resource) {
if ( first instanceof Resource ) {
return pagesByName(as(Resource.class, list), pageSize,
new INameExtractor<Resource>() {
@ -883,40 +871,41 @@ public class ResourceLoadController implements Composer {
}
interface INameExtractor<T> {
public String getNameOf(T value);
String getNameOf(T value);
}
private <T> List<Comboitem> pagesByName(List<T> elements,
int pageSize,
INameExtractor<T> nameExtractor) {
List<Comboitem> result = new ArrayList<Comboitem>();
private <T> List<Comboitem> pagesByName(List<T> elements, int pageSize, INameExtractor<T> nameExtractor) {
List<Comboitem> 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;
}
}
private static <T> List<T> as(Class<T> klass, Collection<?> entities) {
List<T> result = new ArrayList<T>(entities.size());
List<T> result = new ArrayList<>(entities.size());
for (Object each : entities) {
result.add(klass.cast(each));
}
return result;
}
@ -947,7 +936,7 @@ public class ResourceLoadController implements Composer {
@Override
public void chartVisibilityChanged(final boolean visible) {
if (visible && loadChart != null) {
if ( visible && loadChart != null ) {
loadChart.fillChart();
}
}
@ -955,8 +944,7 @@ public class ResourceLoadController implements Composer {
return result;
}
private Tabbox buildChart(ResourcesLoadPanel resourcesLoadPanel,
Emitter<Timeplot> timePlot) {
private Tabbox buildChart(ResourcesLoadPanel resourcesLoadPanel, Emitter<Timeplot> timePlot) {
Tabbox chartComponent = new Tabbox();
chartComponent.setOrient("vertical");
chartComponent.setHeight("200px");
@ -973,50 +961,49 @@ public class ResourceLoadController implements Composer {
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) {
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) {
private IZoomLevelChangedListener fillOnZoomChange(final ResourcesLoadPanel resourcesLoadPanel) {
IZoomLevelChangedListener zoomListener = 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);
@ -1054,10 +1041,9 @@ public class ResourceLoadController implements Composer {
@Override
protected ILoadChartData getDataOn(Interval interval) {
List<DayAssignment> assignments = generatedData
.getDayAssignmentsConsidered();
return new ResourceLoadChartData(assignments,
resources, interval.getStart(), interval.getFinish());
List<DayAssignment> assignments = generatedData.getDayAssignmentsConsidered();
return new ResourceLoadChartData(assignments, resources, interval.getStart(), interval.getFinish());
}
private void initializeResources() {
@ -1068,10 +1054,9 @@ public class ResourceLoadController implements Composer {
}
private static class ListenerTracker {
private final List<Object> trackedListeners = new ArrayList<Object>();
private final List<Object> trackedListeners = new ArrayList<>();
public void addListeners(ResourcesLoadPanel panel,
Iterable<IListenerAdder> listeners) {
public void addListeners(ResourcesLoadPanel panel, Iterable<IListenerAdder> listeners) {
for (IListenerAdder each : listeners) {
Object listener = each.addAndReturnListener(panel);
trackedListeners.add(listener);
@ -1080,13 +1065,11 @@ 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);
}
@ -1106,8 +1089,7 @@ public class ResourceLoadController implements Composer {
});
}
public void setPlanningControllerEntryPoints(
IOrderPlanningGate planningControllerEntryPoints) {
public void setPlanningControllerEntryPoints(IOrderPlanningGate planningControllerEntryPoints) {
this.planningControllerEntryPoints = planningControllerEntryPoints;
}

View file

@ -370,13 +370,13 @@
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>2.4</version>
<version>3.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
<version>2.4</version>
<version>3.2</version>
<scope>test</scope>
</dependency>
@ -390,9 +390,10 @@
<!-- Commons collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
<version>3.2.2</version>
</dependency>
<!-- Commons lang -->