diff --git a/ganttzk/src/main/java/org/zkoss/ganttz/adapters/DomainDependency.java b/ganttzk/src/main/java/org/zkoss/ganttz/adapters/DomainDependency.java index ea14c47b5..2f7b35af7 100644 --- a/ganttzk/src/main/java/org/zkoss/ganttz/adapters/DomainDependency.java +++ b/ganttzk/src/main/java/org/zkoss/ganttz/adapters/DomainDependency.java @@ -33,12 +33,26 @@ import org.zkoss.ganttz.data.IDependency; /** * Represents a dependency in the domain. + * * @author Óscar González Fernández */ public class DomainDependency implements IDependency { private static final Log LOG = LogFactory.getLog(DomainDependency.class); + private final T source; + + private final T destination; + + private final DependencyType type; + + private DomainDependency(T source, T destination, DependencyType type) { + super(); + this.source = source; + this.destination = destination; + this.type = type; + } + public static List toDependencies( IDomainAndBeansMapper mapper, Collection> dependencies) { @@ -55,20 +69,7 @@ public class DomainDependency implements IDependency { } public static DomainDependency createDependency(T source, T destination, DependencyType type) { - return new DomainDependency(source, destination, type); - } - - private final T source; - - private final T destination; - - private final DependencyType type; - - private DomainDependency(T source, T destination, DependencyType type) { - super(); - this.source = source; - this.destination = destination; - this.type = type; + return new DomainDependency<>(source, destination, type); } public T getSource() { diff --git a/libreplan-business/pom.xml b/libreplan-business/pom.xml index 552d89864..2f5cbe09b 100644 --- a/libreplan-business/pom.xml +++ b/libreplan-business/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 @@ -79,7 +80,7 @@ junit - + com.jolbox bonecp @@ -115,6 +116,11 @@ commons-lang3 + + org.apache.commons + commons-collections4 + + org.slf4j @@ -127,12 +133,6 @@ joda-time - - - org.dbunit - dbunit - - org.liquibase diff --git a/libreplan-business/src/main/java/org/libreplan/business/BootstrapOrder.java b/libreplan-business/src/main/java/org/libreplan/business/BootstrapOrder.java index 74e3f3aa9..64c16df9a 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/BootstrapOrder.java +++ b/libreplan-business/src/main/java/org/libreplan/business/BootstrapOrder.java @@ -29,11 +29,10 @@ import java.lang.annotation.Target; /** *

- * It can be applied to a {@link IDataBootstrap} to indicate the order in which it will be executed. - * It's ensured that if a data bootstrap has a priority value greater than another one it will be executed before. - * - * If two data bootstraps have the same priority value the order is unspecified. - * If a data bootstrap doesn't have this annotation it's like it would have a value of zero. + * It can be applied to a {@link IDataBootstrap} to indicate the order in which it will be executed. + * It's ensured that if a data bootstrap has a priority value greater than another one it will be executed before. + * If two data bootstraps have the same priority value the order is unspecified. + * If a data bootstrap doesn't have this annotation it's like it would have a value of zero. *

* * It accepts negative values. diff --git a/libreplan-business/src/main/java/org/libreplan/business/advance/bootstrap/DefaultAdvanceTypesBootstrapListener.java b/libreplan-business/src/main/java/org/libreplan/business/advance/bootstrap/DefaultAdvanceTypesBootstrapListener.java index ce26ddfc9..c674b8955 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/advance/bootstrap/DefaultAdvanceTypesBootstrapListener.java +++ b/libreplan-business/src/main/java/org/libreplan/business/advance/bootstrap/DefaultAdvanceTypesBootstrapListener.java @@ -24,12 +24,13 @@ package org.libreplan.business.advance.bootstrap; import org.libreplan.business.IDataBootstrap; import org.libreplan.business.advance.daos.IAdvanceTypeDAO; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class DefaultAdvanceTypesBootstrapListener implements IDataBootstrap { @Autowired diff --git a/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceType.java b/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceType.java index 269958e8f..39f573eaa 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceType.java +++ b/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceType.java @@ -91,7 +91,7 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{ private Boolean qualityForm = false; - private IAdvanceTypeDAO avancedTypeDAO = Registry.getAdvanceTypeDao(); + private IAdvanceTypeDAO advanceTypeDAO = Registry.getAdvanceTypeDao(); private boolean readOnly = false; @@ -255,7 +255,7 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{ } if ( isNewObject() ) { - return !avancedTypeDAO.existsByNameInAnotherTransaction(unitName); + return !advanceTypeDAO.existsByNameInAnotherTransaction(unitName); } else { return checkNotExistsOrIsTheSame(); } @@ -263,7 +263,7 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{ private boolean checkNotExistsOrIsTheSame() { try { - AdvanceType advanceType = avancedTypeDAO.findUniqueByNameInAnotherTransaction(unitName); + AdvanceType advanceType = advanceTypeDAO.findUniqueByNameInAnotherTransaction(unitName); return advanceType.getId().equals(getId()); } catch (InstanceNotFoundException e) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/advance/entities/DirectAdvanceAssignment.java b/libreplan-business/src/main/java/org/libreplan/business/advance/entities/DirectAdvanceAssignment.java index 41eb4cd44..4fb81869f 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/advance/entities/DirectAdvanceAssignment.java +++ b/libreplan-business/src/main/java/org/libreplan/business/advance/entities/DirectAdvanceAssignment.java @@ -38,8 +38,7 @@ import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.planner.entities.consolidations.NonCalculatedConsolidation; /** - * Represents an {@link AdvanceAssignment} that is own of this - * {@link OrderElement}. + * Represents an {@link AdvanceAssignment} that is own of this {@link OrderElement}. * * @author Manuel Rego Casasnovas */ @@ -52,7 +51,7 @@ public class DirectAdvanceAssignment extends AdvanceAssignment { } public static DirectAdvanceAssignment create(boolean reportGlobalAdvance, - BigDecimal maxValue) { + BigDecimal maxValue) { DirectAdvanceAssignment advanceAssignment = new DirectAdvanceAssignment( reportGlobalAdvance, maxValue); advanceAssignment.setNewObject(true); @@ -62,8 +61,7 @@ public class DirectAdvanceAssignment extends AdvanceAssignment { private BigDecimal maxValue; @Valid - private SortedSet advanceMeasurements = new TreeSet( - new AdvanceMeasurementComparator()); + private SortedSet advanceMeasurements = new TreeSet<>(new AdvanceMeasurementComparator()); @Valid private Set nonCalculatedConsolidations = new HashSet(); @@ -75,7 +73,7 @@ public class DirectAdvanceAssignment extends AdvanceAssignment { } private DirectAdvanceAssignment(boolean reportGlobalAdvance, - BigDecimal maxValue) { + BigDecimal maxValue) { super(reportGlobalAdvance); this.maxValue = maxValue; this.maxValue.setScale(2, BigDecimal.ROUND_HALF_UP); @@ -207,7 +205,7 @@ public class DirectAdvanceAssignment extends AdvanceAssignment { && (currentAdvance.getDate() != null) && (nextAdvance.getDate() != null) && (currentAdvance.getValue().compareTo( - nextAdvance.getValue()) < 0)) { + nextAdvance.getValue()) < 0)) { return false; } currentAdvance = nextAdvance; diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/BaseCalendar.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/BaseCalendar.java index 5f78cbbe5..6857c5a83 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/BaseCalendar.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/BaseCalendar.java @@ -50,16 +50,40 @@ import org.libreplan.business.workingday.IntraDayDate.PartialDay; import org.libreplan.business.workingday.ResourcesPerDay; /** - * Represents a calendar with some exception days. A calendar is valid till the - * expiring date, when the next calendar starts to be valid. On the other hand, - * a calendar could be derived, and the derived calendar could add or overwrite - * some exceptions of its parent calendar. + * Represents a calendar with some exception days. + * A calendar is valid till the expiring date, when the next calendar starts to be valid. + * On the other hand, a calendar could be derived, and + * the derived calendar could add or overwrite some exceptions of its parent calendar. + * * @author Manuel Rego Casasnovas */ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHumanIdentifiable, Comparable { private static final Capacity DEFAULT_VALUE = Capacity.zero().overAssignableWithoutLimit(); + private String name; + + @Valid + private Set exceptions = new HashSet<>(); + + @Valid + private List calendarDataVersions = new ArrayList<>(); + + @Valid + private List calendarAvailabilities = new ArrayList<>(); + + private Integer lastSequenceCode = 0; + + /** + * Constructor for hibernate. Do not use! + */ + public BaseCalendar() {} + + protected BaseCalendar(CalendarData calendarData) { + calendarDataVersions.add(calendarData); + Collections.sort(calendarDataVersions, CalendarData.BY_EXPIRING_DATE_COMPARATOR); + } + public static BaseCalendar create() { return create(new BaseCalendar(CalendarData.create())); } @@ -71,12 +95,14 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman public static BaseCalendar createBasicCalendar() { BaseCalendar calendar = create(); resetDefaultCapacities(calendar); + return calendar; } public static BaseCalendar createBasicCalendar(String code) { BaseCalendar calendar = create(code); resetDefaultCapacities(calendar); + return calendar; } @@ -87,13 +113,13 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } } - public static BaseCalendar createUnvalidated(String code, String name, - BaseCalendar parent, Set exceptions, - List calendarDataVersions) - throws IllegalArgumentException { + public static BaseCalendar createUnvalidated(String code, + String name, + BaseCalendar parent, + Set exceptions, + List calendarDataVersions) { - BaseCalendar baseCalendar = create(new BaseCalendar(CalendarData - .create()), code); + BaseCalendar baseCalendar = create(new BaseCalendar(CalendarData.create()), code); baseCalendar.name = name; if ((exceptions != null) && (!exceptions.isEmpty())) { @@ -126,31 +152,6 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } - private String name; - - @Valid - private Set exceptions = new HashSet(); - - @Valid - private List calendarDataVersions = new ArrayList(); - - @Valid - private List calendarAvailabilities = new ArrayList(); - - private Integer lastSequenceCode = 0; - - /** - * Constructor for hibernate. Do not use! - */ - public BaseCalendar() { - } - - protected BaseCalendar(CalendarData calendarData) { - calendarDataVersions.add(calendarData); - Collections.sort(calendarDataVersions, - CalendarData.BY_EXPIRING_DATE_COMPARATOR); - } - public void setName(String name) { this.name = name; } @@ -177,11 +178,11 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } public boolean isDerived() { - return (getParent() != null); + return getParent() != null; } public boolean isDerived(LocalDate date) { - return (getParent(date) != null); + return getParent(date) != null; } public Set getOwnExceptions() { @@ -189,7 +190,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } public Set getExceptions() { - Set exceptionDays = new HashSet(); + Set exceptionDays = new HashSet<>(); exceptionDays.addAll(exceptions); if (getParent() != null) { @@ -204,7 +205,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } public Set getExceptions(LocalDate date) { - Set exceptionDays = new HashSet(); + Set exceptionDays = new HashSet<>(); exceptionDays.addAll(exceptions); if (getParent(date) != null) { @@ -219,8 +220,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman return Collections.unmodifiableSet(exceptionDays); } - private boolean isExceptionDayAlreadyInExceptions( - CalendarException exceptionDay) { + private boolean isExceptionDayAlreadyInExceptions(CalendarException exceptionDay) { for (CalendarException day : exceptions) { if (day.getDate().equals(exceptionDay.getDate())) { return true; @@ -230,13 +230,13 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman return false; } - public void addExceptionDay(CalendarException day) - throws IllegalArgumentException { + public void addExceptionDay(CalendarException day) { if (day.getDate() == null) { throw new IllegalArgumentException( "This exception day has a incorrect date"); } + if (isExceptionDayAlreadyInExceptions(day)) { throw new IllegalArgumentException( "This day is already in the exception days"); @@ -245,9 +245,9 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman exceptions.add(day); } - public void removeExceptionDay(LocalDate date) - throws IllegalArgumentException { + public void removeExceptionDay(LocalDate date) { CalendarException day = getOwnExceptionDay(date); + if (day == null) { throw new IllegalArgumentException( "There is not an exception day on that date"); @@ -256,11 +256,9 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman exceptions.remove(day); } - public void updateExceptionDay(LocalDate date, Capacity capacity, - CalendarExceptionType type) throws IllegalArgumentException { + public void updateExceptionDay(LocalDate date, Capacity capacity, CalendarExceptionType type) { removeExceptionDay(date); - CalendarException day = CalendarException.create("", date, capacity, - type); + CalendarException day = CalendarException.create("", date, capacity, type); addExceptionDay(day); } @@ -284,14 +282,15 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman return null; } + @Override public EffortDuration getCapacityOn(PartialDay date) { - return date.limitWorkingDay(getCapacityWithOvertime(date.getDate()) - .getStandardEffort()); + return date.limitWorkingDay(getCapacityWithOvertime(date.getDate()).getStandardEffort()); } @Override public Capacity getCapacityWithOvertime(LocalDate day) { Validate.notNull(day); + return multiplyByCalendarUnits(findCapacityAt(day)); } @@ -299,10 +298,12 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (!isActive(date)) { return Capacity.zero(); } + CalendarException exceptionDay = getExceptionDay(date); if (exceptionDay != null) { return exceptionDay.getCapacity(); } + return getCapacityConsideringCalendarDatasOn(date, getDayFrom(date)); } @@ -315,9 +316,11 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman Capacity capacity = calendarData.getCapacityOn(day); BaseCalendar parent = getParent(date); + if (capacity == null && parent != null) { return parent.getCapacityConsideringCalendarDatasOn(date, day); } + return valueIfNotNullElseDefaultValue(capacity); } @@ -325,12 +328,17 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (capacity == null) { return DEFAULT_VALUE; } + return capacity; } /** * Returns the number of workable hours for a specific period depending on * the calendar restrictions. + * + * @param init + * @param end + * @return Workable hours */ public Integer getWorkableHours(LocalDate init, LocalDate end) { return getWorkableDuration(init, end).roundToHours(); @@ -339,12 +347,14 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman /** * Returns the workable duration for a specific period depending on the * calendar restrictions. + * + * @param init + * @param endInclusive + * @return Duration of work */ - public EffortDuration getWorkableDuration(LocalDate init, - LocalDate endInclusive) { + public EffortDuration getWorkableDuration(LocalDate init, LocalDate endInclusive) { Iterable daysBetween = IntraDayDate.startOfDay(init) - .daysUntil( - IntraDayDate.startOfDay(endInclusive).nextDayAtStart()); + .daysUntil(IntraDayDate.startOfDay(endInclusive).nextDayAtStart()); return EffortDuration.sum(daysBetween, new IEffortFrom() { @@ -359,6 +369,9 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman /** * Returns the number of workable hours for a specific week depending on the * calendar restrictions. + * + * @param date + * @return Workable hours per week */ public Integer getWorkableHoursPerWeek(LocalDate date) { LocalDate init = date.dayOfWeek().withMinimumValue(); @@ -375,12 +388,14 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman public BaseCalendar newDerivedCalendar() { BaseCalendar derivedCalendar = create(); derivedCalendar.setParent(this); + return derivedCalendar; } public ResourceCalendar newDerivedResourceCalendar() { ResourceCalendar derivedCalendar = ResourceCalendar.create(); derivedCalendar.setParent(this); + return derivedCalendar; } @@ -388,40 +403,37 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman * Creates a new version this {@link BaseCalendar} from the specific date. * It makes that the current calendar expires in the specific date. And the * new calendar will be used from that date onwards. + * + * @param date */ - public void newVersion(LocalDate date) throws IllegalArgumentException { + public void newVersion(LocalDate date) { BaseCalendar lastParent = null; + if (getLastCalendarData() != null) { lastParent = getLastCalendarData().getParent(); } + CalendarData newCalendarData = createLastVersion(date); newCalendarData.setParent(lastParent); } - public CalendarData createNewVersionInsideIntersection(LocalDate startDate, - LocalDate expiringDate) { + public CalendarData createNewVersionInsideIntersection(LocalDate startDate, LocalDate expiringDate) { for (CalendarData nextVersion : calendarDataVersions) { - if ((nextVersion.getExpiringDate() == null) - || (expiringDate.compareTo(nextVersion.getExpiringDate()) <= 0)) { + if ((nextVersion.getExpiringDate() == null) || + (expiringDate.compareTo(nextVersion.getExpiringDate()) <= 0)) { int index = calendarDataVersions.indexOf(nextVersion); if (index > 0) { - CalendarData prevVersion = calendarDataVersions - .get(index - 1); - if (newIntervalIncludeAnotherWorkWeek(startDate, - expiringDate, prevVersion, nextVersion)) { + CalendarData prevVersion = calendarDataVersions.get(index - 1); + if (newIntervalIncludeAnotherWorkWeek(startDate, expiringDate, prevVersion, nextVersion)) { throw new IllegalArgumentException( "the new work week includes a whole work week already exists"); } else { - LocalDate prevExpiringDate = prevVersion - .getExpiringDate(); - LocalDate nextExpiringDate = nextVersion - .getExpiringDate(); + LocalDate prevExpiringDate = prevVersion.getExpiringDate(); + LocalDate nextExpiringDate = nextVersion.getExpiringDate(); BaseCalendar oldParent = nextVersion.getParent(); - if ((prevExpiringDate == null) - || (startDate.compareTo(prevExpiringDate) > 0)) { - CalendarData prevCalendarData = CalendarData - .create(); + if ((prevExpiringDate == null) || (startDate.compareTo(prevExpiringDate) > 0)) { + CalendarData prevCalendarData = CalendarData.create(); prevCalendarData.setExpiringDate(startDate); prevCalendarData.setParent(oldParent); resetDefaultCapacities(prevCalendarData); @@ -434,13 +446,12 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman newCalendarData.setExpiringDate(expiringDate); calendarDataVersions.add(newCalendarData); - if ((nextExpiringDate != null) - && (expiringDate.compareTo(nextExpiringDate) >= 0)) { + if ((nextExpiringDate != null) && (expiringDate.compareTo(nextExpiringDate) >= 0)) { calendarDataVersions.remove(nextVersion); } - Collections.sort(calendarDataVersions, - CalendarData.BY_EXPIRING_DATE_COMPARATOR); + Collections.sort(calendarDataVersions, CalendarData.BY_EXPIRING_DATE_COMPARATOR); + return newCalendarData; } } else { @@ -454,29 +465,30 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } public boolean newIntervalIncludeAnotherWorkWeek(LocalDate startDate, - LocalDate expiringDate, CalendarData prevVersion, - CalendarData nextVersion) { - if ((startDate.compareTo(prevVersion.getExpiringDate()) <= 0) - && (nextVersion.getExpiringDate() != null) - && (expiringDate.compareTo(nextVersion.getExpiringDate()) >= 0)) { + LocalDate expiringDate, + CalendarData prevVersion, + CalendarData nextVersion) { + + if ((startDate.compareTo(prevVersion.getExpiringDate()) <= 0) && + (nextVersion.getExpiringDate() != null) && + (expiringDate.compareTo(nextVersion.getExpiringDate()) >= 0)) { return true; } int indexPrevOfPrev = calendarDataVersions.indexOf(prevVersion); + if (indexPrevOfPrev > 0) { - CalendarData prevOfPrev = (CalendarData) calendarDataVersions - .get(indexPrevOfPrev - 1); + CalendarData prevOfPrev = calendarDataVersions.get(indexPrevOfPrev - 1); if (startDate.compareTo(prevOfPrev.getExpiringDate()) <= 0) { return true; } } + return false; } - public CalendarData createLastVersion(LocalDate startDate) - throws IllegalArgumentException { + public CalendarData createLastVersion(LocalDate startDate) { CalendarData calendarData = getCalendarDataBeforeTheLastIfAny(); - if ((calendarData.getExpiringDate() != null) - && (startDate.compareTo(calendarData.getExpiringDate()) <= 0)) { + if ((calendarData.getExpiringDate() != null) && (startDate.compareTo(calendarData.getExpiringDate()) <= 0)) { throw new IllegalArgumentException( "Wrong start date : the new work week includes a whole work week already exists"); } @@ -485,16 +497,14 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman CalendarData newCalendarData = CalendarData.create(); calendarDataVersions.add(newCalendarData); - Collections.sort(calendarDataVersions, - CalendarData.BY_EXPIRING_DATE_COMPARATOR); + Collections.sort(calendarDataVersions, CalendarData.BY_EXPIRING_DATE_COMPARATOR); + return newCalendarData; } - public CalendarData createFirstVersion(LocalDate expiringDate) - throws IllegalArgumentException { + public CalendarData createFirstVersion(LocalDate expiringDate) { CalendarData firstVersion = getFirstCalendarData(); - if ((firstVersion.getExpiringDate() != null) - && (expiringDate.compareTo(firstVersion.getExpiringDate()) >= 0)) { + if ((firstVersion.getExpiringDate() != null) && (expiringDate.compareTo(firstVersion.getExpiringDate()) >= 0)) { throw new IllegalArgumentException( "Wrong expiring date : Work week expiring date must be lower than expiring date for " @@ -504,13 +514,12 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman CalendarData newCalendarData = CalendarData.create(); newCalendarData.setExpiringDate(expiringDate); calendarDataVersions.add(newCalendarData); - Collections.sort(calendarDataVersions, - CalendarData.BY_EXPIRING_DATE_COMPARATOR); + Collections.sort(calendarDataVersions, CalendarData.BY_EXPIRING_DATE_COMPARATOR); + return newCalendarData; } - public void newVersion(LocalDate startDate, LocalDate expiringDate, - BaseCalendar parent) throws IllegalArgumentException { + public void newVersion(LocalDate startDate, LocalDate expiringDate, BaseCalendar parent) { CalendarData newCalendarData; if (startDate != null && expiringDate != null) { @@ -518,6 +527,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman throw new IllegalArgumentException( "the start date must be lower than expiring date"); } + if (calendarDataVersions.size() == 1) { BaseCalendar lastParent = getLastCalendarData().getParent(); newCalendarData = createLastVersion(startDate); @@ -525,16 +535,15 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman newLastVersion.setParent(lastParent); resetDefaultCapacities(newLastVersion); } else { - newCalendarData = createNewVersionInsideIntersection(startDate, - expiringDate); + newCalendarData = createNewVersionInsideIntersection(startDate, expiringDate); } + } else if (startDate != null) { newCalendarData = createLastVersion(startDate); } else if (expiringDate != null) { newCalendarData = createFirstVersion(expiringDate); } else { - throw new IllegalArgumentException( - "At least the start date must be specified"); + throw new IllegalArgumentException("At least the start date must be specified"); } if (parent != null) { @@ -555,13 +564,12 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman public void addNewVersion(CalendarData version){ if (version.getExpiringDate() == null) { if (getLastCalendarData().getExpiringDate() == null) { - throw new IllegalArgumentException( - "the date is null and overlaps with the last work week."); + throw new IllegalArgumentException("the date is null and overlaps with the last work week."); } else{ calendarDataVersions.add(version); - Collections.sort(calendarDataVersions, - CalendarData.BY_EXPIRING_DATE_COMPARATOR); + Collections.sort(calendarDataVersions, CalendarData.BY_EXPIRING_DATE_COMPARATOR); + return; } } @@ -572,24 +580,21 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman "You can not add a work week with previous date than current date"); } for (int i = 0; i < calendarDataVersions.size(); i++) { - if ((calendarDataVersions.get(i).getExpiringDate() == null) - || (calendarDataVersions.get(i).getExpiringDate() - .compareTo(version.getExpiringDate()) > 0)) { - if ((i - 1 >= 0) - && (calendarDataVersions.get(i - 1).getExpiringDate() != null) - && (calendarDataVersions.get(i - 1).getExpiringDate() - .compareTo(version.getExpiringDate()) >= 0)) { - throw new IllegalArgumentException( - "the date is null and overlap with the other work week."); + if ((calendarDataVersions.get(i).getExpiringDate() == null) || + (calendarDataVersions.get(i).getExpiringDate().compareTo(version.getExpiringDate()) > 0)) { + if ((i - 1 >= 0) && + (calendarDataVersions.get(i - 1).getExpiringDate() != null) && + (calendarDataVersions.get(i - 1).getExpiringDate().compareTo(version.getExpiringDate()) >= 0)) { + throw new IllegalArgumentException("the date is null and overlap with the other work week."); } calendarDataVersions.add(i, version); + return; } } calendarDataVersions.add(version); - Collections.sort(calendarDataVersions, - CalendarData.BY_EXPIRING_DATE_COMPARATOR); + Collections.sort(calendarDataVersions, CalendarData.BY_EXPIRING_DATE_COMPARATOR); } @@ -602,16 +607,19 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman private void copyFields(BaseCalendar copy) { copy.name = this.name; copy.setCodeAutogenerated(this.isCodeAutogenerated()); - copy.calendarDataVersions = new ArrayList(); + copy.calendarDataVersions = new ArrayList<>(); + for (CalendarData calendarData : this.calendarDataVersions) { copy.calendarDataVersions.add(calendarData.copy()); } - copy.exceptions = new HashSet(this.exceptions); + + copy.exceptions = new HashSet<>(this.exceptions); } public BaseCalendar newCopyResourceCalendar() { BaseCalendar copy = ResourceCalendar.create(); copyFields(copy); + return copy; } @@ -644,6 +652,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (calendarDataVersions.isEmpty()) { return null; } + return calendarDataVersions.get(0); } @@ -666,11 +675,13 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman public boolean isDefault(Days day) { CalendarData calendarData = getLastCalendarData(); + return calendarData.isDefault(day); } public boolean isDefault(Days day, LocalDate date) { CalendarData calendarData = getCalendarData(date); + return calendarData.isDefault(day); } @@ -696,14 +707,12 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman setExpiringDate(expiringDate, new LocalDate()); } - public void setExpiringDate(LocalDate expiringDate, LocalDate date) - throws IllegalArgumentException { + public void setExpiringDate(LocalDate expiringDate, LocalDate date) { CalendarData calendarData = getCalendarData(date); setExpiringDate(calendarData, expiringDate); } - private void setExpiringDate(CalendarData calendarData, - LocalDate expiringDate) throws IllegalArgumentException { + private void setExpiringDate(CalendarData calendarData, LocalDate expiringDate) { if (calendarData.getExpiringDate() == null) { throw new IllegalArgumentException("Can not set the expiring date " + "because of this is the last work week"); @@ -711,8 +720,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman Integer index = calendarDataVersions.indexOf(calendarData); if (index > 0) { - CalendarData preivousCalendarData = calendarDataVersions - .get(index - 1); + CalendarData preivousCalendarData = calendarDataVersions.get(index - 1); if (expiringDate.compareTo(preivousCalendarData.getExpiringDate()) <= 0) { throw new IllegalArgumentException( "This date must be greater than expiring date of previous calendars"); @@ -724,59 +732,73 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman private CalendarData getPreviousCalendarData(LocalDate date) { CalendarData calendarData = getCalendarData(date); + return getPrevious(calendarData); } public CalendarData getPrevious(CalendarData calendarData) { Integer index = calendarDataVersions.indexOf(calendarData) - 1; + if (index < 0) { return null; } + return calendarDataVersions.get(index); } public LocalDate getValidFrom(LocalDate date) { CalendarData calendarData = getPreviousCalendarData(date); + if (calendarData == null) { return null; } + return calendarData.getExpiringDate(); } - public void setValidFrom(LocalDate validFromDate, LocalDate date) - throws IllegalArgumentException { + public void setValidFrom(LocalDate validFromDate, LocalDate date) { CalendarData calendarData = getPreviousCalendarData(date); + if (calendarData == null) { throw new IllegalArgumentException( "You can not set this date for the first work week"); } + setExpiringDate(calendarData, validFromDate); } public boolean isLastVersion(LocalDate date) { CalendarData calendarData = getCalendarData(date); Integer index = calendarDataVersions.indexOf(calendarData); - return (index == (calendarDataVersions.size() - 1)); + + return index == (calendarDataVersions.size() - 1); } public boolean isFirstVersion(LocalDate date) { CalendarData calendarData = getCalendarData(date); Integer index = calendarDataVersions.indexOf(calendarData); - return (index == 0); + + return index == 0; } /** * Returns a set of non workable days (0 hours) for a specific period * depending on the calendar restrictions. + * + * @param init + * @param end + * + * @return Set of locate date */ public Set getNonWorkableDays(LocalDate init, LocalDate end) { - Set result = new HashSet(); - for (LocalDate current = init; current.compareTo(end) <= 0; current = current - .plusDays(1)) { + Set result = new HashSet<>(); + + for (LocalDate current = init; current.compareTo(end) <= 0; current = current.plusDays(1)) { if (getCapacityOn(PartialDay.wholeDay(current)).isZero()) { result.add(current); } } + return result; } @@ -790,8 +812,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman return exceptionDay.getType(); } - public void removeCalendarData(CalendarData calendarData) - throws IllegalArgumentException { + public void removeCalendarData(CalendarData calendarData) { if (this.getCalendarDataVersions().size() <= 1) { throw new IllegalArgumentException( "You can not remove the last calendar data"); @@ -811,6 +832,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (index > 0) { return calendarDataVersions.get(index - 1).getExpiringDate(); } + return null; } @@ -822,45 +844,41 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman * Returns a a copy of calendar availabilities sorted by start date. * calendarAvailabilities should already be sorted by start date, this * method is just for extra safety + * + * @return List of calendar availability */ private List getCalendarAvailabilitiesSortedByStartDate() { - List result = new ArrayList( - calendarAvailabilities); + List result = new ArrayList<>(calendarAvailabilities); Collections.sort(result, CalendarAvailability.BY_START_DATE_COMPARATOR); + return result; } - public void addNewCalendarAvailability( - CalendarAvailability calendarAvailability) - throws IllegalArgumentException { + public void addNewCalendarAvailability(CalendarAvailability calendarAvailability) { if (this instanceof ResourceCalendar) { if (!calendarAvailabilities.isEmpty()) { CalendarAvailability lastCalendarAvailability = getLastCalendarAvailability(); if (lastCalendarAvailability != null) { if (lastCalendarAvailability.getEndDate() == null) { - if (lastCalendarAvailability.getStartDate().compareTo( - calendarAvailability.getStartDate()) >= 0) { + if (lastCalendarAvailability.getStartDate() + .compareTo(calendarAvailability.getStartDate()) >= 0) { throw new IllegalArgumentException( "New calendar availability should start after the last calendar availability"); } } else { - if (lastCalendarAvailability.getEndDate().compareTo( - calendarAvailability.getStartDate()) >= 0) { + if (lastCalendarAvailability.getEndDate().compareTo(calendarAvailability.getStartDate()) >= 0) { throw new IllegalArgumentException( "New calendar availability should start after the last calendar availability"); } } - lastCalendarAvailability.setEndDate(calendarAvailability - .getStartDate().minusDays(1)); + lastCalendarAvailability.setEndDate(calendarAvailability.getStartDate().minusDays(1)); } } calendarAvailabilities.add(calendarAvailability); } } - public void removeCalendarAvailability( - CalendarAvailability calendarAvailability) - throws IllegalArgumentException { + public void removeCalendarAvailability(CalendarAvailability calendarAvailability) { calendarAvailabilities.remove(calendarAvailability); } @@ -868,11 +886,13 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (getCalendarAvailabilities().isEmpty()) { return true; } + for (CalendarAvailability calendarAvailability : getCalendarAvailabilities()) { if (calendarAvailability.isActive(date)) { return true; } } + return false; } @@ -880,16 +900,19 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (getCalendarAvailabilities().isEmpty()) { return true; } + for (CalendarAvailability calendarAvailability : getCalendarAvailabilities()) { if (calendarAvailability.isActiveBetween(startDate, endDate)) { return true; } } + return false; } public boolean canWorkOn(LocalDate date) { Capacity capacity = findCapacityAt(date); + return capacity.allowsWorking(); } @@ -900,6 +923,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman // Sorting for ensuring the last one is picked. In theory sorting would // not be necessary, doing it for safety List sorted = getCalendarAvailabilitiesSortedByStartDate(); + return sorted.get(sorted.size() - 1); } @@ -910,45 +934,34 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman // Sorting for ensuring the first one is picked. In theory sorting would // not be necessary, doing it for safety List sorted = getCalendarAvailabilitiesSortedByStartDate(); + return sorted.get(0); } - public boolean isLastCalendarAvailability( - CalendarAvailability calendarAvailability) { - if (getLastCalendarAvailability() == null - || calendarAvailability == null) { + public boolean isLastCalendarAvailability(CalendarAvailability calendarAvailability) { + if (getLastCalendarAvailability() == null || calendarAvailability == null) { return false; } - if (getLastCalendarAvailability().getId() == null - && calendarAvailability.getId() == null) { + if (getLastCalendarAvailability().getId() == null && calendarAvailability.getId() == null) { return getLastCalendarAvailability() == calendarAvailability; } - return Objects.equals(getLastCalendarAvailability().getId(), - calendarAvailability.getId()); + + return Objects.equals(getLastCalendarAvailability().getId(), calendarAvailability.getId()); } - public void setStartDate(CalendarAvailability calendarAvailability, - LocalDate startDate) throws IllegalArgumentException { + public void setStartDate(CalendarAvailability calendarAvailability, LocalDate startDate) { int index = calendarAvailabilities.indexOf(calendarAvailability); - if (index > 0) { - if (calendarAvailabilities.get(index - 1).getEndDate().compareTo( - startDate) >= 0) { - throw new IllegalArgumentException( - "Start date could not overlap previous calendar availability"); - } + if (index > 0 && calendarAvailabilities.get(index - 1).getEndDate().compareTo(startDate) >= 0) { + throw new IllegalArgumentException("Start date could not overlap previous calendar availability"); } calendarAvailability.setStartDate(startDate); } - public void setEndDate(CalendarAvailability calendarAvailability, - LocalDate endDate) throws IllegalArgumentException { + public void setEndDate(CalendarAvailability calendarAvailability, LocalDate endDate) { int index = calendarAvailabilities.indexOf(calendarAvailability); - if (index < (calendarAvailabilities.size() - 1)) { - if (calendarAvailabilities.get(index + 1).getStartDate().compareTo( - endDate) <= 0) { - throw new IllegalArgumentException( - "End date could not overlap next calendar availability"); - } + if (index < (calendarAvailabilities.size() - 1) && + calendarAvailabilities.get(index + 1).getStartDate().compareTo(endDate) <= 0) { + throw new IllegalArgumentException("End date could not overlap next calendar availability"); } calendarAvailability.setEndDate(endDate); } @@ -956,13 +969,11 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman @Override public EffortDuration asDurationOn(PartialDay day, ResourcesPerDay amount) { Capacity capacity = findCapacityAt(day.getDate()); - EffortDuration oneResourcePerDayWorkingDuration = day - .limitWorkingDay(capacity.getStandardEffort()); - EffortDuration amountRequestedDuration = amount - .asDurationGivenWorkingDayOf(oneResourcePerDayWorkingDuration); + EffortDuration oneResourcePerDayWorkingDuration = day.limitWorkingDay(capacity.getStandardEffort()); + EffortDuration amountRequestedDuration = amount.asDurationGivenWorkingDayOf(oneResourcePerDayWorkingDuration); + + EffortDuration duration = multiplyByCalendarUnits(capacity).limitDuration(amountRequestedDuration); - EffortDuration duration = multiplyByCalendarUnits(capacity) - .limitDuration(amountRequestedDuration); return duration.atNearestMinute(); } @@ -983,9 +994,11 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman @Override public boolean thereAreCapacityFor(AvailabilityTimeLine availability, - ResourcesPerDay resourcesPerDay, EffortDuration durationToAllocate) { - return ThereAreHoursOnWorkHoursCalculator.thereIsAvailableCapacityFor( - this, availability, resourcesPerDay, durationToAllocate) + ResourcesPerDay resourcesPerDay, + EffortDuration durationToAllocate) { + + return ThereAreHoursOnWorkHoursCalculator + .thereIsAvailableCapacityFor(this, availability, resourcesPerDay, durationToAllocate) .thereIsCapacityAvailable(); } @@ -995,6 +1008,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman public boolean lastDataDoesntGiveOnlyZeros() { CalendarData last = lastCalendarData(); + return last.isEmpty(); } @@ -1008,6 +1022,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman return false; } } + return true; } @@ -1025,8 +1040,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman addInvaliditiesFromEmptyDaysInCalendarDatas(result); } - private void addInvaliditiesFromEmptyDaysInCalendarDatas( - AvailabilityTimeLine result) { + private void addInvaliditiesFromEmptyDaysInCalendarDatas(AvailabilityTimeLine result) { result.setVetoer(new IVetoer() { @Override @@ -1036,8 +1050,7 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman }); } - private void addInvaliditiesFromEmptyCalendarDatas( - AvailabilityTimeLine result) { + private void addInvaliditiesFromEmptyCalendarDatas(AvailabilityTimeLine result) { LocalDate previous = null; for (CalendarData each : calendarDataVersions) { addInvalidityIfDataEmpty(result, previous, each); @@ -1045,15 +1058,16 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } } - private void addInvalidityIfDataEmpty(AvailabilityTimeLine result, - LocalDate previous, CalendarData each) { + private void addInvalidityIfDataEmpty(AvailabilityTimeLine result, LocalDate previous, CalendarData each) { if (!each.isEmpty()) { return; } + final boolean hasExpiringDate = each.getExpiringDate() != null; + if (previous == null && hasExpiringDate) { result.invalidUntil(each.getExpiringDate()); - } else if (previous == null && !hasExpiringDate) { + } else if (previous == null) { result.allInvalid(); } else if (hasExpiringDate) { result.invalidAt(previous, each.getExpiringDate()); @@ -1066,22 +1080,25 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman if (calendarAvailabilities.isEmpty()) { return; } + List availabilities = getCalendarAvailabilitiesSortedByStartDate(); CalendarAvailability previous = null; + for (CalendarAvailability each : availabilities) { final boolean isFirstOne = previous == null; + if (isFirstOne) { timeLine.invalidUntil(each.getStartDate()); } else { // CalendarAvailability's end is inclusive - LocalDate startOfInvalidPeriod = previous.getEndDate() - .plusDays(1); + LocalDate startOfInvalidPeriod = previous.getEndDate().plusDays(1); timeLine.invalidAt(startOfInvalidPeriod, each.getStartDate()); } previous = each; } final CalendarAvailability last = previous; - if (last.getEndDate() != null) { + + if (last != null && last.getEndDate() != null) { // CalendarAvailability's end is inclusive timeLine.invalidFrom(last.getEndDate().plusDays(1)); } @@ -1124,12 +1141,10 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman return true; } - public CalendarException getCalendarExceptionByCode(String code) - throws InstanceNotFoundException { + public CalendarException getCalendarExceptionByCode(String code) throws InstanceNotFoundException { if (StringUtils.isBlank(code)) { - throw new InstanceNotFoundException(code, CalendarException.class - .getName()); + throw new InstanceNotFoundException(code, CalendarException.class.getName()); } for (CalendarException e : this.exceptions) { @@ -1138,17 +1153,14 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman } } - throw new InstanceNotFoundException(code, CalendarException.class - .getName()); + throw new InstanceNotFoundException(code, CalendarException.class.getName()); } - public CalendarData getCalendarDataByCode(String code) - throws InstanceNotFoundException { + public CalendarData getCalendarDataByCode(String code) throws InstanceNotFoundException { if (StringUtils.isBlank(code)) { - throw new InstanceNotFoundException(code, CalendarData.class - .getName()); + throw new InstanceNotFoundException(code, CalendarData.class.getName()); } for (CalendarData e : this.calendarDataVersions) { @@ -1163,40 +1175,30 @@ public class BaseCalendar extends IntegrationEntity implements ICalendar, IHuman public void generateCalendarExceptionCodes(int numberOfDigits) { for (CalendarException exception : this.getExceptions()) { - if ((exception.getCode() == null) - || (exception.getCode().isEmpty()) - || (!exception.getCode().startsWith(this.getCode()))) { + if ((exception.getCode() == null) || (exception.getCode().isEmpty()) || + (!exception.getCode().startsWith(this.getCode()))) { + this.incrementLastSequenceCode(); - String exceptionCode = EntitySequence.formatValue( - numberOfDigits, this.getLastSequenceCode()); - exception.setCode(this.getCode() - + EntitySequence.CODE_SEPARATOR_CHILDREN - + exceptionCode); + String exceptionCode = EntitySequence.formatValue(numberOfDigits, this.getLastSequenceCode()); + exception.setCode(this.getCode() + EntitySequence.CODE_SEPARATOR_CHILDREN + exceptionCode); } } for (CalendarData data : this.getCalendarDataVersions()) { - if ((data.getCode() == null) || (data.getCode().isEmpty()) - || (!data.getCode().startsWith(this.getCode()))) { + if ((data.getCode() == null) || (data.getCode().isEmpty()) || (!data.getCode().startsWith(this.getCode()))) { this.incrementLastSequenceCode(); - String dataCode = EntitySequence.formatValue(numberOfDigits, - this.getLastSequenceCode()); - data.setCode(this.getCode() - + EntitySequence.CODE_SEPARATOR_CHILDREN + dataCode); + String dataCode = EntitySequence.formatValue(numberOfDigits, this.getLastSequenceCode()); + data.setCode(this.getCode() + EntitySequence.CODE_SEPARATOR_CHILDREN + dataCode); } } - for (CalendarAvailability availability : this - .getCalendarAvailabilities()) { - if ((availability.getCode() == null) - || (availability.getCode().isEmpty()) - || (!availability.getCode().startsWith(this.getCode()))) { + for (CalendarAvailability availability : this.getCalendarAvailabilities()) { + if ((availability.getCode() == null) || (availability.getCode().isEmpty()) || + (!availability.getCode().startsWith(this.getCode()))) { + this.incrementLastSequenceCode(); - String availabilityCode = EntitySequence.formatValue( - numberOfDigits, this.getLastSequenceCode()); - availability.setCode(this.getCode() - + EntitySequence.CODE_SEPARATOR_CHILDREN - + availabilityCode); + String availabilityCode = EntitySequence.formatValue(numberOfDigits, this.getLastSequenceCode()); + availability.setCode(this.getCode() + EntitySequence.CODE_SEPARATOR_CHILDREN + availabilityCode); } } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarAvailability.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarAvailability.java index 77fc814a1..cf1b50a30 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarAvailability.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarAvailability.java @@ -32,67 +32,54 @@ import org.libreplan.business.common.IntegrationEntity; import org.libreplan.business.common.Registry; /** - * Stores information about activating periods, that define the availability of - * the resource. + * Stores information about activating periods, that define the availability of the resource. * * @author Manuel Rego Casasnovas */ public class CalendarAvailability extends IntegrationEntity { - public static CalendarAvailability craete() { - return create(new CalendarAvailability(new LocalDate(), null)); - } - - public static CalendarAvailability craete(Date startDate, Date endDate) { - return create(new CalendarAvailability(new LocalDate(startDate), - new LocalDate(endDate))); - } - - public static CalendarAvailability create(LocalDate startDate, - LocalDate endDate) { - return create(new CalendarAvailability(startDate, endDate)); - } + public static final Comparator BY_START_DATE_COMPARATOR = + (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()); @NotNull private LocalDate startDate; private LocalDate endDate; - public static final Comparator BY_START_DATE_COMPARATOR = new Comparator() { - - @Override - public int compare(CalendarAvailability o1, CalendarAvailability o2) { - return o1.getStartDate().compareTo(o2.getStartDate()); - } - }; - /** * Constructor for hibernate. Do not use! */ - public CalendarAvailability() { - } + public CalendarAvailability() {} - private CalendarAvailability(LocalDate startDate, LocalDate endDate) - throws IllegalArgumentException { + private CalendarAvailability(LocalDate startDate, LocalDate endDate) { setStartDate(startDate); setEndDate(endDate); } + public static CalendarAvailability create() { + return create(new CalendarAvailability(new LocalDate(), null)); + } + + public static CalendarAvailability create(Date startDate, Date endDate) { + return create(new CalendarAvailability(new LocalDate(startDate), new LocalDate(endDate))); + } + + public static CalendarAvailability create(LocalDate startDate, LocalDate endDate) { + return create(new CalendarAvailability(startDate, endDate)); + } + public LocalDate getStartDate() { return startDate; } - public void setStartDate(LocalDate startDate) - throws IllegalArgumentException { + public void setStartDate(LocalDate startDate) { if (startDate == null) { throw new IllegalArgumentException("Start date must not be null"); } - if (endDate != null) { - if (startDate.compareTo(endDate) > 0) { - throw new IllegalArgumentException( - "End date must be greater or equal than start date"); - } + if (endDate != null && startDate.compareTo(endDate) > 0) { + throw new IllegalArgumentException("End date must be greater or equal than start date"); } + this.startDate = startDate; } @@ -100,26 +87,16 @@ public class CalendarAvailability extends IntegrationEntity { return endDate; } - public void setEndDate(LocalDate endDate) throws IllegalArgumentException { - if (endDate != null) { - if (startDate.compareTo(endDate) > 0) { - throw new IllegalArgumentException( - "End date must be greater or equal than start date"); - } + public void setEndDate(LocalDate endDate) { + if (endDate != null && startDate.compareTo(endDate) > 0) { + throw new IllegalArgumentException("End date must be greater or equal than start date"); } this.endDate = endDate; } public boolean isActive(LocalDate date) { - if (startDate.compareTo(date) > 0) { - return false; - } + return startDate.compareTo(date) <= 0 && !((endDate != null) && (endDate.compareTo(date) < 0)); - if ((endDate != null) && (endDate.compareTo(date) < 0)) { - return false; - } - - return true; } @Override @@ -127,8 +104,7 @@ public class CalendarAvailability extends IntegrationEntity { return Registry.getCalendarAvailabilityDAO(); } - public boolean isActiveBetween(LocalDate filterStartDate, - LocalDate filterEndDate) { + public boolean isActiveBetween(LocalDate filterStartDate, LocalDate filterEndDate) { if (filterStartDate == null && filterEndDate == null) { return true; } @@ -137,29 +113,25 @@ public class CalendarAvailability extends IntegrationEntity { if (endDate == null) { return startDate.compareTo(filterEndDate) <= 0; } - return startDate.compareTo(filterEndDate) <= 0 - || endDate.compareTo(filterEndDate) <= 0; + + return startDate.compareTo(filterEndDate) <= 0 || endDate.compareTo(filterEndDate) <= 0; } if (filterEndDate == null) { - if (endDate == null) { - return true; - } - return startDate.compareTo(filterStartDate) >= 0 - || endDate.compareTo(filterStartDate) >= 0; + return endDate == null || startDate.compareTo(filterStartDate) >= 0 || + endDate.compareTo(filterStartDate) >= 0; } if (endDate == null) { - return startDate.compareTo(filterStartDate) <= 0 - || startDate.compareTo(filterEndDate) <= 0; + return startDate.compareTo(filterStartDate) <= 0 || startDate.compareTo(filterEndDate) <= 0; } - Interval filterPeriod = new Interval( - filterStartDate.toDateTimeAtStartOfDay(), filterEndDate - .plusDays(1).toDateTimeAtStartOfDay()); - Interval activationPeriod = new Interval( - startDate.toDateTimeAtStartOfDay(), endDate.plusDays(1) - .toDateTimeAtStartOfDay()); + Interval filterPeriod = new Interval(filterStartDate.toDateTimeAtStartOfDay(), + filterEndDate.plusDays(1).toDateTimeAtStartOfDay()); + + Interval activationPeriod = new Interval(startDate.toDateTimeAtStartOfDay(), + endDate.plusDays(1).toDateTimeAtStartOfDay()); + return filterPeriod.overlaps(activationPeriod); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarBootstrap.java index 6adb8f709..a7fbdc9b1 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarBootstrap.java @@ -25,6 +25,7 @@ import org.libreplan.business.calendars.daos.ICalendarExceptionTypeDAO; import org.libreplan.business.common.daos.IEntitySequenceDAO; import org.libreplan.business.common.entities.EntityNameEnum; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -35,7 +36,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class CalendarBootstrap implements ICalendarBootstrap { @Autowired diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionType.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionType.java index e398071ea..7270883b7 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionType.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionType.java @@ -23,8 +23,6 @@ package org.libreplan.business.calendars.entities; import static org.libreplan.business.i18n.I18nHelper._; -import java.util.EnumMap; - import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -38,7 +36,6 @@ import org.libreplan.business.common.IntegrationEntity; import org.libreplan.business.common.Registry; import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.workingday.EffortDuration; -import org.libreplan.business.workingday.EffortDuration.Granularity; import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException; /** @@ -57,6 +54,18 @@ public class CalendarExceptionType extends IntegrationEntity implements IHumanId private Capacity capacity = Capacity.zero(); + /** + * Constructor for hibernate. Do not use! + */ + protected CalendarExceptionType() {} + + public CalendarExceptionType(String name, CalendarExceptionTypeColor color, Boolean notOverAssignable) { + this.name = name; + this.color = color; + this.capacity = Capacity.zero(); + this.capacity = this.capacity.overAssignableWithoutLimit(!BooleanUtils.isTrue(notOverAssignable)); + } + public static CalendarExceptionType create() { return create(new CalendarExceptionType()); } @@ -92,19 +101,6 @@ public class CalendarExceptionType extends IntegrationEntity implements IHumanId return create(calendarExceptionType, code); } - /** - * Constructor for hibernate. Do not use! - */ - protected CalendarExceptionType() { - } - - public CalendarExceptionType(String name, CalendarExceptionTypeColor color, Boolean notOverAssignable) { - this.name = name; - this.color = color; - this.capacity = Capacity.zero(); - this.capacity = this.capacity.overAssignableWithoutLimit(!BooleanUtils.isTrue(notOverAssignable)); - } - public boolean isUpdatable() { return this.updatable; } @@ -155,18 +151,6 @@ public class CalendarExceptionType extends IntegrationEntity implements IHumanId return capacity.getStandardEffort(); } - private String asString(EffortDuration duration) { - if ( duration == null ) { - return ""; - } - - EnumMap values = duration.decompose(); - Integer hours = values.get(Granularity.HOURS); - Integer minutes = values.get(Granularity.MINUTES); - - return hours + ":" + minutes; - } - public void setDuration(EffortDuration duration) { this.capacity = this.capacity.withStandardEffort(duration); } @@ -191,12 +175,10 @@ public class CalendarExceptionType extends IntegrationEntity implements IHumanId calendarExceptionTypeDAO.findUniqueByNameAnotherTransaction(name); return calendarExceptionType.getId().equals(getId()); - } catch (InstanceNotFoundException e) { + } catch (InstanceNotFoundException | HibernateOptimisticLockingFailureException e) { return true; } catch (NonUniqueResultException e) { return false; - } catch (HibernateOptimisticLockingFailureException e) { - return true; } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionTypeColor.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionTypeColor.java index d1eb7f36f..06d013cdc 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionTypeColor.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/CalendarExceptionTypeColor.java @@ -22,8 +22,7 @@ package org.libreplan.business.calendars.entities; import static org.libreplan.business.i18n.I18nHelper._; /** - * Enum representing the possible colors to choose for a - * {@link CalendarExceptionType} + * Enum representing the possible colors to choose for a {@link CalendarExceptionType}. * * @author Manuel Rego Casasnovas */ @@ -39,7 +38,9 @@ public enum CalendarExceptionTypeColor { PURPLE(_("purple"), "#801a80", "#b38eb3"); private final String name; + private final String colorOwnException; + private final String colorDerivedException; CalendarExceptionTypeColor(String name, String colorOwnException, String colorDerivedException) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/Capacity.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/Capacity.java index 3d7423df3..213ccd7a4 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/Capacity.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/Capacity.java @@ -33,13 +33,18 @@ import org.libreplan.business.workingday.EffortDuration.Granularity; /** - * This class is intended as a Hibernate component. It's formed by two - * components, the standard effort and the allowed extra effort. It represents - * the capacity for a resource. + * This class is intended as a Hibernate component. + * It's formed by two components, the standard effort and the allowed extra effort. + * It represents the capacity for a resource. + * * @author Óscar González Fernández */ public class Capacity { + private EffortDuration standardEffort; + + private EffortDuration allowedExtraEffort; + public static Capacity sum(Capacity... capacities) { return sum(Arrays.asList(capacities)); } @@ -56,8 +61,7 @@ public class Capacity { } public static Capacity min(Capacity a, Capacity b) { - return new Capacity(EffortDuration.min(a.getStandardEffort(), - b.getStandardEffort()), minExtraEffort(a, b)); + return new Capacity(EffortDuration.min(a.getStandardEffort(), b.getStandardEffort()), minExtraEffort(a, b)); } private static EffortDuration minExtraEffort(Capacity a, Capacity b) { @@ -90,17 +94,14 @@ public class Capacity { } private static Capacity noCapacity() { - return Capacity.create(EffortDuration.zero()) - .notOverAssignableWithoutLimit(); + return Capacity.create(EffortDuration.zero()).notOverAssignableWithoutLimit(); } public static Capacity zero() { return new Capacity(EffortDuration.zero(), EffortDuration.zero()); } - private EffortDuration standardEffort; - private EffortDuration allowedExtraEffort; /** * Default constructor for hibernate. DO NOT USE! @@ -111,7 +112,7 @@ public class Capacity { } private Capacity(EffortDuration standardEffort, - EffortDuration extraHours) { + EffortDuration extraHours) { Validate.notNull(standardEffort); this.standardEffort = standardEffort; this.allowedExtraEffort = extraHours; @@ -229,7 +230,7 @@ public class Capacity { Validate.notNull(assignedDuration); return isOverAssignableWithoutLimit() || assignedDuration.compareTo(standardEffort - .plus(allowedExtraEffort)) < 0; + .plus(allowedExtraEffort)) < 0; } public Capacity minus(EffortDuration assignment) { @@ -243,7 +244,7 @@ public class Capacity { standardEffort, assignment)); EffortDuration newExtra = allowedExtraEffort == null ? null : allowedExtraEffort.minus(EffortDuration.min(pending, - allowedExtraEffort)); + allowedExtraEffort)); return Capacity.create(newStandard).withAllowedExtraEffort(newExtra); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ICalendar.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ICalendar.java index 422f87dc7..83482c406 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ICalendar.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ICalendar.java @@ -29,39 +29,39 @@ import org.libreplan.business.workingday.ResourcesPerDay; public interface ICalendar { /** - * Translates the received amount into the corresponding duration at the - * given date. It takes into account the partial capacity of the day. + * Translates the received amount into the corresponding duration at the given date. + * It takes into account the partial capacity of the day. * * @param day * @param amount * @return */ - public EffortDuration asDurationOn(PartialDay day, ResourcesPerDay amount); + EffortDuration asDurationOn(PartialDay day, ResourcesPerDay amount); /** - * Calculates the capacity duration at a given day. It means all the time - * that could be worked without having overtime. It considers the - * {@link PartialDay} so if the day it's not complete the capacity is - * reduced + * Calculates the capacity duration at a given day. + * It means all the time that could be worked without having overtime. + * It considers the {@link PartialDay} so if the day it's not complete the capacity is reduced. + * * @param date * the date at which the capacity is calculated * @return the capacity at which the resource can work at the day specified */ - public EffortDuration getCapacityOn(PartialDay partialDay); + EffortDuration getCapacityOn(PartialDay partialDay); /** - * Calculates the capacity information for a given date. It contains - * information about the normal effort and the extra effort, i.e., the - * overtime effort. + * Calculates the capacity information for a given date. + * It contains information about the normal effort and the extra effort, i.e., the overtime effort. * * @param date * a not null date * @return the capacity for the date provided */ - public Capacity getCapacityWithOvertime(LocalDate date); + Capacity getCapacityWithOvertime(LocalDate date); - public AvailabilityTimeLine getAvailability(); + AvailabilityTimeLine getAvailability(); - public boolean thereAreCapacityFor(AvailabilityTimeLine availability, - ResourcesPerDay resourcesPerDay, EffortDuration durationToAllocate); + boolean thereAreCapacityFor(AvailabilityTimeLine availability, + ResourcesPerDay resourcesPerDay, + EffortDuration durationToAllocate); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ResourceCalendar.java b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ResourceCalendar.java index 1090b5011..87a20c4fc 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ResourceCalendar.java +++ b/libreplan-business/src/main/java/org/libreplan/business/calendars/entities/ResourceCalendar.java @@ -28,6 +28,7 @@ import org.libreplan.business.resources.entities.Resource; /** * Calendar for a {@link Resource}. + * * @author Manuel Rego Casasnovas * @author Lorenzo Tilve Álvaro */ @@ -41,6 +42,7 @@ public class ResourceCalendar extends BaseCalendar { if (capacity == null) { return 1; } + return capacity; } @@ -60,8 +62,7 @@ public class ResourceCalendar extends BaseCalendar { private ResourceCalendar(CalendarData calendarData) { super(calendarData); - CalendarAvailability calendarAvailability = CalendarAvailability - .create(new LocalDate(), null); + CalendarAvailability calendarAvailability = CalendarAvailability.create(new LocalDate(), null); addNewCalendarAvailability(calendarAvailability); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/AdHocTransactionService.java b/libreplan-business/src/main/java/org/libreplan/business/common/AdHocTransactionService.java index 7b93dac87..d33a40507 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/AdHocTransactionService.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/AdHocTransactionService.java @@ -32,10 +32,13 @@ import org.springframework.transaction.annotation.Transactional; @Service public class AdHocTransactionService implements IAdHocTransactionService { - private static T proxy( - IAdHocTransactionService transactionService, boolean readOnly, Class interfaceClass, T interfaceObject) { + private static T proxy(IAdHocTransactionService transactionService, + boolean readOnly, + Class interfaceClass, + T interfaceObject) { Class[] interfaces = { interfaceClass }; + return interfaceClass.cast(Proxy.newProxyInstance( interfaceClass.getClassLoader(), interfaces, @@ -43,51 +46,54 @@ public class AdHocTransactionService implements IAdHocTransactionService { } /** - * Returns a new object implementing the same interface but with its calls - * wrapped on read only transactions + * Returns a new object implementing the same interface but with its calls wrapped on read only transactions. + * * @param transactionService * @param interfaceClass * @param interfaceObject - * @return + * @return T */ - public static T readOnlyProxy( - IAdHocTransactionService transactionService, Class interfaceClass, T interfaceObject) { + public static T readOnlyProxy(IAdHocTransactionService transactionService, + Class interfaceClass, + T interfaceObject) { return proxy(transactionService, true, interfaceClass, interfaceObject); } /** - * Returns a new object implementing the same interface but with its calls - * wrapped on transactions + * Returns a new object implementing the same interface but with its calls wrapped on transactions. + * * @param transactionService * @param interfaceClass * @param interfaceObject - * @return + * @return T */ - public static T proxy(IAdHocTransactionService transactionService, Class interfaceClass, T interfaceObject) { + public static T proxy(IAdHocTransactionService transactionService, + Class interfaceClass, + T interfaceObject) { + return proxy(transactionService, false, interfaceClass, interfaceObject); } - private static InvocationHandler createHandler( - final Object originalObject, final IAdHocTransactionService transactionService, final boolean readOnly) { - + private static InvocationHandler createHandler(final Object originalObject, + final IAdHocTransactionService transactionService, + final boolean readOnly) { return (proxy, method, args) -> { IOnTransaction onTransaction = createOnTransaction(originalObject, method, args); try { - if ( readOnly ) { - return transactionService.runOnReadOnlyTransaction(onTransaction); - } else { - return transactionService.runOnTransaction(onTransaction); - } + return readOnly + ? transactionService.runOnReadOnlyTransaction(onTransaction) + : transactionService.runOnTransaction(onTransaction); + } catch (RuntimeException e) { throw e.getCause(); } }; } - private static IOnTransaction createOnTransaction( - final Object originalObject, final Method method, final Object[] args) { - + private static IOnTransaction createOnTransaction(final Object originalObject, + final Method method, + final Object[] args) { return () -> { try { return method.invoke(originalObject, args); diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/BaseEntity.java b/libreplan-business/src/main/java/org/libreplan/business/common/BaseEntity.java index 235acbdac..232eb942b 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/BaseEntity.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/BaseEntity.java @@ -43,7 +43,6 @@ import org.libreplan.business.util.deepcopy.Strategy; /** * Base class for all the application entities. - * * It provides the basic behavior for id and version fields. * * @author Manuel Rego Casasnovas @@ -126,8 +125,9 @@ public abstract class BaseEntity implements INewObject { /** * Once the has been really saved in DB (not a readonly transaction), it - * could be necessary to unmark the object as newObject. This is the case if - * you must use the same instance after the transaction.
+ * could be necessary to unmark the object as newObject. + * This is the case if you must use the same instance after the transaction. + *
*/ public void dontPoseAsTransientObjectAnymore() { setNewObject(false); diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/Configuration.java b/libreplan-business/src/main/java/org/libreplan/business/common/Configuration.java index ad40e14e5..163b36758 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/Configuration.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/Configuration.java @@ -28,12 +28,12 @@ import org.apache.commons.lang3.BooleanUtils; * * Currently we have three options: *
    - *
  • Enable/Disable the warning changing default password
  • - * - *
  • Enable/Disable default users - * (such as wsreader, wswriter, wssubcontracting, manager, hresources, outsourcing and reports)
  • - * - *
  • Enable/Disable E-mail sending functionality
  • + *
  • Enable/Disable the warning changing default password
  • + *
  • + * Enable/Disable default users + * (such as wsreader, wswriter, wssubcontracting, manager, hresources, outsourcing and reports) + *
  • + *
  • Enable/Disable E-mail sending functionality
  • *
* * @author Susana Montes Pedreira diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/Registry.java b/libreplan-business/src/main/java/org/libreplan/business/common/Registry.java index f519dcb75..6e0a3b498 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/Registry.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/Registry.java @@ -69,8 +69,8 @@ import org.libreplan.business.workreports.daos.IWorkReportTypeDAO; import org.springframework.beans.factory.annotation.Autowired; /** - * A registry, AKA service locator, for objects in which dependency injection (DI) is not directly supported by Spring - * (e.g. entities) must use this class to access DAOs. + * A registry, AKA service locator, for objects in which dependency injection + * (DI) is not directly supported by Spring (e.g. entities) must use this class to access DAOs. * For the rest of classes (e.g. services, tests, etc.), Spring DI is a more convenient option. * The DAOs or services are added to the registry as needed. * @@ -223,8 +223,7 @@ public class Registry { @Autowired private IAdHocTransactionService transactionServiceDAO; - private Registry() { - } + private Registry() {} public static Registry getInstance() { return singleton; diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/Util.java b/libreplan-business/src/main/java/org/libreplan/business/common/Util.java index fe8bbacfb..d3eb0e4aa 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/Util.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/Util.java @@ -22,7 +22,8 @@ package org.libreplan.business.common; import java.util.Collection; /** - * Utilities class.
+ * Utilities class. + *
* @author Manuel Rego Casasnovas */ public class Util { @@ -34,16 +35,17 @@ public class Util { if (entity1.getId() == null || entity2.getId() == null) { return false; } + return entity1.getId().equals(entity2.getId()); } - public static boolean contains(Collection collection, - BaseEntity entity) { + public static boolean contains(Collection collection, BaseEntity entity) { for (BaseEntity each : collection) { - if (each.getId().equals(entity.getId())) { + if ( each.getId().equals(entity.getId()) ) { return true; } } + return false; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java b/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java index 4a4c6a5a5..3b9cafb19 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java @@ -30,13 +30,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * It contains the current version of project and implements of singleton - * pattern.
- * It also has a cached value with information about last project version - * published. It checks the last version against a URL. + * It contains the current version of project and implements of singleton pattern.
+ * It also has a cached value with information about last project version published. + * It checks the last version against a URL. * * @author Susana Montes Pedreira - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public class VersionInformation { @@ -47,14 +46,11 @@ public class VersionInformation { */ private static final String LIBREPLAN_VERSION_URL = "http://libreplan.org/VERSION"; - private static final String LIBREPLAN_USAGE_STATS_PARAM = "stats"; - private static final String LIBREPLAN_VERSION_PARAM = "version"; - /** * Delay to wait till we check the URL again */ - private static final long DELAY_TO_CHECK_URL = 24 * 60 * 60 * 1000; // 1 day + private static final long DELAY_TO_CHECK_URL = 24 * 60 * 60 * 1000L; // 1 day private static final VersionInformation singleton = new VersionInformation(); @@ -64,31 +60,27 @@ public class VersionInformation { private Date lastVersionCachedDate = new Date(); - private VersionInformation() { - } + private VersionInformation() {} private void loadNewVersionFromURL() { lastVersionCachedDate = new Date(); try { URL url = getURL(); - String lastVersion = (new BufferedReader(new InputStreamReader( - url.openStream()))).readLine(); + String lastVersion = (new BufferedReader(new InputStreamReader(url.openStream()))).readLine(); if (projectVersion != null && lastVersion != null) { newVersionCached = !projectVersion.equals(lastVersion); } } catch (MalformedURLException e) { - LOG.warn("Problems generating URL to check LibrePlan version. MalformedURLException: " - + e.getMessage()); + LOG.warn("Problems generating URL to check LibrePlan version. MalformedURLException: " + e.getMessage()); } catch (IOException e) { - LOG.info("Could not check LibrePlan version information from " - + LIBREPLAN_VERSION_URL + ". IOException: " - + e.getMessage()); + LOG.info( + "Could not check LibrePlan version information from " + + LIBREPLAN_VERSION_URL + ". IOException: " + e.getMessage()); } } private URL getURL() throws MalformedURLException { - String url = LIBREPLAN_VERSION_URL; - return new URL(url); + return new URL(LIBREPLAN_VERSION_URL); } public static VersionInformation getInstance() { @@ -120,13 +112,11 @@ public class VersionInformation { /** * If there is a new version already detected, it doesn't check it again. - * Otherwise, during one day it returns the cached value. And it checks it - * again after that time. + * Otherwise, during one day it returns the cached value. And it checks it again after that time. */ private boolean checkIsNewVersionAvailable() { if ( !newVersionCached ) { - long oneDayLater = lastVersionCachedDate.getTime() - + DELAY_TO_CHECK_URL; + long oneDayLater = lastVersionCachedDate.getTime() + DELAY_TO_CHECK_URL; if ( oneDayLater < new Date().getTime() ) { loadNewVersionFromURL(); } @@ -138,10 +128,7 @@ public class VersionInformation { String lastVersion = ""; try { URL url = new URL(LIBREPLAN_VERSION_URL); - lastVersion = (new BufferedReader(new InputStreamReader( - url.openStream()))).readLine(); - } catch (MalformedURLException e) { - e.printStackTrace(); + lastVersion = (new BufferedReader(new InputStreamReader(url.openStream()))).readLine(); } catch (IOException e) { e.printStackTrace(); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/ConfigurationDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/ConfigurationDAO.java index 29f2e6815..6fe26d7e7 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/ConfigurationDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/ConfigurationDAO.java @@ -41,12 +41,11 @@ import org.springframework.transaction.annotation.Transactional; public class ConfigurationDAO extends GenericDAOHibernate implements IConfigurationDAO { @Override + @Transactional(readOnly = true) public Configuration getConfiguration() { List list = list(Configuration.class); - if ( list.isEmpty() ) { - return null; - } - return list.get(0); + + return list.isEmpty() ? null : list.get(0); } @Override @@ -60,6 +59,7 @@ public class ConfigurationDAO extends GenericDAOHibernate i public void saveChangedDefaultPassword(String user, boolean change) { user = user.substring(0, 1).toUpperCase() + user.substring(1).toLowerCase(); String sql = "UPDATE Configuration e SET e.changedDefault" + user + "Password = :change"; + Query query = getSession().createQuery(sql); query.setParameter("change", change); query.executeUpdate(); diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/EntitySequenceDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/EntitySequenceDAO.java index e870b358a..467ee6542 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/EntitySequenceDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/EntitySequenceDAO.java @@ -40,6 +40,7 @@ import org.springframework.transaction.annotation.Transactional; /** * DAO for {@link EntitySequence}. + * * @author Susana Montes Pedreira */ @Repository @@ -53,7 +54,7 @@ public class EntitySequenceDAO extends GenericDAOHibernate @Override @SuppressWarnings("unchecked") - public List findEntitySquencesNotIn(List entitySequences) { + public List findEntitySequencesNotIn(List entitySequences) { List entitySequenceIds = new ArrayList<>(); for (EntitySequence entitySequence : entitySequences) { if ( !entitySequence.isNewObject() ) { @@ -61,8 +62,10 @@ public class EntitySequenceDAO extends GenericDAOHibernate } } - return getSession().createCriteria(EntitySequence.class) - .add(Restrictions.not(Restrictions.in("id", entitySequenceIds))).list(); + return getSession() + .createCriteria(EntitySequence.class) + .add(Restrictions.not(Restrictions.in("id", entitySequenceIds))) + .list(); } @Override diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/GenericDAOHibernate.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/GenericDAOHibernate.java index 9c522e772..8ea45a937 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/GenericDAOHibernate.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/GenericDAOHibernate.java @@ -43,9 +43,9 @@ import org.springframework.transaction.annotation.Transactional; /** * An implementation of IGenericDao based on Hibernate's native API. * Concrete DAOs must extend directly from this class. - * This constraint is imposed by the constructor of this class that must infer the - * type of the entity from the declaration of the concrete DAO. - *

+ * This constraint is imposed by the constructor of this class that must infer the type of the + * entity from the declaration of the concrete DAO. + * * This class autowires a SessionFactory bean and allows to implement DAOs with Hibernate's native API. * Subclasses access Hibernate's Session by calling on getSession() method. * Operations must be implemented by catching HibernateException @@ -87,8 +87,8 @@ public class GenericDAOHibernate /** * It's necessary to save and validate later. * - * Validate may retrieve the entity from DB and put it into the Session, - * which can eventually lead to a NonUniqueObject exception. + * Validate may retrieve the entity from DB and put it into the Session, which can eventually lead to + * a NonUniqueObject exception. * Save works here to reattach the object as well as saving. */ public void save(E entity) throws ValidationException { @@ -96,16 +96,16 @@ public class GenericDAOHibernate entity.validate(); } - public void saveWithoutValidating(E entity) { - getSession().saveOrUpdate(entity); - } + public void saveWithoutValidating(E entity) { + getSession().saveOrUpdate(entity); + } public void reattachUnmodifiedEntity(E entity) { if ( Hibernate.isInitialized(entity) && entity.isNewObject() ) { return; } + // TODO resolve deprecated getSession().lock(entity, LockMode.NONE); - } public E merge(E entity) { @@ -114,7 +114,7 @@ public class GenericDAOHibernate public void checkVersion(E entity) { - /* Get id and version from entity. */ + /* Get id and version from entity */ Serializable id; Long versionValueInMemory; @@ -138,10 +138,12 @@ public class GenericDAOHibernate throw new RuntimeException(e); } - /* Check version. */ - Long versionValueInDB = (Long) getSession().createCriteria(entityClass) + /* Check version */ + Long versionValueInDB = (Long) getSession() + .createCriteria(entityClass) .add(Restrictions.idEq(id)) - .setProjection(Projections.property("version")).uniqueResult(); + .setProjection(Projections.property("version")) + .uniqueResult(); if ( versionValueInDB == null ) { return; @@ -159,15 +161,11 @@ public class GenericDAOHibernate } - public void associateToSession(E entity) { - getSession().lock(entity, LockMode.NONE); - } - @SuppressWarnings("unchecked") @Transactional(readOnly = true) public E find(PK id) throws InstanceNotFoundException { - E entity = getSession().get(entityClass, id); + E entity = (E) getSession().get(entityClass, id); if ( entity == null ) { throw new InstanceNotFoundException(id, entityClass.getName()); @@ -188,7 +186,8 @@ public class GenericDAOHibernate public boolean exists(final PK id) { - return getSession().createCriteria(entityClass) + return getSession() + .createCriteria(entityClass) .add(Restrictions.idEq(id)) .setProjection(Projections.id()) .uniqueResult() != null; @@ -212,6 +211,7 @@ public class GenericDAOHibernate } @Override + @Transactional public void reattach(E entity) { getSession().saveOrUpdate(entity); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/IEntitySequenceDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/IEntitySequenceDAO.java index 238085afb..7b04be018 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/IEntitySequenceDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/IEntitySequenceDAO.java @@ -33,6 +33,7 @@ import org.springframework.stereotype.Repository; /** * DAO interface for {@link EntitySequenceDAO}. + * * @author Susana Montes Pedreira */ @Repository @@ -41,12 +42,12 @@ public interface IEntitySequenceDAO extends IGenericDAO { List getAll(); - List findEntitySquencesNotIn(List entitySequences); + List findEntitySequencesNotIn(List entitySequences); void remove(EntitySequence entitySequence) throws InstanceNotFoundException, IllegalArgumentException; - EntitySequence getActiveEntitySequence(EntityNameEnum entityName) throws InstanceNotFoundException, - NonUniqueResultException; + EntitySequence getActiveEntitySequence(EntityNameEnum entityName) + throws InstanceNotFoundException, NonUniqueResultException; String getNextEntityCode(EntityNameEnum entityName); diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/ILimitsDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/ILimitsDAO.java index e95b248ea..ebb039636 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/ILimitsDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/ILimitsDAO.java @@ -25,15 +25,15 @@ import java.util.List; /** * DAO interface for the Limits entity. - * Contract for {@link LimitsDAO} + * Contract for {@link LimitsDAO}. * - * Created by - * @author Vova Perebykivskiy - * on 17.12.2015. + * @author Created by Vova Perebykivskyi on 17.12.2015. */ public interface ILimitsDAO extends IGenericDAO { + List getAll(); Limits getUsersType(); + Limits getResourcesType(); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java index 33bb0b7bd..624892527 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java @@ -33,13 +33,13 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** - * Default implementation of IIntegrationEntityDAO. DAOs of - * entities used in application integration may extend from this interface. + * Default implementation of IIntegrationEntityDAO. + * DAOs of entities used in application integration may extend from this interface. * * @author Fernando Bellas Permuy */ public class IntegrationEntityDAO - extends GenericDAOHibernate implements IIntegrationEntityDAO { + extends GenericDAOHibernate implements IIntegrationEntityDAO { @Override public boolean existsByCode(String code) { @@ -66,15 +66,15 @@ public class IntegrationEntityDAO if (StringUtils.isBlank(code)) { throw new InstanceNotFoundException(null, - getEntityClass().getName()); + getEntityClass().getName()); } E entity = (E) getSession().createCriteria(getEntityClass()).add( - Restrictions.eq("code", code.trim()).ignoreCase()).uniqueResult(); + Restrictions.eq("code", code.trim()).ignoreCase()).uniqueResult(); if (entity == null) { throw new InstanceNotFoundException( - code, getEntityClass().getName()); + code, getEntityClass().getName()); } else { return entity; } @@ -84,7 +84,7 @@ public class IntegrationEntityDAO @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public E findByCodeAnotherTransaction(String code) - throws InstanceNotFoundException { + throws InstanceNotFoundException { return findByCode(code); @@ -104,8 +104,7 @@ public class IntegrationEntityDAO @SuppressWarnings("unchecked") @Override public List findAll() { - return getSession().createCriteria(getEntityClass()). - addOrder(Order.asc("code")).list(); + return getSession().createCriteria(getEntityClass()).addOrder(Order.asc("code")).list(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/LimitsDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/LimitsDAO.java index 87a7c7565..484dc8669 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/LimitsDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/LimitsDAO.java @@ -25,11 +25,9 @@ import org.springframework.stereotype.Repository; import java.util.List; /** - * DAO for {@link Limits} + * DAO for {@link Limits}. * - * Created by - * @author Vova Perebykivskiy - * on 24.09.15. + * @author Created by Vova Perebykivskyi on 24.09.2015. */ @Repository diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/Configuration.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/Configuration.java index 253d85ec2..e57585490 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/Configuration.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/Configuration.java @@ -37,14 +37,10 @@ import org.libreplan.business.costcategories.entities.TypeOfWorkHours; * @author Cristina Alvarino Perez * @author Ignacio Diaz Teijido * @author Susana Montes Pedreira - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public class Configuration extends BaseEntity { - public static Configuration create() { - return create(new Configuration()); - } - private BaseCalendar defaultCalendar; private String companyCode; @@ -111,6 +107,7 @@ public class Configuration extends BaseEntity { * Currency code according to ISO-4217 (3 letters) */ private String currencyCode = "EUR"; + private String currencySymbol = "€"; private TypeOfWorkHours personalTimesheetsTypeOfWorkHours; @@ -137,6 +134,10 @@ public class Configuration extends BaseEntity { private String repositoryLocation; + public static Configuration create() { + return create(new Configuration()); + } + public void setDefaultCalendar(BaseCalendar defaultCalendar) { this.defaultCalendar = defaultCalendar; @@ -151,6 +152,7 @@ public class Configuration extends BaseEntity { if (companyCode != null) { companyCode = companyCode.trim(); } + this.companyCode = companyCode; } @@ -161,53 +163,30 @@ public class Configuration extends BaseEntity { @AssertTrue(message = "company code cannot contain whitespaces") public boolean isCompanyCodeWithoutWhiteSpacesConstraint() { - if ((companyCode == null) || (companyCode.isEmpty())) { - return false; - } - return !companyCode.contains(" "); + return !((companyCode == null) || (companyCode.isEmpty())) && !companyCode.contains(" "); } @AssertTrue(message = "host not specified") public boolean isLdapHostWithoutWhiteSpacesConstraint() { - if (getLdapConfiguration().getLdapAuthEnabled()) { - if (StringUtils.isBlank(getLdapConfiguration().getLdapHost())) { - return false; - } - } - return true; + return !getLdapConfiguration().getLdapAuthEnabled() || !StringUtils.isBlank(getLdapConfiguration().getLdapHost()); + } @AssertTrue(message = "port not specified") public boolean isLdapPortWithoutWhiteSpacesConstraint() { - if (getLdapConfiguration().getLdapAuthEnabled()) { - if (StringUtils.isBlank(getLdapConfiguration().getLdapPort())) { - return false; - } - } - return true; + return !getLdapConfiguration().getLdapAuthEnabled() || !StringUtils.isBlank(getLdapConfiguration().getLdapPort()); } @AssertTrue(message = "base not specified") public boolean isLdapBaseWithoutWhiteSpacesConstraint() { - if (getLdapConfiguration().getLdapAuthEnabled()) { - if (StringUtils.isBlank(getLdapConfiguration().getLdapBase())) { - return false; - } - } - return true; + return !getLdapConfiguration().getLdapAuthEnabled() || !StringUtils.isBlank(getLdapConfiguration().getLdapBase()); } @AssertTrue(message = "userId not specified") public boolean isLdapUserIdWithoutWhiteSpacesConstraint() { - if (getLdapConfiguration().getLdapAuthEnabled()) { - if (StringUtils.isBlank(getLdapConfiguration().getLdapUserId())) { - return false; - } - } - return true; + return !getLdapConfiguration().getLdapAuthEnabled() || !StringUtils.isBlank(getLdapConfiguration().getLdapUserId()); } - //TODO 2 added methods follow below public void setGeneratedCodeForProjectLog(Boolean generateCodeForProjectLog) { this.generateCodeForProjectLog = generateCodeForProjectLog; } @@ -245,8 +224,7 @@ public class Configuration extends BaseEntity { return generateCodeForResources; } - public void setGenerateCodeForTypesOfWorkHours( - Boolean generateCodeForTypesOfWorkHours) { + public void setGenerateCodeForTypesOfWorkHours(Boolean generateCodeForTypesOfWorkHours) { this.generateCodeForTypesOfWorkHours = generateCodeForTypesOfWorkHours; } @@ -254,8 +232,7 @@ public class Configuration extends BaseEntity { return generateCodeForTypesOfWorkHours; } - public void setGenerateCodeForMaterialCategories( - Boolean generateCodeForMaterialCategories) { + public void setGenerateCodeForMaterialCategories(Boolean generateCodeForMaterialCategories) { this.generateCodeForMaterialCategories = generateCodeForMaterialCategories; } @@ -287,8 +264,7 @@ public class Configuration extends BaseEntity { this.scenariosVisible = scenariosVisible; } - public void setGenerateCodeForBaseCalendars( - Boolean generateCodeForBaseCalendars) { + public void setGenerateCodeForBaseCalendars(Boolean generateCodeForBaseCalendars) { this.generateCodeForBaseCalendars = generateCodeForBaseCalendars; } @@ -296,8 +272,7 @@ public class Configuration extends BaseEntity { return generateCodeForBaseCalendars; } - public void setGenerateCodeForWorkReportType( - Boolean generateCodeForWorkReportType) { + public void setGenerateCodeForWorkReportType(Boolean generateCodeForWorkReportType) { this.generateCodeForWorkReportType = generateCodeForWorkReportType; } @@ -305,8 +280,7 @@ public class Configuration extends BaseEntity { return generateCodeForWorkReportType; } - public void setGenerateCodeForCalendarExceptionType( - Boolean generateCodeForCalendarExceptionType) { + public void setGenerateCodeForCalendarExceptionType(Boolean generateCodeForCalendarExceptionType) { this.generateCodeForCalendarExceptionType = generateCodeForCalendarExceptionType; } @@ -314,8 +288,7 @@ public class Configuration extends BaseEntity { return this.generateCodeForCalendarExceptionType; } - public void setGenerateCodeForCostCategory( - Boolean generateCodeForCostCategory) { + public void setGenerateCodeForCostCategory(Boolean generateCodeForCostCategory) { this.generateCodeForCostCategory = generateCodeForCostCategory; } @@ -336,14 +309,14 @@ public class Configuration extends BaseEntity { } public ProgressType getProgressType() { - return (progressType == null) ? ProgressType.SPREAD_PROGRESS - : progressType; + return (progressType == null) ? ProgressType.SPREAD_PROGRESS : progressType; } public void setCompanyLogoURL(String companyLogoURL) { if (companyLogoURL != null) { companyLogoURL = companyLogoURL.trim(); } + this.companyLogoURL = companyLogoURL; } @@ -351,84 +324,68 @@ public class Configuration extends BaseEntity { return companyLogoURL; } - public void setChangedDefaultAdminPassword( - Boolean changedDefaultAdminPassword) { + public void setChangedDefaultAdminPassword(Boolean changedDefaultAdminPassword) { this.changedDefaultAdminPassword = changedDefaultAdminPassword; } public Boolean getChangedDefaultAdminPassword() { - return changedDefaultAdminPassword == null ? false - : changedDefaultAdminPassword; + return changedDefaultAdminPassword == null ? false : changedDefaultAdminPassword; } - public void setChangedDefaultWsreaderPassword( - Boolean changedDefaultWsreaderPassword) { + public void setChangedDefaultWsreaderPassword(Boolean changedDefaultWsreaderPassword) { this.changedDefaultWsreaderPassword = changedDefaultWsreaderPassword; } public Boolean getChangedDefaultWsreaderPassword() { - return changedDefaultWsreaderPassword != null ? changedDefaultWsreaderPassword - : false; + return changedDefaultWsreaderPassword != null ? changedDefaultWsreaderPassword : false; } - public void setChangedDefaultWswriterPassword( - Boolean changedDefaultWswriterPassword) { + public void setChangedDefaultWswriterPassword(Boolean changedDefaultWswriterPassword) { this.changedDefaultWswriterPassword = changedDefaultWswriterPassword; } public Boolean getChangedDefaultWswriterPassword() { - return changedDefaultWswriterPassword != null ? changedDefaultWswriterPassword - : false; + return changedDefaultWswriterPassword != null ? changedDefaultWswriterPassword : false; } - public void setChangedDefaultWssubcontractingPassword( - Boolean changedDefaultWssubcontractingPassword) { + public void setChangedDefaultWssubcontractingPassword(Boolean changedDefaultWssubcontractingPassword) { this.changedDefaultWssubcontractingPassword = changedDefaultWssubcontractingPassword; } public Boolean getChangedDefaultWssubcontractingPassword() { - return changedDefaultWssubcontractingPassword != null ? changedDefaultWssubcontractingPassword - : false; + return changedDefaultWssubcontractingPassword != null ? changedDefaultWssubcontractingPassword : false; } - public void setChangedDefaultManagerPassword( - Boolean changedDefaultManagerPassword) { + public void setChangedDefaultManagerPassword(Boolean changedDefaultManagerPassword) { this.changedDefaultManagerPassword = changedDefaultManagerPassword; } public Boolean getChangedDefaultManagerPassword() { - return changedDefaultManagerPassword != null ? changedDefaultManagerPassword - : false; + return changedDefaultManagerPassword != null ? changedDefaultManagerPassword : false; } - public void setChangedDefaultHresourcesPassword( - Boolean changedDefaultHresourcesPassword) { + public void setChangedDefaultHresourcesPassword(Boolean changedDefaultHresourcesPassword) { this.changedDefaultHresourcesPassword = changedDefaultHresourcesPassword; } public Boolean getChangedDefaultHresourcesPassword() { - return changedDefaultHresourcesPassword != null ? changedDefaultHresourcesPassword - : false; + return changedDefaultHresourcesPassword != null ? changedDefaultHresourcesPassword : false; } - public void setChangedDefaultOutsourcingPassword( - Boolean changedDefaultOutsourcingPassword) { + public void setChangedDefaultOutsourcingPassword(Boolean changedDefaultOutsourcingPassword) { this.changedDefaultOutsourcingPassword = changedDefaultOutsourcingPassword; } public Boolean getChangedDefaultOutsourcingPassword() { - return changedDefaultOutsourcingPassword != null ? changedDefaultOutsourcingPassword - : false; + return changedDefaultOutsourcingPassword != null ? changedDefaultOutsourcingPassword : false; } - public void setChangedDefaultReportsPassword( - Boolean changedDefaultReportsPassword) { + public void setChangedDefaultReportsPassword(Boolean changedDefaultReportsPassword) { this.changedDefaultReportsPassword = changedDefaultReportsPassword; } public Boolean getChangedDefaultReportsPassword() { - return changedDefaultReportsPassword != null ? changedDefaultReportsPassword - : false; + return changedDefaultReportsPassword != null ? changedDefaultReportsPassword : false; } public LDAPConfiguration getLdapConfiguration() { @@ -455,13 +412,11 @@ public class Configuration extends BaseEntity { this.checkNewVersionEnabled = checkNewVersionEnabled; } - public boolean isAllowToGatherUsageStatsEnabled() { - return allowToGatherUsageStatsEnabled != null ? allowToGatherUsageStatsEnabled - : false; + public boolean isAllowedToGatherUsageStatsEnabled() { + return allowToGatherUsageStatsEnabled != null ? allowToGatherUsageStatsEnabled : false; } - public void setAllowToGatherUsageStatsEnabled( - boolean allowToGatherUsageStatsEnabled) { + public void setAllowToGatherUsageStatsEnabled(boolean allowToGatherUsageStatsEnabled) { this.allowToGatherUsageStatsEnabled = allowToGatherUsageStatsEnabled; } @@ -487,8 +442,7 @@ public class Configuration extends BaseEntity { return personalTimesheetsTypeOfWorkHours; } - public void setPersonalTimesheetsTypeOfWorkHours( - TypeOfWorkHours typeOfWorkHours) { + public void setPersonalTimesheetsTypeOfWorkHours(TypeOfWorkHours typeOfWorkHours) { personalTimesheetsTypeOfWorkHours = typeOfWorkHours; } @@ -504,8 +458,7 @@ public class Configuration extends BaseEntity { return personalTimesheetsPeriodicity; } - public void setPersonalTimesheetsPeriodicity( - PersonalTimesheetsPeriodicityEnum personalTimesheetsPeriodicity) { + public void setPersonalTimesheetsPeriodicity(PersonalTimesheetsPeriodicityEnum personalTimesheetsPeriodicity) { this.personalTimesheetsPeriodicity = personalTimesheetsPeriodicity; } @@ -538,6 +491,7 @@ public class Configuration extends BaseEntity { public String getRepositoryLocation() { return repositoryLocation; } + public void setRepositoryLocation(String repositoryLocation) { this.repositoryLocation = repositoryLocation; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationBootstrap.java index 633b4b85f..5789f41c9 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationBootstrap.java @@ -35,17 +35,18 @@ import org.libreplan.business.common.daos.IConfigurationDAO; import org.libreplan.business.common.daos.IEntitySequenceDAO; import org.libreplan.business.workingday.EffortDuration; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** - * Creates a default {@link Configuration} with default values. It also creates - * a default {@link OrderSequence}. + * Creates a default {@link Configuration} with default values. + * * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) @BootstrapOrder(-1) public class ConfigurationBootstrap implements IConfigurationBootstrap { @@ -94,9 +95,9 @@ public class ConfigurationBootstrap implements IConfigurationBootstrap { } private Map> initEntitySequences() { - Map> entitySequences = new HashMap>(); + Map> entitySequences = new HashMap<>(); for (EntityNameEnum entityName : EntityNameEnum.values()) { - entitySequences.put(entityName, new ArrayList()); + entitySequences.put(entityName, new ArrayList<>()); } for (EntitySequence entitySequence : entitySequenceDAO.getAll()) { entitySequences.get(entitySequence.getEntityName()).add( diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationTypeOfWorkHoursBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationTypeOfWorkHoursBootstrap.java index c3404b920..12aea39e7 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationTypeOfWorkHoursBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConfigurationTypeOfWorkHoursBootstrap.java @@ -27,29 +27,28 @@ import org.libreplan.business.costcategories.entities.TypeOfWorkHours; import org.libreplan.business.costcategories.entities.TypeOfWorkHoursBootstrap; import org.libreplan.business.workreports.entities.PredefinedWorkReportTypes; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** - * Fills the attributes {@link Configuration#personalTimesheetsTypeOfWorkHours} - * and {@link JiraConfiguration#jiraConnectorTypeOfWorkHours} with a default - * values.
+ * Fills the attributes {@link Configuration#personalTimesheetsTypeOfWorkHours} with a default values. + *
* * If possible it uses the "Default" {@link TypeOfWorkHours}, but if it doesn't - * exist, it uses the first {@link TypeOfWorkHours} found.
+ * exist, it uses the first {@link TypeOfWorkHours} found. + *
* * This bootstrap have to be executed after {@link ConfigurationBootstrap} and - * {@link TypeOfWorkHoursBootstrap}, this is why it's marked with - * {@link BootstrapOrder BootstrapOrder(1)}. + * {@link TypeOfWorkHoursBootstrap}, this is why it's marked with {@link BootstrapOrder BootstrapOrder(1)}. * * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) @BootstrapOrder(1) -public class ConfigurationTypeOfWorkHoursBootstrap implements - IConfigurationTypeOfWorkHoursBootstrap { +public class ConfigurationTypeOfWorkHoursBootstrap implements IConfigurationTypeOfWorkHoursBootstrap { @Autowired private IConfigurationDAO configurationDAO; @@ -63,13 +62,10 @@ public class ConfigurationTypeOfWorkHoursBootstrap implements Configuration configuration = configurationDAO.getConfiguration(); // TypeOfWorkHoursBootstrap creates the TypeOfWorkHours objects - // specified by PredefinedWorkReportTypes if there isn't any - // TypeOfWorkHours in the database + // specified by PredefinedWorkReportTypes if there isn't any TypeOfWorkHours in the database TypeOfWorkHours typeOfWorkHours; try { - typeOfWorkHours = typeOfWorkHoursDAO - .findUniqueByName(PredefinedWorkReportTypes.DEFAULT - .getName()); + typeOfWorkHours = typeOfWorkHoursDAO.findUniqueByName(PredefinedWorkReportTypes.DEFAULT.getName()); } catch (InstanceNotFoundException e) { typeOfWorkHours = typeOfWorkHoursDAO.findActive().get(0); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConnectorBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConnectorBootstrap.java index e765df7a2..c90909b48 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConnectorBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/ConnectorBootstrap.java @@ -21,6 +21,7 @@ package org.libreplan.business.common.entities; import org.libreplan.business.common.daos.IConnectorDAO; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -32,7 +33,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class ConnectorBootstrap implements IConnectorBootstrap { @Autowired diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobClassNameEnum.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobClassNameEnum.java index 539f13c14..64a4dec6c 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobClassNameEnum.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/JobClassNameEnum.java @@ -21,11 +21,10 @@ package org.libreplan.business.common.entities; /** - * Defines the job class package and name to be used as data type in - * {@link JobSchedulerConfiguration} + * Defines the job class package and name to be used as data type in {@link JobSchedulerConfiguration}. * * @author Miciele Ghiorghis - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public enum JobClassNameEnum { @@ -43,7 +42,7 @@ public enum JobClassNameEnum { private String packageName; private String name; - private JobClassNameEnum(String packageName, String name) { + JobClassNameEnum(String packageName, String name) { this.packageName = packageName; this.name = name; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/Limits.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/Limits.java index 1b2a041d1..3b76e2cac 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/Limits.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/Limits.java @@ -26,11 +26,9 @@ import org.libreplan.business.common.BaseEntity; * This class is intended to work as a Hibernate component. * It represents the limit that can be modified only in database. * - * Created by - * @author Vova Perebykivskiy - * on 17.12.2015. + * @author Created by Vova Perebykivskyi on 17.12.2015. */ -public class Limits extends BaseEntity{ +public class Limits extends BaseEntity { private String type; diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectorProperties.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectorProperties.java index 9611c0384..24ef7a27e 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectorProperties.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectorProperties.java @@ -22,12 +22,11 @@ package org.libreplan.business.common.entities; import static org.libreplan.business.i18n.I18nHelper._; /** - * Simply class to keep constants of {@link ConnectorProperty properties} for - * LibrePlan {@link Connector connectors}. + * Simply class to keep constants of {@link ConnectorProperty properties} for LibrePlan {@link Connector connectors}. * * @author Miciele Ghiorghis * @author Manuel Rego Casasnovas - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public class PredefinedConnectorProperties { diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectors.java b/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectors.java index b647d1c0d..c8b413507 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectors.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/entities/PredefinedConnectors.java @@ -23,35 +23,32 @@ import java.util.Arrays; import java.util.List; /** - * Defines the LibrePlan {@link Connector Connectors} together with its - * configuration properties. + * Defines the LibrePlan {@link Connector Connectors} together with its configuration properties. * * @author Miciele Ghiorghis * @author Manuel Rego Casasnovas - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public enum PredefinedConnectors { TIM("Tim", - ConnectorProperty.create(PredefinedConnectorProperties.ACTIVATED, "N"), - ConnectorProperty.create(PredefinedConnectorProperties.SERVER_URL, ""), - ConnectorProperty.create(PredefinedConnectorProperties.USERNAME, ""), - ConnectorProperty.create(PredefinedConnectorProperties.PASSWORD, ""), - ConnectorProperty.create(PredefinedConnectorProperties.TIM_NR_DAYS_TIMESHEET, "7"), - ConnectorProperty.create(PredefinedConnectorProperties.TIM_NR_DAYS_ROSTER, "90"), - ConnectorProperty.create(PredefinedConnectorProperties.TIM_PRODUCTIVITY_FACTOR, "100"), - ConnectorProperty.create( - PredefinedConnectorProperties.TIM_DEPARTAMENTS_IMPORT_ROSTER, - "0")), + ConnectorProperty.create(PredefinedConnectorProperties.ACTIVATED, "N"), + ConnectorProperty.create(PredefinedConnectorProperties.SERVER_URL, ""), + ConnectorProperty.create(PredefinedConnectorProperties.USERNAME, ""), + ConnectorProperty.create(PredefinedConnectorProperties.PASSWORD, ""), + ConnectorProperty.create(PredefinedConnectorProperties.TIM_NR_DAYS_TIMESHEET, "7"), + ConnectorProperty.create(PredefinedConnectorProperties.TIM_NR_DAYS_ROSTER, "90"), + ConnectorProperty.create(PredefinedConnectorProperties.TIM_PRODUCTIVITY_FACTOR, "100"), + ConnectorProperty.create(PredefinedConnectorProperties.TIM_DEPARTAMENTS_IMPORT_ROSTER, "0")), + JIRA("Jira", - ConnectorProperty.create(PredefinedConnectorProperties.ACTIVATED, "N"), - ConnectorProperty.create(PredefinedConnectorProperties.SERVER_URL, ""), - ConnectorProperty.create(PredefinedConnectorProperties.USERNAME, ""), - ConnectorProperty.create(PredefinedConnectorProperties.PASSWORD, ""), - ConnectorProperty - .create(PredefinedConnectorProperties.JIRA_LABELS, ""), - ConnectorProperty.create( - PredefinedConnectorProperties.JIRA_HOURS_TYPE, "Default")), + ConnectorProperty.create(PredefinedConnectorProperties.ACTIVATED, "N"), + ConnectorProperty.create(PredefinedConnectorProperties.SERVER_URL, ""), + ConnectorProperty.create(PredefinedConnectorProperties.USERNAME, ""), + ConnectorProperty.create(PredefinedConnectorProperties.PASSWORD, ""), + ConnectorProperty.create(PredefinedConnectorProperties.JIRA_LABELS, ""), + ConnectorProperty.create(PredefinedConnectorProperties.JIRA_HOURS_TYPE, "Default")), + EMAIL("E-mail", ConnectorProperty.create(PredefinedConnectorProperties.ACTIVATED, "N"), ConnectorProperty.create(PredefinedConnectorProperties.PROTOCOL, ""), @@ -64,10 +61,10 @@ public enum PredefinedConnectors { ); private String name; + private List properties; - private PredefinedConnectors(String name, - ConnectorProperty... properties) { + PredefinedConnectors(String name, ConnectorProperty... properties) { this.name = name; this.properties = Arrays.asList(properties); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/exceptions/InstanceException.java b/libreplan-business/src/main/java/org/libreplan/business/common/exceptions/InstanceException.java index fee77139c..8108f6c79 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/exceptions/InstanceException.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/exceptions/InstanceException.java @@ -26,19 +26,17 @@ package org.libreplan.business.common.exceptions; * It contains a message, the key of the instance, and its class name. * * @author Fernando Bellas Permuy - * */ @SuppressWarnings("serial") public abstract class InstanceException extends Exception { - private Object key; - private String className; + private final Object key; - protected InstanceException(String specificMessage, Object key, - String className) { + private final String className; - super(specificMessage + " (key = '" + key + "' - className = '" + - className + "')"); + protected InstanceException(String specificMessage, Object key, String className) { + + super(specificMessage + " (key = '" + key + "' - className = '" + className + "')"); this.key = key; this.className = className; diff --git a/libreplan-business/src/main/java/org/libreplan/business/costcategories/entities/TypeOfWorkHoursBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/costcategories/entities/TypeOfWorkHoursBootstrap.java index 096b6a44c..6fec3b44c 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/costcategories/entities/TypeOfWorkHoursBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/costcategories/entities/TypeOfWorkHoursBootstrap.java @@ -23,6 +23,7 @@ import org.libreplan.business.common.daos.IEntitySequenceDAO; import org.libreplan.business.common.entities.EntityNameEnum; import org.libreplan.business.costcategories.daos.ITypeOfWorkHoursDAO; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -33,7 +34,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Ignacio Díaz Teijido */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class TypeOfWorkHoursBootstrap implements ITypeOfWorkHoursBootstrap { @Autowired @@ -46,10 +47,8 @@ public class TypeOfWorkHoursBootstrap implements ITypeOfWorkHoursBootstrap { @Transactional public void loadRequiredData() { if (typeOfWorkHoursDAO.findActive().size() == 0) { - for (PredefinedTypeOfWorkHours predefinedTypeOfWorkHours : PredefinedTypeOfWorkHours - .values()) { - TypeOfWorkHours typeOfWorkHours = predefinedTypeOfWorkHours - .getTypeOfWorkHours(); + for (PredefinedTypeOfWorkHours predefinedTypeOfWorkHours : PredefinedTypeOfWorkHours.values()) { + TypeOfWorkHours typeOfWorkHours = predefinedTypeOfWorkHours.getTypeOfWorkHours(); typeOfWorkHours.setCodeAutogenerated(true); typeOfWorkHours .setCode(entitySequenceDAO diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java index a1f2a7872..40d154307 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailNotificationDAO.java @@ -30,7 +30,7 @@ import java.util.List; /** * Dao for {@link EmailNotification} * - * @author Created by Vova Perebykivskiy on 19.10.2015. + * @author Created by Vova Perebykivskyi on 19.10.2015. */ @Repository public class EmailNotificationDAO diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java index 7c8439cae..976d31444 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/EmailTemplateDAO.java @@ -33,7 +33,7 @@ import java.util.List; /** * DAO for {@link EmailTemplate} * - * @author Created by Vova Perebykivskiy on 24.09.2015. + * @author Created by Vova Perebykivskyi on 24.09.2015. */ @Repository public class EmailTemplateDAO extends GenericDAOHibernate implements IEmailTemplateDAO{ @@ -68,7 +68,6 @@ public class EmailTemplateDAO extends GenericDAOHibernate i public void delete(EmailTemplate entity) { try { remove(entity.getId()); - } catch (InstanceNotFoundException ignored) { - } + } catch (InstanceNotFoundException ignored) {} } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java index a23a69265..9cc28dc5a 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailNotificationDAO.java @@ -28,7 +28,7 @@ import java.util.List; /** * Contract for {@link EmailNotificationDAO} * - * @author Created by Vova Perebykivskiy on 19.10.2015. + * @author Created by Vova Perebykivskyi on 19.10.2015. */ public interface IEmailNotificationDAO extends IGenericDAO { diff --git a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java index e2d7ebf3a..953111007 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/email/daos/IEmailTemplateDAO.java @@ -28,9 +28,9 @@ import java.util.List; /** * DAO interface for the EmailTemplate entity. - * Contract for {@link EmailTemplateDAO} + * Contract for {@link EmailTemplateDAO}. * - * @author Created by Vova Perebykivskiy on 29.09.2015. + * @author Created by Vova Perebykivskyi on 29.09.2015. */ public interface IEmailTemplateDAO extends IGenericDAO{ diff --git a/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/EndDateCommunication.java b/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/EndDateCommunication.java index 45d0bb506..d314a8eab 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/EndDateCommunication.java +++ b/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/EndDateCommunication.java @@ -24,7 +24,7 @@ import java.util.Date; import org.libreplan.business.common.BaseEntity; /** - * Entity EndDateCommunication + * Entity EndDateCommunication. * * @author Susana Montes Pedreira */ @@ -46,8 +46,7 @@ public class EndDateCommunication extends BaseEntity { this.setSaveDate(new Date()); } - protected EndDateCommunication(Date saveDate, Date endDate, - Date communicationDate) { + protected EndDateCommunication(Date saveDate, Date endDate, Date communicationDate) { this.setSaveDate(saveDate); this.setEndDate(endDate); this.setCommunicationDate(communicationDate); @@ -61,8 +60,7 @@ public class EndDateCommunication extends BaseEntity { return create(new EndDateCommunication(endDate)); } - public static EndDateCommunication create(Date saveDate, Date endDate, - Date communicationDate) { + public static EndDateCommunication create(Date saveDate, Date endDate, Date communicationDate) { return create(new EndDateCommunication(saveDate, endDate, communicationDate)); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/ExternalCompany.java b/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/ExternalCompany.java index 359e2939e..8d612bb31 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/ExternalCompany.java +++ b/libreplan-business/src/main/java/org/libreplan/business/externalcompanies/entities/ExternalCompany.java @@ -32,12 +32,11 @@ import org.libreplan.business.externalcompanies.daos.IExternalCompanyDAO; import org.libreplan.business.users.entities.User; /** - * Entity ExternalCompany + * Entity ExternalCompany. * * @author Jacobo Aragunde Perez */ -public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, - Comparable { +public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, Comparable { private String name; @@ -60,7 +59,7 @@ public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, protected ExternalCompany() {} public static ExternalCompany create() { - return (ExternalCompany) create(new ExternalCompany()); + return create(new ExternalCompany()); } protected ExternalCompany(String name, String nif) { @@ -69,7 +68,7 @@ public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, } public static ExternalCompany create(String name, String nif) { - return (ExternalCompany) create(new ExternalCompany(name,nif)); + return create(new ExternalCompany(name,nif)); } public void setName(String name) { @@ -154,8 +153,8 @@ public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, return !dao.existsByNameInAnotherTransaction(name); } else { try { - ExternalCompany company = - dao.findUniqueByNameInAnotherTransaction(name); + ExternalCompany company = dao.findUniqueByNameInAnotherTransaction(name); + return company.getId().equals(getId()); } catch (InstanceNotFoundException e) { return true; @@ -171,8 +170,8 @@ public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, return !dao.existsByNifInAnotherTransaction(nif); } else { try { - ExternalCompany company = - dao.findUniqueByNifInAnotherTransaction(nif); + ExternalCompany company = dao.findUniqueByNifInAnotherTransaction(nif); + return company.getId().equals(getId()); } catch (InstanceNotFoundException e) { return true; @@ -182,13 +181,9 @@ public class ExternalCompany extends BaseEntity implements IHumanIdentifiable, @AssertTrue(message = "interaction fields are empty and company is marked as interact with applications") public boolean isInteractionFieldsNotEmptyIfNeededConstraint() { - if (!interactsWithApplications) { - return true; - } + return !interactsWithApplications || !StringUtils.isEmpty(appURI) && !StringUtils.isEmpty(ourCompanyLogin) && + !StringUtils.isEmpty(ourCompanyPassword); - return !StringUtils.isEmpty(appURI) - && !StringUtils.isEmpty(ourCompanyLogin) - && !StringUtils.isEmpty(ourCompanyPassword); } @Override diff --git a/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java b/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java index 6f827b1da..1c7070aa1 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java +++ b/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java @@ -23,18 +23,23 @@ package org.libreplan.business.i18n; /** - * This class provides a function to mark strings to be translated. Real - * translation have to be done in webapp module depending on user language and + * This class provides a function to mark strings to be translated. + * Real translation have to be done in webapp module depending on user language and * not done here depending on server language. * * @author Manuel Rego Casasnovas */ public class I18nHelper { - private I18nHelper() { - - } + private I18nHelper() {} + //TODO It should be changed since JDK9. + /** + * Use of '_' as an identifier might not be supported in releases after Java SE 8. + * + * @param str + * @return Text depends on locale + */ public static String _(String text) { return text; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/labels/entities/LabelBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/labels/entities/LabelBootstrap.java index 616126d3c..62e5ec700 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/labels/entities/LabelBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/labels/entities/LabelBootstrap.java @@ -23,6 +23,7 @@ import org.libreplan.business.common.daos.IEntitySequenceDAO; import org.libreplan.business.common.entities.EntityNameEnum; import org.libreplan.business.labels.daos.ILabelTypeDAO; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -33,7 +34,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Ignacio Díaz Teijido */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class LabelBootstrap implements ILabelBootstrap { @Autowired @@ -45,17 +46,16 @@ public class LabelBootstrap implements ILabelBootstrap { @Override @Transactional public void loadRequiredData() { - if (labelTypeDAO.getAll().size() == 0) { + if (labelTypeDAO.getAll().isEmpty()) { LabelType priorityType = LabelType.create("Priority"); priorityType.setCodeAutogenerated(true); - priorityType.setCode(entitySequenceDAO - .getNextEntityCodeWithoutTransaction(EntityNameEnum.LABEL)); + priorityType.setCode(entitySequenceDAO.getNextEntityCodeWithoutTransaction(EntityNameEnum.LABEL)); + for (PredefinedLabels predefinedLabel : PredefinedLabels.values()) { Label label = predefinedLabel.getLabel(); priorityType.addLabel(label); } - priorityType.generateLabelCodes(entitySequenceDAO - .getNumberOfDigitsCode(EntityNameEnum.LABEL)); + priorityType.generateLabelCodes(entitySequenceDAO.getNumberOfDigitsCode(EntityNameEnum.LABEL)); labelTypeDAO.save(priorityType); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/logs/entities/IssueLog.java b/libreplan-business/src/main/java/org/libreplan/business/logs/entities/IssueLog.java index bc42efd9a..c791379c5 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/logs/entities/IssueLog.java +++ b/libreplan-business/src/main/java/org/libreplan/business/logs/entities/IssueLog.java @@ -27,22 +27,30 @@ import org.libreplan.business.common.daos.IIntegrationEntityDAO; import org.libreplan.business.users.entities.User; /** - * IssueLog entity, represents parameters to be able to administrate issues that - * come up in the project - * + * IssueLog entity, represents parameters to be able to administrate issues that come up in the project. + * * @author Misha Gozhda */ public class IssueLog extends ProjectLog { private IssueTypeEnum type = IssueTypeEnum.getDefault(); + private String status = "LOW"; + private LowMediumHighEnum priority = LowMediumHighEnum.getDefault(); + private LowMediumHighEnum severity = LowMediumHighEnum.getDefault(); + private Date dateRaised; + private User createdBy; + private String assignedTo; + private Date dateResolved; + private Date deadline; + private String notes; @@ -151,7 +159,6 @@ public class IssueLog extends ProjectLog { @Override protected IIntegrationEntityDAO getIntegrationEntityDAO() { - return (IIntegrationEntityDAO) Registry - .getIssueLogDAO(); + return Registry.getIssueLogDAO(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/logs/entities/RiskLog.java b/libreplan-business/src/main/java/org/libreplan/business/logs/entities/RiskLog.java index f4d387a28..b5d23590e 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/logs/entities/RiskLog.java +++ b/libreplan-business/src/main/java/org/libreplan/business/logs/entities/RiskLog.java @@ -27,24 +27,34 @@ import org.libreplan.business.users.entities.User; import java.util.Date; /** - * RiskLog entity, represents parameters to be able to administrate risks that - * come up in the project - * + * RiskLog entity, represents parameters to be able to administrate risks that come up in the project. + * * @author Misha Gozhda */ public class RiskLog extends ProjectLog { private String projectName; + private String status; + private LowMediumHighEnum probability = LowMediumHighEnum.getDefault(); + private LowMediumHighEnum impact = LowMediumHighEnum.getDefault(); + private Date dateCreated; + private User createdBy; + private String counterMeasures; + private String contingency; + private String responsible; + private Date actionWhen; + private String notes; + private RiskScoreStatesEnum score = RiskScoreStatesEnum.getDefault(); public static RiskLog create() { @@ -169,8 +179,7 @@ public class RiskLog extends ProjectLog { @Override protected IIntegrationEntityDAO getIntegrationEntityDAO() { - return (IIntegrationEntityDAO) Registry - .getRiskLogDAO(); + return Registry.getRiskLogDAO(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/MaterialCategoryBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/MaterialCategoryBootstrap.java index 764403353..4a0541e1a 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/MaterialCategoryBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/MaterialCategoryBootstrap.java @@ -27,6 +27,7 @@ import org.libreplan.business.common.entities.EntityNameEnum; import org.libreplan.business.materials.daos.IMaterialCategoryDAO; import org.libreplan.business.materials.entities.MaterialCategory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -37,7 +38,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class MaterialCategoryBootstrap implements IMaterialCategoryBootstrap { @Autowired @@ -49,13 +50,10 @@ public class MaterialCategoryBootstrap implements IMaterialCategoryBootstrap { @Override @Transactional public void loadRequiredData() { - for (PredefinedMaterialCategories predefinedMaterialCategory : PredefinedMaterialCategories - .values()) { + for (PredefinedMaterialCategories predefinedMaterialCategory : PredefinedMaterialCategories.values()) { if (!materialCategoryDAO - .existsMaterialCategoryWithNameInAnotherTransaction(predefinedMaterialCategory - .getName())) { - MaterialCategory materialCategory = predefinedMaterialCategory - .createMaterialCategory(); + .existsMaterialCategoryWithNameInAnotherTransaction(predefinedMaterialCategory.getName())) { + MaterialCategory materialCategory = predefinedMaterialCategory.createMaterialCategory(); materialCategory .setCode(entitySequenceDAO .getNextEntityCodeWithoutTransaction(EntityNameEnum.MATERIAL_CATEGORY)); diff --git a/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/UnitTypeBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/UnitTypeBootstrap.java index 55dd6acfb..fcb06e622 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/UnitTypeBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/materials/bootstrap/UnitTypeBootstrap.java @@ -28,17 +28,19 @@ import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.materials.daos.IUnitTypeDAO; import org.libreplan.business.materials.entities.UnitType; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * Creates the bootstrap of the predefined {@link UnitType}. + * * @author Susana Montes Pedreira */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class UnitTypeBootstrap implements IDataBootstrap { @Autowired @@ -52,24 +54,21 @@ public class UnitTypeBootstrap implements IDataBootstrap { @Transactional @Override public void loadRequiredData() { - for (PredefinedUnitTypes predefinedUnitType : PredefinedUnitTypes - .values()) { - UnitType type = null; + for (PredefinedUnitTypes predefinedUnitType : PredefinedUnitTypes.values()) { + UnitType type; try { type = unitTypeDAO .findUniqueByNameInAnotherTransaction(predefinedUnitType .getMeasure()); } catch (InstanceNotFoundException e) { type = predefinedUnitType.createUnitType(); - type - .setCode(entitySequenceDAO - .getNextEntityCodeWithoutTransaction(EntityNameEnum.UNIT_TYPE)); + type.setCode(entitySequenceDAO + .getNextEntityCodeWithoutTransaction(EntityNameEnum.UNIT_TYPE)); type.setCodeAutogenerated(true); unitTypeDAO.save(type); } - if (predefinedUnitType - .equals(PredefinedUnitTypes.defaultUnitType())) { - defaultUnitType = type; + if (predefinedUnitType.equals(PredefinedUnitTypes.defaultUnitType())) { + UnitTypeBootstrap.defaultUnitType = type; } } } @@ -78,6 +77,7 @@ public class UnitTypeBootstrap implements IDataBootstrap { if (defaultUnitType.isNewObject()) { defaultUnitType.dontPoseAsTransientObjectAnymore(); } + return defaultUnitType; } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/materials/entities/MaterialCategory.java b/libreplan-business/src/main/java/org/libreplan/business/materials/entities/MaterialCategory.java index 21dfcb2eb..ccfe0450d 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/materials/entities/MaterialCategory.java +++ b/libreplan-business/src/main/java/org/libreplan/business/materials/entities/MaterialCategory.java @@ -40,30 +40,31 @@ import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.materials.daos.IMaterialCategoryDAO; /** - * MaterialCategory entity + * MaterialCategory entity. * * @author Jacobo Aragunde Perez - * */ public class MaterialCategory extends IntegrationEntity { - public static List getAllMaterialsFrom( - Collection categories) { - List result = new ArrayList(); + public static List getAllMaterialsFrom(Collection categories) { + List result = new ArrayList<>(); for (MaterialCategory each : categories) { result.addAll(each.getMaterials()); } + return result; } public static List getAllMaterialsWithoutAutogeneratedCodeFrom( Collection categories) { - List result = new ArrayList(); + + List result = new ArrayList<>(); for (MaterialCategory each : categories) { if (!each.isCodeAutogenerated()) { result.addAll(each.getMaterials()); } } + return result; } @@ -86,12 +87,13 @@ public class MaterialCategory extends IntegrationEntity { } public static MaterialCategory create(String name) { - return (MaterialCategory) create(new MaterialCategory(name)); + return create(new MaterialCategory(name)); } public static MaterialCategory createUnvalidated(String code, String name) { MaterialCategory materialCategory = create(new MaterialCategory(), code); materialCategory.name = name; + return materialCategory; } @@ -153,32 +155,34 @@ public class MaterialCategory extends IntegrationEntity { @AssertTrue(message="material category name has to be unique. It is already used") public boolean isUniqueNameConstraint() { boolean result; + if (isNewObject()) { result = !existsMaterialCategoryWithTheName(); } else { result = isIfExistsTheExistentMaterialCategoryThisOne(); } + return result; } private boolean existsMaterialCategoryWithTheName() { IMaterialCategoryDAO materialCategoryDAO = Registry.getMaterialCategoryDAO(); + return materialCategoryDAO.existsMaterialCategoryWithNameInAnotherTransaction(name); } private boolean isIfExistsTheExistentMaterialCategoryThisOne() { IMaterialCategoryDAO materialCategoryDAO = Registry.getMaterialCategoryDAO(); try { - MaterialCategory materialCategory = - materialCategoryDAO.findUniqueByNameInAnotherTransaction(name); + MaterialCategory materialCategory = materialCategoryDAO.findUniqueByNameInAnotherTransaction(name); + return materialCategory.getId().equals(getId()); } catch (InstanceNotFoundException e) { return true; } } - public Material getMaterialByCode(String code) - throws InstanceNotFoundException { + public Material getMaterialByCode(String code) throws InstanceNotFoundException { if (StringUtils.isBlank(code)) { throw new InstanceNotFoundException(code, Material.class.getName()); @@ -194,12 +198,10 @@ public class MaterialCategory extends IntegrationEntity { } - public MaterialCategory getSubcategoryByCode(String code) - throws InstanceNotFoundException { + public MaterialCategory getSubcategoryByCode(String code) throws InstanceNotFoundException { if (StringUtils.isBlank(code)) { - throw new InstanceNotFoundException(code, MaterialCategory.class - .getName()); + throw new InstanceNotFoundException(code, MaterialCategory.class.getName()); } for (MaterialCategory s : this.subcategories) { @@ -208,8 +210,7 @@ public class MaterialCategory extends IntegrationEntity { } } - throw new InstanceNotFoundException(code, MaterialCategory.class - .getName()); + throw new InstanceNotFoundException(code, MaterialCategory.class.getName()); } @@ -221,11 +222,13 @@ public class MaterialCategory extends IntegrationEntity { @SuppressWarnings("unused") @AssertTrue(message = "Subcategory names must be unique.") public boolean isUniqueSubcategoryNameConstraint() { - Set subcategoriesNames = new HashSet(); + Set subcategoriesNames = new HashSet<>(); + for (MaterialCategory mc : this.getAllSubcategories()) { + if (!StringUtils.isBlank(mc.getName())) { - String name = StringUtils.deleteWhitespace(mc.getName() - .toLowerCase()); + String name = StringUtils.deleteWhitespace(mc.getName().toLowerCase()); + if (subcategoriesNames.contains(name)) { return false; } else { @@ -240,42 +243,43 @@ public class MaterialCategory extends IntegrationEntity { public boolean isNonRepeatedMaterialCategoryCodesConstraint() { Set allSubcategories = getAllSubcategories(); allSubcategories.add(this); + return getFirstRepeatedCode(allSubcategories) == null; } private Set getAllSubcategories() { - Set result = new HashSet(subcategories); + Set result = new HashSet<>(subcategories); for (MaterialCategory subcategory : subcategories) { result.addAll(subcategory.getAllSubcategories()); } + return result; } @AssertTrue(message = "There are repeated material codes") public boolean isNonRepeatedMaterialCodesConstraint() { Set allMaterials = getAllMaterials(); + return getFirstRepeatedCode(allMaterials) == null; } private Set getAllMaterials() { - Set result = new HashSet(materials); + Set result = new HashSet<>(materials); for (MaterialCategory subcategory : subcategories) { result.addAll(subcategory.getAllMaterials()); } + return result; } public void generateMaterialCodes(int numberOfDigits) { for (Material material : this.getMaterials()) { - if ((material.getCode() == null) || (material.getCode().isEmpty()) - || (!material.getCode().startsWith(this.getCode()))) { + if ((material.getCode() == null) || (material.getCode().isEmpty()) || + (!material.getCode().startsWith(this.getCode()))) { + this.incrementLastMaterialSequenceCode(); - String materialCode = EntitySequence.formatValue( - numberOfDigits, this.getLastMaterialSequenceCode()); - material - .setCode(this.getCode() - + EntitySequence.CODE_SEPARATOR_CHILDREN - + materialCode); + String materialCode = EntitySequence.formatValue(numberOfDigits, this.getLastMaterialSequenceCode()); + material.setCode(this.getCode() + EntitySequence.CODE_SEPARATOR_CHILDREN + materialCode); } } } @@ -284,6 +288,7 @@ public class MaterialCategory extends IntegrationEntity { if (this.lastMaterialSequenceCode == null) { this.lastMaterialSequenceCode = 0; } + this.lastMaterialSequenceCode++; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderFileDAO.java b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderFileDAO.java index 6b7c4ee35..0b60df2da 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderFileDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderFileDAO.java @@ -26,9 +26,7 @@ import org.libreplan.business.orders.entities.OrderFile; import java.util.List; /** - * Created by - * @author Vova Perebykivskiy - * on 12.24.2015. + * @author Created by Vova Perebykivskyi on 12.24.2015. */ public interface IOrderFileDAO extends IGenericDAO { diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java index a9788f8dc..fcd1219e6 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java @@ -64,7 +64,7 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** - * Dao for {@link Order} + * DAO for {@link Order}. * * @author Óscar González Fernández * @author Lorenzo Tilve Álvaro @@ -72,8 +72,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) -public class OrderDAO extends IntegrationEntityDAO implements - IOrderDAO { +public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { @Autowired private ITaskSourceDAO taskSourceDAO; @@ -90,6 +89,8 @@ public class OrderDAO extends IntegrationEntityDAO implements @Autowired private IAdHocTransactionService transactionService; + private String STATE_PARAMETER = "state"; + @Override public List getOrders() { return list(Order.class); @@ -111,34 +112,39 @@ public class OrderDAO extends IntegrationEntityDAO implements return false; } - private boolean matchFilterCriterion(OrderElement orderElement, - List criterions) { + private boolean matchFilterCriterion(OrderElement orderElement, List criterions) { if ((criterions != null) && (!criterions.isEmpty())) { - List orderElements = new ArrayList(); + + List orderElements = new ArrayList<>(); orderElements.add(orderElement); List tasks = this.getFilteredTask(orderElements, criterions); - return (!tasks.isEmpty()); + + return !tasks.isEmpty(); } return true; } @Transactional(readOnly = true) public List getOrderCostsPerResource( - List orders, Date startingDate, Date endingDate, + List orders, + Date startingDate, + Date endingDate, List criterions) { - String strQuery = "SELECT new org.libreplan.business.reports.dtos.OrderCostsPerResourceDTO(worker, wrl) " - + "FROM Worker worker, WorkReportLine wrl " - + "LEFT OUTER JOIN wrl.resource resource " - + "WHERE resource.id = worker.id "; + String strQuery = "SELECT new org.libreplan.business.reports.dtos.OrderCostsPerResourceDTO(worker, wrl) " + + "FROM Worker worker, WorkReportLine wrl " + + "LEFT OUTER JOIN wrl.resource resource " + + "WHERE resource.id = worker.id "; // Set date range if (startingDate != null && endingDate != null) { strQuery += "AND wrl.date BETWEEN :startingDate AND :endingDate "; } + if (startingDate != null && endingDate == null) { strQuery += "AND wrl.date >= :startingDate "; } + if (startingDate == null && endingDate != null) { strQuery += "AND wrl.date <= :endingDate "; } @@ -151,34 +157,32 @@ public class OrderDAO extends IntegrationEntityDAO implements if (startingDate != null) { query.setParameter("startingDate", startingDate); } + if (endingDate != null) { query.setParameter("endingDate", endingDate); } List list = query.list(); - List filteredList = new ArrayList(); + List filteredList = new ArrayList<>(); for (OrderCostsPerResourceDTO each : list) { Order order = loadOrderAvoidingProxyFor(each.getOrderElement()); // Apply filtering - if (matchFilterCriterion(each.getOrderElement(), criterions) - && isOrderContained(order, orders)) { + if (matchFilterCriterion(each.getOrderElement(), criterions) && isOrderContained(order, orders)) { // Attach ordername value each.setOrderName(order.getName()); each.setOrderCode(order.getCode()); + // Attach calculated pricePerHour - BigDecimal pricePerHour = CostCategoryDAO - .getPriceByResourceDateAndHourType(each.getWorker(), - new LocalDate(each.getDate()), each - .getHoursTypeCode()); + BigDecimal pricePerHour = CostCategoryDAO.getPriceByResourceDateAndHourType( + each.getWorker(), new LocalDate(each.getDate()), each.getHoursTypeCode()); + if (pricePerHour == null) { - for (TypeOfWorkHours defaultprice : typeOfWorkHoursDAO - .list(TypeOfWorkHours.class)) { - if (defaultprice.getCode().equals( - each.getHoursTypeCode())) { + for (TypeOfWorkHours defaultprice : typeOfWorkHoursDAO.list(TypeOfWorkHours.class)) { + if (defaultprice.getCode().equals(each.getHoursTypeCode())) { pricePerHour = defaultprice.getDefaultPrice(); } } @@ -194,21 +198,24 @@ public class OrderDAO extends IntegrationEntityDAO implements @Override public List getOrdersByReadAuthorization(User user) { - if (user.isInRole(UserRole.ROLE_SUPERUSER) - || user.isInRole(UserRole.ROLE_READ_ALL_PROJECTS) - || user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { + if (user.isInRole(UserRole.ROLE_SUPERUSER) || + user.isInRole(UserRole.ROLE_READ_ALL_PROJECTS) || + user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { + return getOrders(); } else { - List orders = new ArrayList(); + List orders = new ArrayList<>(); List authorizations = orderAuthorizationDAO.listByUserAndItsProfiles(user); for(OrderAuthorization authorization : authorizations) { + if (authorization.getAuthorizationType() == OrderAuthorizationType.READ_AUTHORIZATION || - authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION) { + authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION) { Order order = authorization.getOrder(); - if(!orders.contains(order)) { - order.getName(); //this lines forces the load of the basic attributes of the order + if (!orders.contains(order)) { + // These lines forces the load of the basic attributes of the order + order.getName(); orders.add(order); } } @@ -218,11 +225,15 @@ public class OrderDAO extends IntegrationEntityDAO implements } private List getOrdersByReadAuthorizationBetweenDatesByLabelsCriteriaCustomerAndState( - User user, Date startDate, Date endDate, List

    - *
  • - * {@link ResourceAllocation#allocating(List)}. - * {@link AllocationsSpecified#untilAllocating(int) untiAllocating(int)}
  • - *
  • {@link ResourceAllocation#allocating(List)}. - * {@link AllocationsSpecified#allocateOnTaskLength() allocateOnTaskLength}
  • - *
  • - * {@link ResourceAllocation#allocating(List)}. - * {@link AllocationsSpecified#allocateUntil(LocalDate) - * allocateUntil(LocalDate)}
  • + *
  • + * {@link ResourceAllocation#allocating(List)}. + * {@link AllocationsSpecified#untilAllocating(int) untiAllocating(int)} + *
  • + *
  • + * {@link ResourceAllocation#allocating(List)}. + * {@link AllocationsSpecified#allocateOnTaskLength() allocateOnTaskLength} + *
  • + *
  • + * {@link ResourceAllocation#allocating(List)}. + * {@link AllocationsSpecified#allocateUntil(LocalDate) allocateUntil(LocalDate)} + *
  • *
- * */ public static class AllocationsSpecified { @@ -263,25 +296,22 @@ public abstract class ResourceAllocation extends private final Task task; - public AllocationsSpecified( - List resourceAllocations) { + public AllocationsSpecified(List resourceAllocations) { Validate.notNull(resourceAllocations); Validate.notEmpty(resourceAllocations); Validate.noNullElements(resourceAllocations); checkNoOneHasNullTask(resourceAllocations); checkAllHaveSameTask(resourceAllocations); checkNoAllocationWithZeroResourcesPerDay(resourceAllocations); + this.allocations = resourceAllocations; - this.task = resourceAllocations.get(0).getBeingModified() - .getTask(); + this.task = resourceAllocations.get(0).getBeingModified().getTask(); } - private static void checkNoAllocationWithZeroResourcesPerDay( - List allocations) { + private static void checkNoAllocationWithZeroResourcesPerDay(List allocations) { for (ResourcesPerDayModification r : allocations) { if (isZero(r.getGoal().getAmount())) { - throw new IllegalArgumentException( - "all resources per day must be no zero"); + throw new IllegalArgumentException("all resources per day must be no zero"); } } } @@ -290,50 +320,41 @@ public abstract class ResourceAllocation extends return amount.movePointRight(amount.scale()).intValue() == 0; } - private static void checkNoOneHasNullTask( - List allocations) { + private static void checkNoOneHasNullTask(List allocations) { for (ResourcesPerDayModification resourcesPerDayModification : allocations) { - if (resourcesPerDayModification - .getBeingModified().getTask() == null) { - throw new IllegalArgumentException( - "all allocations must have task"); + if (resourcesPerDayModification.getBeingModified().getTask() == null) { + throw new IllegalArgumentException("all allocations must have task"); } } } - private static void checkAllHaveSameTask( - List resourceAllocations) { + private static void checkAllHaveSameTask(List resourceAllocations) { Task task = null; for (ResourcesPerDayModification r : resourceAllocations) { if (task == null) { task = r.getBeingModified().getTask(); } + if (!task.equals(r.getBeingModified().getTask())) { - throw new IllegalArgumentException( - "all allocations must belong to the same task"); + throw new IllegalArgumentException("all allocations must belong to the same task"); } } } public interface INotFulfilledReceiver { - public void cantFulfill(ResourcesPerDayModification allocationAttempt, CapacityResult capacityResult); + void cantFulfill(ResourcesPerDayModification allocationAttempt, CapacityResult capacityResult); } public IntraDayDate untilAllocating(EffortDuration effort) { return untilAllocating(Direction.FORWARD, effort); } - public IntraDayDate untilAllocating(Direction direction, - EffortDuration effort) { + public IntraDayDate untilAllocating(Direction direction, EffortDuration effort) { return untilAllocating(direction, effort, doNothing()); } private static INotFulfilledReceiver doNothing() { - return new INotFulfilledReceiver() { - @Override - public void cantFulfill(ResourcesPerDayModification allocationAttempt, CapacityResult capacityResult) { - } - }; + return (allocationAttempt, capacityResult) -> {}; } public IntraDayDate untilAllocating(EffortDuration effort, final INotFulfilledReceiver receiver) { @@ -356,10 +377,17 @@ public abstract class ResourceAllocation extends Task task = AllocationsSpecified.this.task; allocation.setIntendedResourcesPerDay(resourcesPerDay); + if ( isForwardScheduling() ) { - allocation.resetAllAllocationAssignmentsTo(dayAssignments, task.getIntraDayStartDate(), resultDate); + + allocation.resetAllAllocationAssignmentsTo( + dayAssignments, task.getIntraDayStartDate(), resultDate); + } else { - allocation.resetAllAllocationAssignmentsTo(dayAssignments, resultDate, task.getIntraDayEndDate()); + + allocation.resetAllAllocationAssignmentsTo( + dayAssignments, resultDate, task.getIntraDayEndDate()); + } allocation.updateResourcesPerDay(); } @@ -374,6 +402,7 @@ public abstract class ResourceAllocation extends ResourcesPerDay resourcesPerDay = resourcesPerDayModification.getGoal(); AvailabilityTimeLine availability = resourcesPerDayModification.getAvailability(); getDirection().limitAvailabilityOn(availability, dateFromWhichToAllocate); + return ThereAreHoursOnWorkHoursCalculator.thereIsAvailableCapacityFor( calendar, availability, @@ -389,62 +418,62 @@ public abstract class ResourceAllocation extends @Override protected void markUnsatisfied( - ResourcesPerDayModification allocationAttempt, - CapacityResult capacityResult) { + ResourcesPerDayModification allocationAttempt, CapacityResult capacityResult) { + allocationAttempt.getBeingModified().markAsUnsatisfied(); receiver.cantFulfill(allocationAttempt, capacityResult); } }; IntraDayDate result = allocator.untilAllocating(toAllocate); + if (result == null) { - // allocation could not be done - return direction == Direction.FORWARD ? task - .getIntraDayEndDate() : task.getIntraDayStartDate(); + // Allocation could not be done + return direction == Direction.FORWARD ? task.getIntraDayEndDate() : task.getIntraDayStartDate(); } return result; } public void allocateOnTaskLength() { - AllocatorForTaskDurationAndSpecifiedResourcesPerDay allocator = new AllocatorForTaskDurationAndSpecifiedResourcesPerDay( - allocations); + AllocatorForTaskDurationAndSpecifiedResourcesPerDay allocator = + new AllocatorForTaskDurationAndSpecifiedResourcesPerDay(allocations); + allocator.allocateOnTaskLength(); } public void allocateUntil(IntraDayDate endExclusive) { - AllocatorForTaskDurationAndSpecifiedResourcesPerDay allocator = new AllocatorForTaskDurationAndSpecifiedResourcesPerDay( - allocations); + AllocatorForTaskDurationAndSpecifiedResourcesPerDay allocator = + new AllocatorForTaskDurationAndSpecifiedResourcesPerDay(allocations); + allocator.allocateUntil(endExclusive); } public void allocateFromEndUntil(IntraDayDate start) { - AllocatorForTaskDurationAndSpecifiedResourcesPerDay allocator = new AllocatorForTaskDurationAndSpecifiedResourcesPerDay( - allocations); + AllocatorForTaskDurationAndSpecifiedResourcesPerDay allocator = + new AllocatorForTaskDurationAndSpecifiedResourcesPerDay(allocations); + allocator.allocateFromEndUntil(start); } } - public static HoursAllocationSpecified allocatingHours( - List effortsModifications) { - effortsModifications = new ArrayList( - effortsModifications); + public static HoursAllocationSpecified allocatingHours(List effortsModifications) { + effortsModifications = new ArrayList<>(effortsModifications); sortBySpecificFirst(effortsModifications); + return new HoursAllocationSpecified(effortsModifications); } /** * Needed for doing fluent interface calls: *
    - *
  • - * {@link ResourceAllocation#allocatingHours(List)}. - * {@link HoursAllocationSpecified#allocateUntil(LocalDate) - * allocateUntil(LocalDate)}
  • - *
  • - * {@link ResourceAllocation#allocatingHours(List)}. - * {@link HoursAllocationSpecified#allocate() allocate()}
  • - * + *
  • + * {@link ResourceAllocation#allocatingHours(List)} + * .{@link HoursAllocationSpecified#allocateUntil(LocalDate) allocateUntil(LocalDate)} + *
  • + *
  • + * {@link ResourceAllocation#allocatingHours(List)}.{@link HoursAllocationSpecified#allocate() allocate()} + *
  • *
- * */ public static class HoursAllocationSpecified { @@ -483,71 +512,31 @@ public abstract class ResourceAllocation extends } - private Task task; - - private AssignmentFunction assignmentFunction; - - @OnCopy(Strategy.SHARE) - private ResourcesPerDay resourcesPerDay; - - @OnCopy(Strategy.SHARE) - private ResourcesPerDay intendedResourcesPerDay; - - private Integer intendedTotalHours; - - private Set derivedAllocations = new HashSet(); - - @OnCopy(Strategy.SHARE_COLLECTION_ELEMENTS) - private Set limitingResourceQueueElements = new HashSet(); - - @OnCopy(Strategy.SHARE) - private EffortDuration intendedTotalAssignment = zero(); - - @OnCopy(Strategy.SHARE) - private EffortDuration intendedNonConsolidatedEffort = zero(); - - private IOnDayAssignmentRemoval dayAssignmenteRemoval = new DoNothing(); - public interface IOnDayAssignmentRemoval { - public void onRemoval(ResourceAllocation allocation, - DayAssignment assignment); + void onRemoval(ResourceAllocation allocation, DayAssignment assignment); } public static class DoNothing implements IOnDayAssignmentRemoval { - @Override - public void onRemoval( - ResourceAllocation allocation, DayAssignment assignment) { - } + public void onRemoval(ResourceAllocation allocation, DayAssignment assignment) {} } - public static class DetachDayAssignmentOnRemoval implements - IOnDayAssignmentRemoval { - + public static class DetachDayAssignmentOnRemoval implements IOnDayAssignmentRemoval { @Override - public void onRemoval(ResourceAllocation allocation, - DayAssignment assignment) { + public void onRemoval(ResourceAllocation allocation, DayAssignment assignment) { assignment.detach(); } } - public void setOnDayAssignmentRemoval( - IOnDayAssignmentRemoval dayAssignmentRemoval) { + public void setOnDayAssignmentRemoval(IOnDayAssignmentRemoval dayAssignmentRemoval) { Validate.notNull(dayAssignmentRemoval); this.dayAssignmenteRemoval = dayAssignmentRemoval; } /** - * Constructor for hibernate. Do not use! - */ - public ResourceAllocation() { - this.assignmentsState = buildFromDBState(); - } - - /** - * Returns the associated resources from the day assignments of this - * {@link ResourceAllocation}. + * Returns the associated resources from the day assignments of this {@link ResourceAllocation}. + * * @return the associated resources with no repeated elements */ public abstract List getAssociatedResources(); @@ -585,7 +574,7 @@ public abstract class ResourceAllocation extends } /** - * Returns the last specified resources per day + * Returns the last specified resources per day. */ public ResourcesPerDay getIntendedResourcesPerDay() { return intendedResourcesPerDay; @@ -593,15 +582,12 @@ public abstract class ResourceAllocation extends private ResourcesPerDay getReassignationResourcesPerDay() { ResourcesPerDay intended = getIntendedResourcesPerDay(); - if ( intended != null ) { - return intended; - } - return getResourcesPerDay(); + + return intended != null ? intended : getResourcesPerDay(); } public boolean areIntendedResourcesPerDaySatisfied() { - CalculatedValue calculatedValue = getTask().getCalculatedValue(); - return calculatedValue == CalculatedValue.RESOURCES_PER_DAY || + return getTask().getCalculatedValue() == CalculatedValue.RESOURCES_PER_DAY || Objects.equals(getNonConsolidatedResourcePerDay(), getIntendedResourcesPerDay()); } @@ -654,29 +640,33 @@ public abstract class ResourceAllocation extends T on(GenericResourceAllocation genericAllocation); } - public static T visit(ResourceAllocation allocation, - IVisitor visitor) { + public static T visit(ResourceAllocation allocation, IVisitor visitor) { Validate.notNull(allocation); Validate.notNull(visitor); + if (allocation instanceof GenericResourceAllocation) { GenericResourceAllocation generic = (GenericResourceAllocation) allocation; + return visitor.on(generic); } else if (allocation instanceof SpecificResourceAllocation) { SpecificResourceAllocation specific = (SpecificResourceAllocation) allocation; + return visitor.on(specific); } throw new RuntimeException("can't handle: " + allocation.getClass()); } - public abstract ResourcesPerDayModification withDesiredResourcesPerDay( - ResourcesPerDay resourcesPerDay); + /** + * This method is in use. + */ + public abstract ResourcesPerDayModification withDesiredResourcesPerDay(ResourcesPerDay resourcesPerDay); public final ResourcesPerDayModification asResourcesPerDayModification() { if ( getReassignationResourcesPerDay().isZero() ) { return null; } - return visit(this, new IVisitor() { + return visit(this, new IVisitor() { @Override public ResourcesPerDayModification on(SpecificResourceAllocation specificAllocation) { return ResourcesPerDayModification.create(specificAllocation, getReassignationResourcesPerDay()); @@ -692,12 +682,13 @@ public abstract class ResourceAllocation extends }); } - public final EffortModification asHoursModification(){ + public final EffortModification asHoursModification() { return visit(this, new IVisitor() { @Override public EffortModification on(GenericResourceAllocation genericAllocation) { - return EffortModification.create(genericAllocation, getEffortForReassignation(), getAssociatedResources()); + return EffortModification.create( + genericAllocation, getEffortForReassignation(), getAssociatedResources()); } @Override @@ -711,9 +702,8 @@ public abstract class ResourceAllocation extends public interface IEffortDistributor { /** - * It does not add the created assigments to the underlying allocation. + * It does not add the created assignments to the underlying allocation. * It just distributes them. - * */ List distributeForDay(PartialDay day, EffortDuration effort); } @@ -736,7 +726,7 @@ public abstract class ResourceAllocation extends IntraDayDate startInclusive, IntraDayDate endExclusive) { - List assignmentsCreated = new ArrayList(); + List assignmentsCreated = new ArrayList<>(); for (PartialDay day : getDays(startInclusive, endExclusive)) { EffortDuration durationForDay = calculateTotalToDistribute(day, resourcesPerDay); assignmentsCreated.addAll(distributeForDay(day, durationForDay)); @@ -747,6 +737,7 @@ public abstract class ResourceAllocation extends @Override public IAllocateResourcesPerDay resourcesPerDayUntil(IntraDayDate end) { IntraDayDate startInclusive = getStartSpecifiedByTask(); + return new AllocateResourcesPerDayOnInterval(startInclusive, end); } @@ -754,13 +745,14 @@ public abstract class ResourceAllocation extends public IAllocateResourcesPerDay resourcesPerDayFromEndUntil(IntraDayDate start) { IntraDayDate startInclusive = IntraDayDate.max(start, getStartSpecifiedByTask()); IntraDayDate endDate = task.getIntraDayEndDate(); + return new AllocateResourcesPerDayOnInterval(startInclusive, endDate); } private Iterable getDays(IntraDayDate startInclusive, IntraDayDate endExclusive) { checkStartLessOrEqualToEnd(startInclusive, endExclusive); - Iterable daysUntil = startInclusive.daysUntil(endExclusive); - return daysUntil; + + return startInclusive.daysUntil(endExclusive); } private final class AllocateResourcesPerDayOnInterval implements IAllocateResourcesPerDay { @@ -786,24 +778,28 @@ public abstract class ResourceAllocation extends @Override public IAllocateEffortOnInterval onIntervalWithinTask(final LocalDate start, final LocalDate end) { checkStartLessOrEqualToEnd(start, end); + return new OnSubIntervalAllocator(new AllocationIntervalInsideTask(start, end)); } @Override public IAllocateEffortOnInterval onIntervalWithinTask(IntraDayDate start, IntraDayDate end) { checkStartLessOrEqualToEnd(start, end); + return new OnSubIntervalAllocator(new AllocationIntervalInsideTask(start, end)); } @Override public IAllocateEffortOnInterval onInterval(final LocalDate startInclusive, final LocalDate endExclusive) { checkStartLessOrEqualToEnd(startInclusive, endExclusive); + return new OnSubIntervalAllocator(new AllocationInterval(startInclusive, endExclusive)); } @Override public IAllocateEffortOnInterval onInterval(IntraDayDate start, IntraDayDate end) { checkStartLessOrEqualToEnd(start, end); + return new OnSubIntervalAllocator(new AllocationInterval(start, end)); } @@ -837,16 +833,15 @@ public abstract class ResourceAllocation extends List rightSlice = interval.getRightSlice(durationsByDay); AvailabilityTimeLine availability = getAvailability(); - List assignments = - createAssignments(interval, availability, rightSlice.toArray(new EffortDuration[rightSlice.size()])); + List assignments = createAssignments( + interval, availability, rightSlice.toArray(new EffortDuration[rightSlice.size()])); interval.resetAssignments(assignments); } @Override public IAllocateEffortOnInterval fromStartUntil(final IntraDayDate end) { - final AllocationInterval interval = new AllocationInterval(getStartSpecifiedByTask(), end); - return getIAllocateEffortOnInterval(interval); + return getIAllocateEffortOnInterval(new AllocationInterval(getStartSpecifiedByTask(), end)); } private IAllocateEffortOnInterval getIAllocateEffortOnInterval(final AllocationInterval interval) { @@ -875,6 +870,7 @@ public abstract class ResourceAllocation extends @Override public IAllocateEffortOnInterval fromEndUntil(IntraDayDate start) { final AllocationInterval interval = new AllocationInterval(start, task.getIntraDayEndDate()); + return new IAllocateEffortOnInterval() { @Override @@ -915,12 +911,10 @@ public abstract class ResourceAllocation extends AvailabilityTimeLine availability, EffortDuration[] durationsEachDay) { - List result = new ArrayList(); + List result = new ArrayList<>(); int i = 0; - for (PartialDay day : getDays(interval.getStartInclusive(), - interval.getEndExclusive())) { - // if all days are not available, it would try to assign - // them anyway, preventing it with a check + for (PartialDay day : getDays(interval.getStartInclusive(), interval.getEndExclusive())) { + // If all days are not available, it would try to assign them anyway, preventing it with a check if ( availability.isValid(day.getDate()) ) { result.addAll(distributeForDay(day, durationsEachDay[i])); } @@ -940,7 +934,7 @@ public abstract class ResourceAllocation extends } private List onlyNonZeroHours(List assignmentsCreated) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (T each : assignmentsCreated) { if ( !each.getDuration().isZero() ) { result.add(each); @@ -954,7 +948,7 @@ public abstract class ResourceAllocation extends Iterable days, EffortDuration duration) { - List capacities = new ArrayList(); + List capacities = new ArrayList<>(); for (PartialDay each : days) { capacities.add(getCapacity(availability, each)); } @@ -963,24 +957,12 @@ public abstract class ResourceAllocation extends } private Capacity getCapacity(AvailabilityTimeLine availability, PartialDay day) { - if ( availability.isValid(day.getDate()) ) { - return getCapacityAt(day); - } else { - return Capacity.create(zero()).notOverAssignableWithoutLimit(); - } + return availability.isValid(day.getDate()) + ? getCapacityAt(day) + : Capacity.create(zero()).notOverAssignableWithoutLimit(); } protected abstract Capacity getCapacityAt(PartialDay each); - - private Share getShareAt(PartialDay day, AvailabilityTimeLine availability) { - if ( availability.isValid(day.getDate()) ) { - EffortDuration capacityAtDay = getAllocationCalendar().getCapacityOn(day); - return new Share(-capacityAtDay.getSeconds()); - } else { - return new Share(Integer.MAX_VALUE); - } - } - } public void markAsUnsatisfied() { @@ -997,16 +979,11 @@ public abstract class ResourceAllocation extends } public boolean isSatisfied() { - if (isCompletelyConsolidated()) { - return hasAssignments(); - } else { - return !getNonConsolidatedAssignments().isEmpty(); - } + return isCompletelyConsolidated() ? hasAssignments() : !getNonConsolidatedAssignments().isEmpty(); } private boolean isCompletelyConsolidated() { - return task.getConsolidation() != null - && task.getConsolidation().isCompletelyConsolidated(); + return task.getConsolidation() != null && task.getConsolidation().isCompletelyConsolidated(); } public boolean isUnsatisfied() { @@ -1073,7 +1050,7 @@ public abstract class ResourceAllocation extends } public List getRightSlice(List original) { - List result = new ArrayList(original); + List result = new ArrayList<>(original); final int numberOfDaysToFill = originalStart.numberOfDaysUntil(originalEnd); for (int i = 0; i < numberOfDaysToFill - original.size(); i++) { result.add(zero()); @@ -1136,19 +1113,17 @@ public abstract class ResourceAllocation extends updateAssignments(interval, assignmentsCreated); // The resource allocation cannot grow beyond the start of the task. - // This - // is guaranteed by IntervalInsideTask. It also cannot shrink from the - // original size, this is guaranteed by originalStart + // This is guaranteed by IntervalInsideTask. + // It also cannot shrink from the original size, this is guaranteed by originalStart. getDayAssignmentsState().setIntraDayStart(IntraDayDate.min(originalStart, interval.getStartInclusive())); - // The resource allocation cannot grow beyond the end of the task. This - // is guaranteed by IntervalInsideTask. It also cannot shrink from the - // original size, this is guaranteed by originalEnd + // The resource allocation cannot grow beyond the end of the task. + // This is guaranteed by IntervalInsideTask. + // It also cannot shrink from the original size, this is guaranteed by originalEnd. getDayAssignmentsState().setIntraDayEnd(IntraDayDate.max(originalEnd, interval.getEndExclusive())); } private void updateAssignments(AllocationInterval interval, List assignmentsCreated) { - removingAssignments(withoutConsolidated(interval.getAssignmentsOnInterval())); addingAssignments(assignmentsCreated); @@ -1170,21 +1145,25 @@ public abstract class ResourceAllocation extends LocalDate startConsideringAssignments = getStartConsideringAssignments(); IntraDayDate start = IntraDayDate.startOfDay(startConsideringAssignments); + if ( interval.getStartInclusive().areSameDay(startConsideringAssignments) ) { start = interval.getStartInclusive(); } + getDayAssignmentsState().setIntraDayStart(start); LocalDate endConsideringAssignments = getEndDateGiven(getAssignments()); IntraDayDate end = IntraDayDate.startOfDay(endConsideringAssignments); + if ( interval.getEndExclusive().areSameDay(endConsideringAssignments) ) { end = interval.getEndExclusive(); } + getDayAssignmentsState().setIntraDayEnd(end); } private static List withoutConsolidated(List assignments) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (T each : assignments) { if ( !each.isConsolidated() ) { result.add(each); @@ -1198,7 +1177,7 @@ public abstract class ResourceAllocation extends } private List withoutAlreadyPresent(Collection assignments) { - if( assignments.isEmpty() ){ + if ( assignments.isEmpty() ) { return Collections.emptyList(); } @@ -1206,7 +1185,7 @@ public abstract class ResourceAllocation extends LocalDate max = Collections.max(assignments, DayAssignment.byDayComparator()).getDay(); Set daysPresent = DayAssignment.byDay(getAssignments(min, max.plusDays(1))).keySet(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (T each : assignments) { if ( !daysPresent.contains(each.getDay()) ) { result.add(each); @@ -1216,7 +1195,7 @@ public abstract class ResourceAllocation extends } public void removeLimitingDayAssignments() { - resetAssignmentsTo(Collections. emptyList()); + resetAssignmentsTo(Collections.emptyList()); } @SuppressWarnings("unchecked") @@ -1270,28 +1249,18 @@ public abstract class ResourceAllocation extends private IntraDayDate startFor(LocalDate dayDate) { IntraDayDate start = getIntraDayStartDate(); - if ( start.getDate().equals(dayDate) ) { - return start; - } else { - return IntraDayDate.startOfDay(dayDate); - } + + return start.getDate().equals(dayDate) ? start : IntraDayDate.startOfDay(dayDate); } private IntraDayDate endFor(LocalDate assignmentDate) { IntraDayDate end = getIntraDayEndDate(); - if ( end.getDate().equals(assignmentDate) ) { - return end; - } else { - return IntraDayDate.startOfDay(assignmentDate).nextDayAtStart(); - } + + return end.getDate().equals(assignmentDate) ? end : IntraDayDate.startOfDay(assignmentDate).nextDayAtStart(); } private static T avoidNull(T value, T defaultValue) { - if ( value != null ) { - return value; - } else { - return defaultValue; - } + return value != null ? value : defaultValue; } public ICalendar getAllocationCalendar() { @@ -1299,16 +1268,14 @@ public abstract class ResourceAllocation extends } private ICalendar getTaskCalendar() { - if ( getTask().getCalendar() == null ) { - return SameWorkHoursEveryDay.getDefaultWorkingDay(); - } else { - return getTask().getCalendar(); - } + return getTask().getCalendar() == null ? SameWorkHoursEveryDay.getDefaultWorkingDay() : getTask().getCalendar(); } - protected abstract ICalendar getCalendarGivenTaskCalendar( - ICalendar taskCalendar); + protected abstract ICalendar getCalendarGivenTaskCalendar(ICalendar taskCalendar); + /** + * This method is in use. + */ protected abstract Class getDayAssignmentType(); public ResourceAllocation copy(Scenario scenario) { @@ -1325,6 +1292,7 @@ public abstract class ResourceAllocation extends copy.task = task; copy.assignmentFunction = assignmentFunction; copy.intendedResourcesPerDay = intendedResourcesPerDay; + return copy; } @@ -1336,31 +1304,26 @@ public abstract class ResourceAllocation extends TransientState result = new TransientState(initialAssignments); result.setIntraDayStart(start); result.setIntraDayEnd(end); + return result; } private Set getUnorderedFor(Scenario scenario) { IDayAssignmentsContainer container = retrieveContainerFor(scenario); - if ( container == null ) { - return new HashSet(); - } - return container.getDayAssignments(); + + return container == null ? new HashSet<>() : container.getDayAssignments(); } private IntraDayDate getIntraDayStartDateFor(Scenario scenario) { IDayAssignmentsContainer container = retrieveContainerFor(scenario); - if ( container == null ) { - return null; - } - return container.getIntraDayStart(); + + return container == null ? null : container.getIntraDayStart(); } private IntraDayDate getIntraDayEndFor(Scenario scenario) { IDayAssignmentsContainer container = retrieveContainerFor(scenario); - if ( container == null ) { - return null; - } - return container.getIntraDayEnd(); + + return container == null ? null : container.getIntraDayEnd(); } abstract ResourceAllocation createCopy(Scenario scenario); @@ -1370,13 +1333,13 @@ public abstract class ResourceAllocation extends } /** - * If {@link AssignmentFunction} is null, it's just set and nothing is - * applied + * If {@link AssignmentFunction} is null, it's just set and nothing is applied. * * @param assignmentFunction */ public void setAssignmentFunctionAndApplyIfNotFlat(AssignmentFunction assignmentFunction) { this.assignmentFunction = assignmentFunction; + if ( this.assignmentFunction != null ) { this.assignmentFunction.applyTo(this); } @@ -1398,9 +1361,6 @@ public abstract class ResourceAllocation extends return intendedNonConsolidatedEffort; } - @OnCopy(Strategy.IGNORE) - private DayAssignmentsState assignmentsState; - protected DayAssignmentsState getDayAssignmentsState() { return assignmentsState; } @@ -1425,8 +1385,8 @@ public abstract class ResourceAllocation extends } /** - * It can be null. It allows to mark that the allocation is started in a - * point within a day instead of the start of the day + * It can be null. + * It allows to mark that the allocation is started in a point within a day instead of the start of the day. */ abstract IntraDayDate getIntraDayStart(); @@ -1441,8 +1401,8 @@ public abstract class ResourceAllocation extends /** - * It can be null. It allows to mark that the allocation is finished in - * a point within a day instead of taking the whole day + * It can be null. + * It allows to mark that the allocation is finished in a point within a day instead of taking the whole day. */ abstract IntraDayDate getIntraDayEnd(); @@ -1507,11 +1467,9 @@ public abstract class ResourceAllocation extends } /** - * Override if necessary to do extra actions + * Override if necessary to do extra actions. */ - protected void copyTransientPropertiesIfAppropiateTo( - DayAssignmentsState newStateForScenario) { - } + protected void copyTransientPropertiesIfAppropiateTo(DayAssignmentsState newStateForScenario) {} } protected abstract void setItselfAsParentFor(T dayAssignment); @@ -1525,7 +1483,7 @@ public abstract class ResourceAllocation extends private IntraDayDate intraDayEnd; TransientState(Collection assignments) { - this.assignments = new HashSet(assignments); + this.assignments = new HashSet<>(assignments); } @Override @@ -1534,8 +1492,7 @@ public abstract class ResourceAllocation extends } @Override - final protected void removeAssignments( - List assignments) { + final protected void removeAssignments(List assignments) { this.assignments.removeAll(assignments); } @@ -1570,19 +1527,16 @@ public abstract class ResourceAllocation extends this.intraDayEnd = intraDayEnd; } - protected void copyTransientPropertiesIfAppropiateTo( - DayAssignmentsState newStateForScenario) { + protected void copyTransientPropertiesIfAppropiateTo(DayAssignmentsState newStateForScenario) { newStateForScenario.resetTo(getUnorderedAssignments()); newStateForScenario.setIntraDayStart(getIntraDayStart()); newStateForScenario.setIntraDayEnd(getIntraDayEnd()); - }; + } } private DayAssignmentsState explicitlySpecifiedState(Scenario scenario) { - IDayAssignmentsContainer container; - container = retrieveOrCreateContainerFor(scenario); - return new ExplicitlySpecifiedScenarioState(container); + return new ExplicitlySpecifiedScenarioState(retrieveOrCreateContainerFor(scenario)); } protected abstract IDayAssignmentsContainer retrieveContainerFor(Scenario scenario); @@ -1590,11 +1544,13 @@ public abstract class ResourceAllocation extends protected abstract IDayAssignmentsContainer retrieveOrCreateContainerFor(Scenario scenario); /** * It uses the current scenario retrieved from {@link IScenarioManager} in - * order to return the assignments for that scenario. This state doesn't - * allow to update the current assignments for that scenario.
+ * order to return the assignments for that scenario. + * This state doesn't allow to update the current assignments for that scenario. + *
* Note that this implementation doesn't work well if the current scenario * is changed since the assignments are cached and the assignments for the - * previous one would be returned
+ * previous one would be returned. + *
*/ private class NoExplicitlySpecifiedScenario extends DayAssignmentsState { @@ -1625,8 +1581,7 @@ public abstract class ResourceAllocation extends @Override protected Collection getUnorderedAssignments() { - Scenario scenario = currentScenario(); - return retrieveOrCreateContainerFor(scenario).getDayAssignments(); + return retrieveOrCreateContainerFor(currentScenario()).getDayAssignments(); } private Scenario currentScenario() { @@ -1706,10 +1661,6 @@ public abstract class ResourceAllocation extends } - public int getConsolidatedHours() { - return getConsolidatedEffort().roundToHours(); - } - public EffortDuration getConsolidatedEffort() { return DayAssignment.sum(getConsolidatedAssignments()); } @@ -1719,11 +1670,7 @@ public abstract class ResourceAllocation extends } public EffortDuration getEffortForReassignation() { - if (isSatisfied()) { - return getNonConsolidatedEffort(); - } else { - return getIntendedNonConsolidatedEffort(); - } + return isSatisfied() ? getNonConsolidatedEffort() : getIntendedNonConsolidatedEffort(); } public EffortDuration getNonConsolidatedEffort() { @@ -1753,42 +1700,38 @@ public abstract class ResourceAllocation extends return calculateResourcesPerDayFromAssignments(getConsolidatedAssignments()); } - // just called for validation purposes. It must be public, otherwise if it's - // a proxy the call is not intercepted. + /** + * Just called for validation purposes. + * It must be public, otherwise if it's a proxy the call is not intercepted. + */ @NotNull public ResourcesPerDay getRawResourcesPerDay() { return resourcesPerDay; } public ResourcesPerDay getResourcesPerDay() { - if (resourcesPerDay == null) { - return ResourcesPerDay.amount(0); - } - return resourcesPerDay; + return resourcesPerDay == null ? ResourcesPerDay.amount(0) : resourcesPerDay; } public void createDerived(IWorkerFinder finder) { final List assignments = getAssignments(); - List result = new ArrayList(); + List result = new ArrayList<>(); List machines = Resource.machines(getAssociatedResources()); + for (Machine machine : machines) { - for (MachineWorkersConfigurationUnit each : machine - .getConfigurationUnits()) { - result.add(DerivedAllocationGenerator.generate(this, finder, - each, - assignments)); + for (MachineWorkersConfigurationUnit each : machine.getConfigurationUnits()) { + result.add(DerivedAllocationGenerator.generate(this, finder, each, assignments)); } } resetDerivedAllocationsTo(result); } /** - * Resets the derived allocations + * Resets the derived allocations. */ - private void resetDerivedAllocationsTo( - Collection derivedAllocations) { - // avoiding error: A collection with cascade="all-delete-orphan" was no - // longer referenced by the owning entity instance + private void resetDerivedAllocationsTo(Collection derivedAllocations) { + // Avoiding error: + // A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance. this.derivedAllocations.clear(); this.derivedAllocations.addAll(derivedAllocations); } @@ -1799,37 +1742,33 @@ public abstract class ResourceAllocation extends public LocalDate getStartConsideringAssignments() { List assignments = getAssignments(); - if (assignments.isEmpty()) { - return getStartDate(); - } - return assignments.get(0).getDay(); + + return assignments.isEmpty() ? getStartDate() : assignments.get(0).getDay(); } public LocalDate getStartDate() { IntraDayDate start = getIntraDayStartDate(); + return start != null ? start.getDate() : null; } private IntraDayDate getStartSpecifiedByTask() { IntraDayDate taskStart = task.getIntraDayStartDate(); - IntraDayDate firstDayNotConsolidated = getTask() - .getFirstDayNotConsolidated(); + IntraDayDate firstDayNotConsolidated = getTask().getFirstDayNotConsolidated(); + return IntraDayDate.max(taskStart, firstDayNotConsolidated); } public IntraDayDate getIntraDayStartDate() { - IntraDayDate intraDayStart = getDayAssignmentsState() - .getIntraDayStart(); - if (intraDayStart != null) { - return intraDayStart; - } - return task.getIntraDayStartDate(); + IntraDayDate intraDayStart = getDayAssignmentsState().getIntraDayStart(); + + return intraDayStart != null ? intraDayStart : task.getIntraDayStartDate(); } public LocalDate getEndDate() { IntraDayDate intraDayEndDate = getIntraDayEndDate(); - return intraDayEndDate != null ? intraDayEndDate.asExclusiveEnd() - : null; + + return intraDayEndDate != null ? intraDayEndDate.asExclusiveEnd() : null; } public IntraDayDate getIntraDayEndDate() { @@ -1839,86 +1778,69 @@ public abstract class ResourceAllocation extends } LocalDate l = getEndDateGiven(getAssignments()); - if (l == null) { - return task.getIntraDayEndDate(); - } - return IntraDayDate.startOfDay(l); + + return l == null ? task.getIntraDayEndDate() : IntraDayDate.startOfDay(l); } - private LocalDate getEndDateGiven( - List assignments) { + private LocalDate getEndDateGiven(List assignments) { if (assignments.isEmpty()) { return null; } DayAssignment lastAssignment = assignments.get(assignments.size() - 1); - return IntraDayDate.create(lastAssignment.getDay(), - lastAssignment.getDuration()).asExclusiveEnd(); + + return IntraDayDate.create(lastAssignment.getDay(), lastAssignment.getDuration()).asExclusiveEnd(); } public boolean isAlreadyFinishedBy(LocalDate date) { - if (getEndDate() == null) { - return false; - } - return getEndDate().compareTo(date) <= 0; + return getEndDate() != null && getEndDate().compareTo(date) <= 0; } private interface PredicateOnDayAssignment { boolean satisfiedBy(DayAssignment dayAssignment); } - public int getAssignedHours(final Resource resource, LocalDate start, - LocalDate endExclusive) { - return getAssignedEffort(resource, IntraDayDate.create(start, zero()), - IntraDayDate.create(endExclusive, zero())).roundToHours(); + public int getAssignedHours(final Resource resource, LocalDate start, LocalDate endExclusive) { + return getAssignedEffort( + resource, IntraDayDate.create(start, zero()), IntraDayDate.create(endExclusive, zero())).roundToHours(); } - public EffortDuration getAssignedEffort(final Resource resource, - IntraDayDate start, IntraDayDate endExclusive) { - List assignments = getAssingments(resource, - start.getDate(), endExclusive.asExclusiveEnd()); - return getAssignedDuration(assignments, start, endExclusive); + public EffortDuration getAssignedEffort(final Resource resource, IntraDayDate start, IntraDayDate endExclusive) { + return getAssignedDuration( + getAssingments(resource, start.getDate(), endExclusive.asExclusiveEnd()), start, endExclusive); } @Override public EffortDuration getAssignedDurationAt(Resource resource, LocalDate day) { IntraDayDate start = IntraDayDate.startOfDay(day); + return getAssignedEffort(resource, start, start.nextDayAtStart()); } - private List getAssingments(final Resource resource, - LocalDate startInclusive, LocalDate endExclusive) { - return filter(getAssignments(startInclusive, endExclusive), - new PredicateOnDayAssignment() { - @Override - public boolean satisfiedBy( - DayAssignment dayAssignment) { - return dayAssignment.isAssignedTo(resource); - } - }); + private List getAssingments( + final Resource resource, LocalDate startInclusive, LocalDate endExclusive) { + + return filter( + getAssignments(startInclusive, endExclusive), dayAssignment -> dayAssignment.isAssignedTo(resource)); } - public List getAssignments(IntraDayDate start, - IntraDayDate endExclusive) { + public List getAssignments(IntraDayDate start, IntraDayDate endExclusive) { return getAssignments(start.getDate(), endExclusive.asExclusiveEnd()); } - public List getAssignments(LocalDate start, - LocalDate endExclusive) { - return new ArrayList(DayAssignment.getAtInterval( - getAssignments(), start, endExclusive)); + public List getAssignments(LocalDate start, LocalDate endExclusive) { + return new ArrayList<>(DayAssignment.getAtInterval(getAssignments(), start, endExclusive)); } public int getAssignedHours(LocalDate start, LocalDate endExclusive) { - return getAssignedDuration(IntraDayDate.create(start, zero()), - IntraDayDate.create(endExclusive, zero())).roundToHours(); + return getAssignedDuration( + IntraDayDate.create(start, zero()), IntraDayDate.create(endExclusive, zero())).roundToHours(); } - public abstract EffortDuration getAssignedEffort(Criterion criterion, - IntraDayDate startInclusive, IntraDayDate endExclusive); + public abstract EffortDuration getAssignedEffort( + Criterion criterion, IntraDayDate startInclusive, IntraDayDate endExclusive); - private List filter(List assignments, - PredicateOnDayAssignment predicate) { - List result = new ArrayList(); + private List filter(List assignments, PredicateOnDayAssignment predicate) { + List result = new ArrayList<>(); for (DayAssignment dayAssignment : assignments) { if (predicate.satisfiedBy(dayAssignment)) { result.add(dayAssignment); @@ -1927,113 +1849,98 @@ public abstract class ResourceAllocation extends return result; } - protected EffortDuration getAssignedDuration(IntraDayDate startInclusive, - IntraDayDate endExclusive) { - return getAssignedDuration( - getAssignments(startInclusive, endExclusive), startInclusive, - endExclusive); + protected EffortDuration getAssignedDuration(IntraDayDate startInclusive, IntraDayDate endExclusive) { + return getAssignedDuration(getAssignments(startInclusive, endExclusive), startInclusive, endExclusive); } - private EffortDuration sumDuration( - Collection assignments) { - return EffortDuration.sum(assignments, - new IEffortFrom() { - - @Override - public EffortDuration from(DayAssignment each) { - return each.getDuration(); - } - }); + private EffortDuration sumDuration(Collection assignments) { + return EffortDuration.sum(assignments, new IEffortFrom() { + @Override + public EffortDuration from(DayAssignment each) { + return each.getDuration(); + } + }); } private EffortDuration getAssignedDuration( List assignments, - final IntraDayDate startInclusive, final IntraDayDate endExclusive) { + final IntraDayDate startInclusive, + final IntraDayDate endExclusive) { final IntraDayDate allocationStart = getIntraDayStartDate(); - return EffortDuration.sum(assignments, - new IEffortFrom() { + return EffortDuration.sum(assignments, new IEffortFrom() { + @Override + public EffortDuration from(DayAssignment value) { + return getPartialDay(value, startInclusive, endExclusive).limitWorkingDay(value.getDuration()); + } - @Override - public EffortDuration from(DayAssignment value) { - PartialDay partial = getPartialDay(value, - startInclusive, endExclusive); - return partial.limitWorkingDay(value.getDuration()); - } + private PartialDay getPartialDay(DayAssignment assignment, + IntraDayDate startInclusive, + IntraDayDate endExclusive) { - private PartialDay getPartialDay(DayAssignment assignment, - IntraDayDate startInclusive, - IntraDayDate endExclusive) { + LocalDate assignmentDay = assignment.getDay(); + LocalDate startDate = startInclusive.getDate(); + LocalDate endDate = endExclusive.getDate(); - LocalDate assignmentDay = assignment.getDay(); - LocalDate startDate = startInclusive.getDate(); - LocalDate endDate = endExclusive.getDate(); + PartialDay result = PartialDay.wholeDay(assignment.getDay()); + if (assignmentDay.equals(startDate)) { + result = new PartialDay(startInclusive, result.getEnd()); + } + if (assignmentDay.equals(endDate)) { + result = new PartialDay(result.getStart(), endExclusive); + } + return adjustPartialDayToAllocationStart(result); + } - PartialDay result = PartialDay.wholeDay(assignment - .getDay()); - if (assignmentDay.equals(startDate)) { - result = new PartialDay(startInclusive, result - .getEnd()); - } - if (assignmentDay.equals(endDate)) { - result = new PartialDay(result.getStart(), - endExclusive); - } - return adjustPartialDayToAllocationStart(result); - } + // If the start of the allocation is in the middle of a day, its work also starts later, + // so the PartialDay must be moved to earlier so it doesn't limit the duration more that it should + private PartialDay adjustPartialDayToAllocationStart(PartialDay day) { + PartialDay result = day; + if (allocationStart.areSameDay(day.getDate())) { + EffortDuration substractingAtStart = day.getStart().getEffortDuration(); - // if the start of the allocation is in the middle of a day, - // its work also starts later; so the PartialDay must be - // moved to earlier so it doesn't limit the duration more - // that it should - private PartialDay adjustPartialDayToAllocationStart( - PartialDay day) { - PartialDay result = day; - if (allocationStart.areSameDay(day.getDate())) { - EffortDuration substractingAtStart = day.getStart() - .getEffortDuration(); - EffortDuration newSubstractionAtStart = substractingAtStart - .minus(EffortDuration - .min(substractingAtStart, - allocationStart - .getEffortDuration())); - IntraDayDate newStart = IntraDayDate.create( - day.getDate(), newSubstractionAtStart); - result = new PartialDay(newStart, day.getEnd()); - } - return result; - } - }); + EffortDuration newSubstractionAtStart = substractingAtStart.minus( + EffortDuration.min(substractingAtStart, allocationStart.getEffortDuration())); + + IntraDayDate newStart = IntraDayDate.create(day.getDate(), newSubstractionAtStart); + result = new PartialDay(newStart, day.getEnd()); + } + return result; + } + }); } - public void mergeAssignmentsAndResourcesPerDay(Scenario scenario, - ResourceAllocation modifications) { + public void mergeAssignmentsAndResourcesPerDay(Scenario scenario, ResourceAllocation modifications) { if (modifications == this) { return; } + switchToScenario(scenario); mergeAssignments(modifications); this.intendedResourcesPerDay = modifications.intendedResourcesPerDay; + if (modifications.isSatisfied()) { updateOriginalTotalAssigment(); updateResourcesPerDay(); } + setAssignmentFunctionWithoutApply(modifications.getAssignmentFunction()); mergeDerivedAllocations(scenario, modifications.getDerivedAllocations()); } - private void mergeDerivedAllocations(Scenario scenario, - Set derivedAllocations) { - Map newMap = DerivedAllocation - .byConfigurationUnit(derivedAllocations); - Map currentMap = DerivedAllocation - .byConfigurationUnit(getDerivedAllocations()); - for (Entry entry : newMap - .entrySet()) { + private void mergeDerivedAllocations(Scenario scenario, Set derivedAllocations) { + Map newMap = + DerivedAllocation.byConfigurationUnit(derivedAllocations); + + Map currentMap = + DerivedAllocation.byConfigurationUnit(getDerivedAllocations()); + + for (Entry entry : newMap.entrySet()) { final MachineWorkersConfigurationUnit key = entry.getKey(); final DerivedAllocation modification = entry.getValue(); DerivedAllocation current = currentMap.get(key); + if (current == null) { DerivedAllocation derived = modification.asDerivedFrom(this); derived.useScenario(scenario); @@ -2048,10 +1955,8 @@ public abstract class ResourceAllocation extends final void mergeAssignments(ResourceAllocation modifications) { getDayAssignmentsState().mergeAssignments(modifications); - getDayAssignmentsState().setIntraDayStart( - modifications.getDayAssignmentsState().getIntraDayStart()); - getDayAssignmentsState().setIntraDayEnd( - modifications.getDayAssignmentsState().getIntraDayEnd()); + getDayAssignmentsState().setIntraDayStart(modifications.getDayAssignmentsState().getIntraDayStart()); + getDayAssignmentsState().setIntraDayEnd(modifications.getDayAssignmentsState().getIntraDayEnd()); } public void detach() { @@ -2069,7 +1974,7 @@ public abstract class ResourceAllocation extends } public LimitingResourceQueueElement getLimitingResourceQueueElement() { - return (!limitingResourceQueueElements.isEmpty()) ? (LimitingResourceQueueElement) limitingResourceQueueElements.iterator().next() : null; + return (!limitingResourceQueueElements.isEmpty()) ? limitingResourceQueueElements.iterator().next() : null; } public void setLimitingResourceQueueElement(LimitingResourceQueueElement element) { @@ -2089,14 +1994,13 @@ public abstract class ResourceAllocation extends } /** - * Do a query to recover a list of resources that are suitable for this - * allocation. For a {@link SpecificResourceAllocation} returns the current - * resource. For a {@link GenericResourceAllocation} returns the resources - * that currently match this allocation criterions + * Do a query to recover a list of resources that are suitable for this allocation. + * For a {@link SpecificResourceAllocation} returns the current resource. + * For a {@link GenericResourceAllocation} returns the resources that currently match this allocation criterions. + * * @return a list of resources that are proper for this allocation */ - public abstract List querySuitableResources( - IResourcesSearcher resourceSearcher); + public abstract List querySuitableResources(IResourcesSearcher resourceSearcher); public abstract void makeAssignmentsContainersDontPoseAsTransientAnyMore(); @@ -2118,20 +2022,17 @@ public abstract class ResourceAllocation extends protected abstract void removeContainersFor(Scenario scenario); - /* - * Returns first non consolidated day + /** + * Returns first non consolidated day. */ public LocalDate getFirstNonConsolidatedDate() { List nonConsolidated = getNonConsolidatedAssignments(); - return (!nonConsolidated.isEmpty()) ? nonConsolidated.get(0).getDay() - : null; + + return (!nonConsolidated.isEmpty()) ? nonConsolidated.get(0).getDay() : null; } public boolean isManualAssignmentFunction() { - if (assignmentFunction != null) { - return assignmentFunction.isManual(); - } - return false; + return assignmentFunction != null && assignmentFunction.isManual(); } public void resetIntendedIntendedResourcesPerDayWithNonConsolidated() { @@ -2139,7 +2040,7 @@ public abstract class ResourceAllocation extends } public void removeDayAssignmentsBeyondDate(LocalDate date) { - List toRemove = new ArrayList(); + List toRemove = new ArrayList<>(); for (T t : getAssignments()) { if (t.getDay().compareTo(date) >= 0) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SpecificResourceAllocation.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SpecificResourceAllocation.java index b349059bd..6cd9522ec 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SpecificResourceAllocation.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SpecificResourceAllocation.java @@ -22,7 +22,6 @@ package org.libreplan.business.planner.entities; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -58,21 +57,28 @@ import org.libreplan.business.workingday.ResourcesPerDay; /** * Represents the relation between {@link Task} and a specific {@link Worker}. + * * @author Manuel Rego Casasnovas */ public class SpecificResourceAllocation extends ResourceAllocation implements IAllocatable { + @OnCopy(Strategy.SHARE) + private Resource resource; + + private Set specificDayAssignmentsContainers = new HashSet<>(); + + public SpecificResourceAllocation() {} + public static SpecificResourceAllocation create(Task task) { return create(new SpecificResourceAllocation(task)); } /** - * Creates a {@link SpecificResourceAllocation} for a - * {@link LimitingResourceQueueElement} + * Creates a {@link SpecificResourceAllocation} for a {@link LimitingResourceQueueElement}. * * The process of creating a specific resource allocation for a queue * element is different as it's necessary to assign a resource and a number - * of resources per day without allocating day assignments + * of resources per day without allocating day assignments. * * @param resource * @param task @@ -83,26 +89,19 @@ public class SpecificResourceAllocation extends ResourceAllocation specificDayAssignmentsContainers = new HashSet(); - @Valid public Set getSpecificDayAssignmentsContainers() { - return new HashSet(specificDayAssignmentsContainers); + return new HashSet<>(specificDayAssignmentsContainers); } public static SpecificResourceAllocation createForTesting(ResourcesPerDay resourcesPerDay, Task task) { return create(new SpecificResourceAllocation(resourcesPerDay, task)); } - public SpecificResourceAllocation() { - } - @Override protected SpecificDayAssignmentsContainer retrieveOrCreateContainerFor(Scenario scenario) { SpecificDayAssignmentsContainer retrieved = retrieveContainerFor(scenario); @@ -111,13 +110,13 @@ public class SpecificResourceAllocation extends ResourceAllocation containers = containersByScenario(); - return containers.get(scenario); + return containersByScenario().get(scenario); } private SpecificResourceAllocation(ResourcesPerDay resourcesPerDay, Task task) { @@ -134,7 +133,7 @@ public class SpecificResourceAllocation extends ResourceAllocation containersByScenario() { - Map result = new HashMap(); + Map result = new HashMap<>(); for (SpecificDayAssignmentsContainer each : specificDayAssignmentsContainers) { assert !result.containsKey(each); result.put(each.getScenario(), each); @@ -160,8 +159,7 @@ public class SpecificResourceAllocation extends ResourceAllocation distributeForDay(PartialDay day, EffortDuration effort) { - return Arrays.asList(SpecificDayAssignment.create(day.getDate(), effort, resource)); + return Collections.singletonList(SpecificDayAssignment.create(day.getDate(), effort, resource)); } @Override @@ -189,8 +186,7 @@ public class SpecificResourceAllocation extends ResourceAllocation getAssociatedResources() { - return Arrays.asList(resource); + return Collections.singletonList(resource); } @Override ResourceAllocation createCopy(Scenario scenario) { SpecificResourceAllocation result = create(getTask()); result.resource = getResource(); + return result; } @Override - public ResourcesPerDayModification withDesiredResourcesPerDay( - ResourcesPerDay resourcesPerDay) { + public ResourcesPerDayModification withDesiredResourcesPerDay(ResourcesPerDay resourcesPerDay) { return ResourcesPerDayModification.create(this, resourcesPerDay); } @Override - public List querySuitableResources( - IResourcesSearcher resourcesSearcher) { + public List querySuitableResources(IResourcesSearcher resourcesSearcher) { return Collections.singletonList(resource); } @@ -290,8 +285,7 @@ public class SpecificResourceAllocation extends ResourceAllocation assignmentsForEfforts(List assignments, EffortDuration[] newEffortsPerDay) { - List result = new ArrayList(); + List result = new ArrayList<>(); int i = 0; for (DayAssignment each : assignments) { EffortDuration durationForAssignment = newEffortsPerDay[i++]; @@ -356,12 +350,13 @@ public class SpecificResourceAllocation extends ResourceAllocation() { - + return EffortDuration.sum( + getIntervalsRelatedWith(criterion, startInclusive.getDate(), endExclusive.asExclusiveEnd()), + new IEffortFrom() { @Override public EffortDuration from(Interval each) { FixedPoint intervalStart = (FixedPoint) each.getStart(); @@ -374,12 +369,13 @@ public class SpecificResourceAllocation extends ResourceAllocation getIntervalsRelatedWith(Criterion criterion, LocalDate startInclusive, + private List getIntervalsRelatedWith(Criterion criterion, + LocalDate startInclusive, LocalDate endExclusive) { Interval queryInterval = AvailabilityTimeLine.Interval.create(startInclusive, endExclusive); - List result = new ArrayList(); + List result = new ArrayList<>(); for (Interval each : getIntervalsThisAllocationInterferesWith(criterion)) { if ( queryInterval.overlaps(each) ) { @@ -390,17 +386,18 @@ public class SpecificResourceAllocation extends ResourceAllocation getIntervalsThisAllocationInterferesWith(Criterion criterion) { + AvailabilityTimeLine availability = AvailabilityCalculator.getCriterionsAvailabilityFor(Collections.singleton(criterion), resource); availability.invalidUntil(getStartDate()); availability.invalidFrom(getEndDate()); + return availability.getValidPeriods(); } public boolean interferesWith(Criterion criterion, LocalDate startInclusive, LocalDate endExclusive) { - List intervalsRelatedWith = getIntervalsRelatedWith(criterion, startInclusive, endExclusive); - return !intervalsRelatedWith.isEmpty(); + return !getIntervalsRelatedWith(criterion, startInclusive, endExclusive).isEmpty(); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/StretchesFunction.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/StretchesFunction.java index 138be399e..4059ffaac 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/StretchesFunction.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/StretchesFunction.java @@ -397,11 +397,9 @@ public class StretchesFunction extends AssignmentFunction { @Override public String getName() { - if ( StretchesFunctionTypeEnum.INTERPOLATED.equals(type) ) { - return AssignmentFunctionName.INTERPOLATION.toString(); - } else { - return AssignmentFunctionName.STRETCHES.toString(); - } + return StretchesFunctionTypeEnum.INTERPOLATED.equals(type) + ? AssignmentFunctionName.INTERPOLATION.toString() + : AssignmentFunctionName.STRETCHES.toString(); } public List getIntervalsDefinedByStreches() { @@ -415,9 +413,9 @@ public class StretchesFunction extends AssignmentFunction { } private List stretchesFor() { - boolean condition = (getDesiredType().equals(StretchesFunctionTypeEnum.INTERPOLATED)); - - return condition ? getStretchesPlusConsolidated() : getStretches(); + return getDesiredType().equals(StretchesFunctionTypeEnum.INTERPOLATED) + ? getStretchesPlusConsolidated() + : getStretches(); } private void checkStretchesSumOneHundredPercent() { diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractedTaskData.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractedTaskData.java index d413d6cf4..a4cc66132 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractedTaskData.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractedTaskData.java @@ -45,6 +45,46 @@ import org.libreplan.business.util.deepcopy.Strategy; */ public class SubcontractedTaskData extends BaseEntity { + private Task task; + + @OnCopy(Strategy.SHARE) + private ExternalCompany externalCompany; + + private Date subcontratationDate; + + private Date subcontractCommunicationDate; + + private String workDescription; + + private BigDecimal subcontractPrice; + + private String subcontractedCode; + + private Boolean nodeWithoutChildrenExported; + + private Boolean labelsExported; + + private Boolean materialAssignmentsExported; + + private Boolean hoursGroupsExported; + + private SubcontractState state = SubcontractState.PENDING_INITIAL_SEND; + + private final SortedSet requiredDeliveringDates = + new TreeSet<>(new DeliverDateComparator()); + + private SortedSet endDatesCommunicatedFromSubcontractor = + new TreeSet<>(new EndDateCommunicationComparator()); + + /** + * Constructor for hibernate. Do not use! + */ + public SubcontractedTaskData() {} + + private SubcontractedTaskData(Task task) { + this.task = task; + } + public static SubcontractedTaskData create(Task task) { SubcontractedTaskData subcontractedTaskData = new SubcontractedTaskData(task); subcontractedTaskData.subcontratationDate = new Date(); @@ -78,44 +118,6 @@ public class SubcontractedTaskData extends BaseEntity { return create(result); } - private Task task; - - @OnCopy(Strategy.SHARE) - private ExternalCompany externalCompany; - - private Date subcontratationDate; - - private Date subcontractCommunicationDate; - - private String workDescription; - - private BigDecimal subcontractPrice; - - private String subcontractedCode; - - private Boolean nodeWithoutChildrenExported; - private Boolean labelsExported; - private Boolean materialAssignmentsExported; - private Boolean hoursGroupsExported; - - private SubcontractState state = SubcontractState.PENDING_INITIAL_SEND; - - private final SortedSet requiredDeliveringDates = - new TreeSet<>(new DeliverDateComparator()); - - private SortedSet endDatesCommunicatedFromSubcontractor = - new TreeSet<>(new EndDateCommunicationComparator()); - - /** - * Constructor for hibernate. Do not use! - */ - public SubcontractedTaskData() { - } - - private SubcontractedTaskData(Task task) { - this.task = task; - } - @NotNull(message = "task not specified") public Task getTask() { return task; @@ -163,11 +165,7 @@ public class SubcontractedTaskData extends BaseEntity { } public boolean isNodeWithoutChildrenExported() { - if ( nodeWithoutChildrenExported == null ) { - return false; - } - - return nodeWithoutChildrenExported; + return nodeWithoutChildrenExported == null ? false : nodeWithoutChildrenExported; } public void setNodeWithoutChildrenExported(Boolean nodeWithoutChildrenExported) { @@ -178,11 +176,7 @@ public class SubcontractedTaskData extends BaseEntity { } public boolean isLabelsExported() { - if ( labelsExported == null ) { - return false; - } - - return labelsExported; + return labelsExported == null ? false : labelsExported; } public void setLabelsExported(Boolean labelsExported) { @@ -193,11 +187,7 @@ public class SubcontractedTaskData extends BaseEntity { } public Boolean isMaterialAssignmentsExported() { - if ( materialAssignmentsExported == null ) { - return false; - } - - return materialAssignmentsExported; + return materialAssignmentsExported == null ? false : materialAssignmentsExported; } public void setMaterialAssignmentsExported(Boolean materialAssignmentsExported) { @@ -208,11 +198,7 @@ public class SubcontractedTaskData extends BaseEntity { } public Boolean isHoursGroupsExported() { - if ( hoursGroupsExported == null ) { - return false; - } - - return hoursGroupsExported; + return hoursGroupsExported == null ? false : hoursGroupsExported; } public void setHoursGroupsExported(Boolean hoursGroupsExported) { @@ -246,7 +232,6 @@ public class SubcontractedTaskData extends BaseEntity { @AssertTrue(message = "external company should be subcontractor") public boolean isExternalCompanyIsSubcontractorConstraint() { return !firstLevelValidationsPassed() || externalCompany.isSubcontractor(); - } private boolean firstLevelValidationsPassed() { @@ -291,11 +276,9 @@ public class SubcontractedTaskData extends BaseEntity { } public Date getLastRequiredDeliverDate() { - if ( this.requiredDeliveringDates != null && !this.requiredDeliveringDates.isEmpty() ) { - return this.requiredDeliveringDates.first().getSubcontractorDeliverDate(); - } - - return null; + return this.requiredDeliveringDates != null && !this.requiredDeliveringDates.isEmpty() + ? this.requiredDeliveringDates.first().getSubcontractorDeliverDate() + : null; } public void setEndDatesCommunicatedFromSubcontractor( @@ -309,10 +292,8 @@ public class SubcontractedTaskData extends BaseEntity { } public EndDateCommunication getLastEndDatesCommunicatedFromSubcontractor() { - if ( getEndDatesCommunicatedFromSubcontractor() != null ) { - return getEndDatesCommunicatedFromSubcontractor().first(); - } - - return null; + return getEndDatesCommunicatedFromSubcontractor() != null + ? getEndDatesCommunicatedFromSubcontractor().first() + : null; } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunication.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunication.java index 4949372aa..2d9bf3855 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunication.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunication.java @@ -44,10 +44,10 @@ public class SubcontractorCommunication extends BaseEntity { private List subcontractorCommunicationValues = new ArrayList<>(); - // Default constructor, needed by Hibernate - protected SubcontractorCommunication() { - - } + /** + * Default constructor, needed by Hibernate. + */ + protected SubcontractorCommunication() {} private SubcontractorCommunication(SubcontractedTaskData subcontractedTaskData, CommunicationType communicationType, @@ -116,17 +116,14 @@ public class SubcontractorCommunication extends BaseEntity { return subcontractorCommunicationValues; } - public SubcontractorCommunicationValue getLastSubcontractorCommunicationValues(){ - if ( subcontractorCommunicationValues.isEmpty() ){ - return null; - } - - return subcontractorCommunicationValues.get(subcontractorCommunicationValues.size()-1); + public SubcontractorCommunicationValue getLastSubcontractorCommunicationValues() { + return subcontractorCommunicationValues.isEmpty() + ? null + : subcontractorCommunicationValues.get(subcontractorCommunicationValues.size() - 1); } public Date getLastSubcontractorCommunicationValueDate(){ SubcontractorCommunicationValue value = getLastSubcontractorCommunicationValues(); - return (value == null) ? null : value.getDate(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunicationValue.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunicationValue.java index 8a38a27f9..671b4b6c4 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunicationValue.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/SubcontractorCommunicationValue.java @@ -32,34 +32,34 @@ import org.libreplan.business.INewObject; */ public class SubcontractorCommunicationValue implements INewObject { - public static SubcontractorCommunicationValue create() { - SubcontractorCommunicationValue subcontractorCommunicationValue = new SubcontractorCommunicationValue(); - subcontractorCommunicationValue.setNewObject(true); - return subcontractorCommunicationValue; - } + private boolean newObject = false; - public static SubcontractorCommunicationValue create(Date date, - BigDecimal progress) { - SubcontractorCommunicationValue subcontractorCommunicationValue = new SubcontractorCommunicationValue( - date, progress); - subcontractorCommunicationValue.setNewObject(true); - return subcontractorCommunicationValue; - } + private Date date; - protected SubcontractorCommunicationValue() { + private BigDecimal progress; - } + protected SubcontractorCommunicationValue() {} private SubcontractorCommunicationValue(Date date, BigDecimal progress) { this.setDate(date); this.setProgress(progress); } - private boolean newObject = false; + public static SubcontractorCommunicationValue create() { + SubcontractorCommunicationValue subcontractorCommunicationValue = new SubcontractorCommunicationValue(); + subcontractorCommunicationValue.setNewObject(true); - private Date date; + return subcontractorCommunicationValue; + } - private BigDecimal progress; + public static SubcontractorCommunicationValue create(Date date, BigDecimal progress) { + SubcontractorCommunicationValue subcontractorCommunicationValue = + new SubcontractorCommunicationValue(date, progress); + + subcontractorCommunicationValue.setNewObject(true); + + return subcontractorCommunicationValue; + } public boolean isNewObject() { return newObject; @@ -72,11 +72,9 @@ public class SubcontractorCommunicationValue implements INewObject { @SuppressWarnings("unused") @AssertTrue(message = "progress should be greater than 0% and less than 100%") public boolean isQualityFormItemPercentageConstraint() { - if (getProgress() == null) { - return true; - } - return ((getProgress().compareTo(new BigDecimal(100).setScale(2)) <= 0) && (getProgress() - .compareTo(new BigDecimal(0).setScale(2)) > 0)); + return getProgress() == null || + (getProgress().compareTo(new BigDecimal(100).setScale(2)) <= 0 && + (getProgress().compareTo(new BigDecimal(0).setScale(2)) > 0)); } public void setDate(Date date) { @@ -97,8 +95,6 @@ public class SubcontractorCommunicationValue implements INewObject { @Override public String toString() { - String progress_reported = progress != null ? progress.toString() - + "% - " : ""; - return progress_reported + date; + return progress != null ? progress.toString() + "% - " + date : date.toString(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/TaskElement.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/TaskElement.java index 02cda3cea..71812b2c8 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/TaskElement.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/TaskElement.java @@ -70,6 +70,46 @@ public abstract class TaskElement extends BaseEntity { private static final Log LOG = LogFactory.getLog(TaskElement.class); + private static final IDatesInterceptor EMPTY_INTERCEPTOR = new IDatesInterceptor() { + @Override + public void setStartDate(IntraDayDate previousStart, IntraDayDate previousEnd, IntraDayDate newStart) {} + + @Override + public void setNewEnd(IntraDayDate previousEnd, IntraDayDate newEnd) {} + }; + + @OnCopy(Strategy.SHARE) + private IDatesInterceptor datesInterceptor = EMPTY_INTERCEPTOR; + + @OnCopy(Strategy.SHARE) + private BaseCalendar calendar; + + private IntraDayDate startDate; + + private IntraDayDate endDate; + + private LocalDate deadline; + + private String name; + + private String notes; + + private BigDecimal advancePercentage = BigDecimal.ZERO; + + private Boolean simplifiedAssignedStatusCalculationEnabled = false; + + private Boolean updatedFromTimesheets = false; + + private EffortDuration sumOfAssignedEffort = EffortDuration.zero(); + + private TaskGroup parent; + + private Set dependenciesWithThisOrigin = new HashSet<>(); + + private Set dependenciesWithThisDestination = new HashSet<>(); + + private TaskSource taskSource; + public static List justTasks(Collection tasks) { List result = new ArrayList<>(); for (TaskElement taskElement : tasks) { @@ -82,27 +122,14 @@ public abstract class TaskElement extends BaseEntity { } public interface IDatesInterceptor { - void setStartDate(IntraDayDate previousStart, - IntraDayDate previousEnd, IntraDayDate newStart); + + void setStartDate(IntraDayDate previousStart, IntraDayDate previousEnd, IntraDayDate newStart); void setNewEnd(IntraDayDate previousEnd, IntraDayDate newEnd); } - private static final IDatesInterceptor EMPTY_INTERCEPTOR = new IDatesInterceptor() { - - @Override - public void setStartDate(IntraDayDate previousStart, IntraDayDate previousEnd, IntraDayDate newStart) { - } - - @Override - public void setNewEnd(IntraDayDate previousEnd, IntraDayDate newEnd) { - } - - }; - public static Comparator getByStartDateComparator() { Comparator result = new Comparator() { - @Override public int compare(TaskElement o1, TaskElement o2) { return o1.getStartDate().compareTo(o2.getStartDate()); @@ -114,13 +141,10 @@ public abstract class TaskElement extends BaseEntity { public static Comparator getByEndAndDeadlineDateComparator() { return new Comparator() { - @Override public int compare(TaskElement o1, TaskElement o2) { - return o1.getBiggestAmongEndOrDeadline().compareTo( - o2.getBiggestAmongEndOrDeadline()); + return o1.getBiggestAmongEndOrDeadline().compareTo(o2.getBiggestAmongEndOrDeadline()); } - }; } @@ -129,11 +153,9 @@ public abstract class TaskElement extends BaseEntity { */ @SuppressWarnings("unchecked") public LocalDate getBiggestAmongEndOrDeadline() { - if ( this.getDeadline() != null ) { - return Collections.max(asList(this.getDeadline(), this.getEndAsLocalDate())); - } - - return this.getEndAsLocalDate(); + return this.getDeadline() != null + ? Collections.max(asList(this.getDeadline(), this.getEndAsLocalDate())) + : this.getEndAsLocalDate(); } protected static T create(T taskElement, TaskSource taskSource) { @@ -142,6 +164,7 @@ public abstract class TaskElement extends BaseEntity { taskElement.setName(taskElement.getOrderElement().getName()); taskElement.updateAdvancePercentageFromOrderElement(); Order order = taskElement.getOrderElement().getOrder(); + if ( order.isScheduleBackwards() ) { taskElement.setEndDate(order.getDeadline()); } else { @@ -154,36 +177,6 @@ public abstract class TaskElement extends BaseEntity { return create(taskElement); } - @OnCopy(Strategy.SHARE) - private IDatesInterceptor datesInterceptor = EMPTY_INTERCEPTOR; - - private IntraDayDate startDate; - - private IntraDayDate endDate; - - private LocalDate deadline; - - private String name; - - private String notes; - - private TaskGroup parent; - - private Set dependenciesWithThisOrigin = new HashSet(); - - private Set dependenciesWithThisDestination = new HashSet(); - - @OnCopy(Strategy.SHARE) - private BaseCalendar calendar; - - private TaskSource taskSource; - - private BigDecimal advancePercentage = BigDecimal.ZERO; - - private Boolean simplifiedAssignedStatusCalculationEnabled = false; - - private Boolean updatedFromTimesheets = false; - public void initializeDatesIfNeeded() { if ( getIntraDayEndDate() == null || getIntraDayStartDate() == null ) { initializeDates(); @@ -203,11 +196,7 @@ public abstract class TaskElement extends BaseEntity { } public Integer getWorkHours() { - if ( taskSource == null ) { - return 0; - } - - return taskSource.getTotalHours(); + return taskSource == null ? 0 : taskSource.getTotalHours(); } protected void copyPropertiesFrom(TaskElement task) { @@ -227,12 +216,11 @@ public abstract class TaskElement extends BaseEntity { protected void copyDependenciesTo(TaskElement result) { for (Dependency dependency : getDependenciesWithThisOrigin()) { - Dependency.create(result, dependency.getDestination(), - dependency.getType()); + Dependency.create(result, dependency.getDestination(), dependency.getType()); } + for (Dependency dependency : getDependenciesWithThisDestination()) { - Dependency.create(dependency.getOrigin(), result, - dependency.getType()); + Dependency.create(dependency.getOrigin(), result, dependency.getType()); } } @@ -274,11 +262,7 @@ public abstract class TaskElement extends BaseEntity { } public OrderElement getOrderElement() { - if ( getTaskSource() == null ) { - return null; - } - - return getTaskSource().getOrderElement(); + return getTaskSource() == null ? null : getTaskSource().getOrderElement(); } public Set getDependenciesWithThisOrigin() { @@ -290,7 +274,7 @@ public abstract class TaskElement extends BaseEntity { } public Set getDependenciesWithThisDestinationAndAllParents() { - Set result = new HashSet(getDependenciesWithThisDestination()); + Set result = new HashSet<>(getDependenciesWithThisDestination()); if ( parent != null ) { result.addAll(parent.getDependenciesWithThisDestinationAndAllParents()); } @@ -323,6 +307,7 @@ public abstract class TaskElement extends BaseEntity { if ( startDate == null ) { LOG.error(doNotProvideNullsDiscouragingMessage()); } + IntraDayDate previousStart = getIntraDayStartDate(); IntraDayDate previousEnd = getIntraDayEndDate(); this.startDate = startDate; @@ -335,24 +320,26 @@ public abstract class TaskElement extends BaseEntity { } public void setEndDate(Date endDate) { - setIntraDayEndDate( (endDate != null) ? - IntraDayDate.create(LocalDate.fromDateFields(endDate), EffortDuration.zero()) : null); + setIntraDayEndDate( (endDate != null) + ? IntraDayDate.create(LocalDate.fromDateFields(endDate), EffortDuration.zero()) + : null); } public void setIntraDayEndDate(IntraDayDate endDate) { if ( endDate == null ) { LOG.error(doNotProvideNullsDiscouragingMessage()); } + IntraDayDate previousEnd = getIntraDayEndDate(); this.endDate = endDate; datesInterceptor.setNewEnd(previousEnd, this.endDate); } private String doNotProvideNullsDiscouragingMessage() { - return "The provided date shouldn't be null.\n" - + "Providing null values to start or end dates is not safe.\n" - + "In a near future an exception will be thrown if you provide a null value to a start or end date.\n" - + "Please detect the caller and fix it"; + return "The provided date shouldn't be null.\n" + + "Providing null values to start or end dates is not safe.\n" + + "In a near future an exception will be thrown if you provide a null value to a start or end date.\n" + + "Please detect the caller and fix it"; } @NotNull @@ -360,8 +347,7 @@ public abstract class TaskElement extends BaseEntity { return endDate; } - public IDatesHandler getDatesHandler(Scenario scenario, - IResourcesSearcher resourcesSearcher) { + public IDatesHandler getDatesHandler(Scenario scenario, IResourcesSearcher resourcesSearcher) { return noNullDates(createDatesHandler(scenario, resourcesSearcher)); } @@ -388,15 +374,13 @@ public abstract class TaskElement extends BaseEntity { }; } - protected abstract IDatesHandler createDatesHandler(Scenario scenario, - IResourcesSearcher resourcesSearcher); + protected abstract IDatesHandler createDatesHandler(Scenario scenario, IResourcesSearcher resourcesSearcher); public interface IDatesHandler { /** - * Sets the startDate to newStartDate. It can update the endDate + * Sets the startDate to newStartDate. It can update the endDate. * - * @param scenario * @param newStartDate */ void moveTo(IntraDayDate newStartDate); @@ -420,8 +404,10 @@ public abstract class TaskElement extends BaseEntity { public void setDeadline(LocalDate deadline) { this.deadline = deadline; if ( taskSource != null && taskSource.getOrderElement() != null ) { - taskSource.getOrderElement().setDeadline( - (deadline == null)? null : deadline.toDateTimeAtStartOfDay().toDate()); + + taskSource.getOrderElement().setDeadline((deadline == null) + ? null + : deadline.toDateTimeAtStartOfDay().toDate()); } } @@ -429,6 +415,7 @@ public abstract class TaskElement extends BaseEntity { if ( this.equals(dependency.getOrigin()) ) { dependenciesWithThisOrigin.add(dependency); } + if ( this.equals(dependency.getDestination()) ) { dependenciesWithThisDestination.add(dependency); } @@ -445,7 +432,7 @@ public abstract class TaskElement extends BaseEntity { } public void removeDependencyWithDestination(TaskElement destination, Type type) { - ArrayList toBeRemoved = new ArrayList(); + ArrayList toBeRemoved = new ArrayList<>(); for (Dependency dependency : dependenciesWithThisOrigin) { if ( dependency.getDestination().equals(destination) && dependency.getType().equals(type) ) { toBeRemoved.add(dependency); @@ -498,7 +485,8 @@ public abstract class TaskElement extends BaseEntity { private List getDependenciesWithOrigin(TaskElement t) { ArrayList result = new ArrayList<>(); for (Dependency dependency : dependenciesWithThisDestination) { - if ( dependency.getOrigin().equals(t) ) {result.add(dependency); + if ( dependency.getOrigin().equals(t) ) { + result.add(dependency); } } @@ -511,7 +499,7 @@ public abstract class TaskElement extends BaseEntity { } private void detachIncomingDependencies() { - Set tasksToNotify = new HashSet(); + Set tasksToNotify = new HashSet<>(); for (Dependency dependency : dependenciesWithThisDestination) { TaskElement origin = dependency.getOrigin(); if ( origin != null ) { @@ -525,7 +513,7 @@ public abstract class TaskElement extends BaseEntity { } private void detachOutcomingDependencies() { - Set tasksToNotify = new HashSet(); + Set tasksToNotify = new HashSet<>(); for (Dependency dependency : dependenciesWithThisOrigin) { TaskElement destination = dependency.getDestination(); if ( destination != null ) { @@ -549,6 +537,7 @@ public abstract class TaskElement extends BaseEntity { public BaseCalendar getCalendar() { if ( calendar == null ) { OrderElement orderElement = getOrderElement(); + return orderElement != null ? orderElement.getOrder().getCalendar() : null; } @@ -590,8 +579,10 @@ public abstract class TaskElement extends BaseEntity { return DayAssignment.filter(dayAssignments, filter); } + /** + * Just Task could be subcontracted. + */ public boolean isSubcontracted() { - // Just Task could be subcontracted return false; } @@ -599,8 +590,10 @@ public abstract class TaskElement extends BaseEntity { return ""; } + /** + * Just Task could be subcontracted. + */ public boolean isSubcontractedAndWasAlreadySent() { - // Just Task could be subcontracted return false; } @@ -612,8 +605,10 @@ public abstract class TaskElement extends BaseEntity { return false; } + /** + * Just Task could be consolidated. + */ public boolean hasConsolidations() { - // Just Task could be consolidated return false; } @@ -637,20 +632,19 @@ public abstract class TaskElement extends BaseEntity { } public String getAssignedStatus() { - if(isSimplifiedAssignedStatusCalculationEnabled()) { - //simplified calculation has only two states: - //unassigned, when hours allocated is zero, and - //assigned otherwise - if ( getSumOfAssignedEffort().isZero() ) { - return "unassigned"; - } + if (isSimplifiedAssignedStatusCalculationEnabled()) { + // Simplified calculation has only two states: + // 1. Unassigned, when hours allocated is zero. + // 2. Assigned otherwise. - return "assigned"; + return getSumOfAssignedEffort().isZero() ? "unassigned" : "assigned"; } + Set> resourceAllocations = getSatisfiedResourceAllocations(); if ( resourceAllocations.isEmpty() ) { return "unassigned"; } + for (ResourceAllocation resourceAllocation : resourceAllocations) { final ResourcesPerDay resourcesPerDay = resourceAllocation.getResourcesPerDay(); if ( resourcesPerDay != null && resourcesPerDay.isZero() ) { @@ -662,16 +656,11 @@ public abstract class TaskElement extends BaseEntity { } public Boolean belongsClosedProject() { - EnumSet CLOSED = EnumSet.of(OrderStatusEnum.CANCELLED, - OrderStatusEnum.FINISHED, - OrderStatusEnum.STORED); - Order order = getOrderElement().getOrder(); - if( CLOSED.contains(order.getState()) ) { - return true; - } + EnumSet CLOSED = + EnumSet.of(OrderStatusEnum.CANCELLED, OrderStatusEnum.FINISHED, OrderStatusEnum.STORED); - return false; + return CLOSED.contains(getOrderElement().getOrder().getState()); } public abstract boolean hasLimitedResourceAllocation(); @@ -695,15 +684,12 @@ public abstract class TaskElement extends BaseEntity { /** * For common tasks it just return the spread progress. * - * It's overridden in {@link TaskGroup} to return different progresses - * depending on parameter + * It's overridden in {@link TaskGroup} to return different progresses depending on parameter. */ public BigDecimal getAdvancePercentage(ProgressType progressType) { - if ( progressType != null && progressType.equals(ProgressType.SPREAD_PROGRESS) ) { - return advancePercentage; - } - - return BigDecimal.ZERO; + return progressType != null && progressType.equals(ProgressType.SPREAD_PROGRESS) + ? advancePercentage + : BigDecimal.ZERO; } public void setAdvancePercentage(BigDecimal advancePercentage) { @@ -711,15 +697,13 @@ public abstract class TaskElement extends BaseEntity { this.resetStatus(); } - private EffortDuration sumOfAssignedEffort = EffortDuration.zero(); - public void setSumOfAssignedEffort(EffortDuration sumOfAssignedEffort) { this.sumOfAssignedEffort = sumOfAssignedEffort; } public EffortDuration getSumOfAssignedEffort() { if ( this.getParent() == null ) { - //it's an order, we use the cached value + // It's an order, we use the cached value return sumOfAssignedEffort; } else { @@ -729,7 +713,7 @@ public abstract class TaskElement extends BaseEntity { private EffortDuration getSumOfAssignedEffortCalculated() { EffortDuration result = EffortDuration.zero(); - for(ResourceAllocation allocation : getAllResourceAllocations()) { + for (ResourceAllocation allocation : getAllResourceAllocations()) { result = result.plus(allocation.getAssignedEffort()); } return result; @@ -743,7 +727,7 @@ public abstract class TaskElement extends BaseEntity { public List getAllChildren() { List children = getChildren(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (TaskElement child : children) { result.add(child); result.addAll(child.getAllChildren()); @@ -755,12 +739,15 @@ public abstract class TaskElement extends BaseEntity { public abstract EffortDuration getTheoreticalCompletedTimeUntilDate(Date date); public BigDecimal getTheoreticalAdvancePercentageUntilDate(Date date) { - EffortDuration totalAllocatedTime = AggregateOfDayAssignments.create( - this.getDayAssignments(FilterType.KEEP_ALL)).getTotalTime(); + EffortDuration totalAllocatedTime = + AggregateOfDayAssignments.create(this.getDayAssignments(FilterType.KEEP_ALL)).getTotalTime(); + EffortDuration totalTheoreticalCompletedTime = this.getTheoreticalCompletedTimeUntilDate(date); + if ( totalAllocatedTime.isZero() || totalTheoreticalCompletedTime.isZero() ) { return BigDecimal.ZERO; } + Validate.isTrue(totalTheoreticalCompletedTime.getSeconds() <= totalAllocatedTime.getSeconds()); return totalTheoreticalCompletedTime.dividedByAndResultAsBigDecimal(totalAllocatedTime); @@ -779,23 +766,19 @@ public abstract class TaskElement extends BaseEntity { } public Boolean isRoot() { - return (this.getParent() == null); + return this.getParent() == null; } public BigDecimal getBudget() { - if ( (taskSource != null) && (taskSource.getOrderElement() != null) ) { - return taskSource.getOrderElement().getBudget(); - } - - return null; + return (taskSource != null) && (taskSource.getOrderElement() != null) + ? taskSource.getOrderElement().getBudget() + : null; } public BigDecimal getResourcesBudget() { - if ( (taskSource != null) && (taskSource.getOrderElement() != null) ) { - return taskSource.getOrderElement().getResourcesBudget(); - } - - return null; + return (taskSource != null) && (taskSource.getOrderElement() != null) + ? taskSource.getOrderElement().getResourcesBudget() + : null; } public ExternalCompany getSubcontractedCompany() { @@ -806,10 +789,13 @@ public abstract class TaskElement extends BaseEntity { public TaskDeadlineViolationStatusEnum getDeadlineViolationStatus() { LocalDate deadline = this.getDeadline(); + if ( deadline == null ) { return TaskDeadlineViolationStatusEnum.NO_DEADLINE; + } else if ( this.getEndAsLocalDate().isAfter(deadline) ) { return TaskDeadlineViolationStatusEnum.DEADLINE_VIOLATED; + } else { return TaskDeadlineViolationStatusEnum.ON_SCHEDULE; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java b/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java index 182bab06d..e15a78fb6 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/qualityforms/daos/QualityFormDAO.java @@ -98,16 +98,16 @@ public class QualityFormDAO extends GenericDAOHibernate imple @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) public QualityForm findUniqueByName(QualityForm qualityForm) throws InstanceNotFoundException { Validate.notNull(qualityForm); - return findUniqueByName(qualityForm.getName()); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) public QualityForm findUniqueByName(String name) throws InstanceNotFoundException, NonUniqueResultException { - Criteria c = getSession().createCriteria(QualityForm.class); - c.add(Restrictions.eq("name", name)); - QualityForm qualityForm = (QualityForm) c.uniqueResult(); + QualityForm qualityForm = (QualityForm) getSession() + .createCriteria(QualityForm.class) + .add(Restrictions.eq("name", name)) + .uniqueResult(); if (qualityForm == null) { throw new InstanceNotFoundException(null, "QualityForm"); @@ -120,7 +120,6 @@ public class QualityFormDAO extends GenericDAOHibernate imple public boolean existsOtherWorkReportTypeByName(QualityForm qualityForm) { try { QualityForm t = findUniqueByName(qualityForm); - return t != null && t != qualityForm; } catch (InstanceNotFoundException e) { return false; diff --git a/libreplan-business/src/main/java/org/libreplan/business/qualityforms/entities/TaskQualityForm.java b/libreplan-business/src/main/java/org/libreplan/business/qualityforms/entities/TaskQualityForm.java index 005a28a8a..a359cab1f 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/qualityforms/entities/TaskQualityForm.java +++ b/libreplan-business/src/main/java/org/libreplan/business/qualityforms/entities/TaskQualityForm.java @@ -36,14 +36,13 @@ import org.libreplan.business.orders.entities.OrderElement; public class TaskQualityForm extends BaseEntity { - public static TaskQualityForm create(OrderElement orderElement, - QualityForm qualityForm) { - return create(new TaskQualityForm(orderElement, qualityForm)); - } + private OrderElement orderElement; - protected TaskQualityForm() { + private QualityForm qualityForm; - } + private List taskQualityFormItems = new ArrayList<>(); + + private Boolean reportAdvance = false; private TaskQualityForm(OrderElement orderElement, QualityForm qualityForm) { this.orderElement = orderElement; @@ -51,21 +50,21 @@ public class TaskQualityForm extends BaseEntity { createTaskQualityFormItems(); } - private OrderElement orderElement; + protected TaskQualityForm() { - private QualityForm qualityForm; + } - private List taskQualityFormItems = new ArrayList(); - - private Boolean reportAdvance = false; + public static TaskQualityForm create(OrderElement orderElement, + QualityForm qualityForm) { + return create(new TaskQualityForm(orderElement, qualityForm)); + } @Valid public List getTaskQualityFormItems() { return Collections.unmodifiableList(taskQualityFormItems); } - public void setTaskQualityFormItems( - List taskQualityFormItems) { + public void setTaskQualityFormItems(List taskQualityFormItems) { this.taskQualityFormItems = taskQualityFormItems; } @@ -89,10 +88,8 @@ public class TaskQualityForm extends BaseEntity { private void createTaskQualityFormItems() { Validate.notNull(qualityForm); - for (QualityFormItem qualityFormItem : qualityForm - .getQualityFormItems()) { - TaskQualityFormItem taskQualityFormItem = TaskQualityFormItem - .create(qualityFormItem); + for (QualityFormItem qualityFormItem : qualityForm.getQualityFormItems()) { + TaskQualityFormItem taskQualityFormItem = TaskQualityFormItem.create(qualityFormItem); taskQualityFormItems.add(taskQualityFormItem); } } @@ -107,6 +104,7 @@ public class TaskQualityForm extends BaseEntity { } } } + return true; } @@ -120,52 +118,48 @@ public class TaskQualityForm extends BaseEntity { } } } + return true; } public boolean isCorrectConsecutivePassed(TaskQualityFormItem item) { - if (item.getPassed()) { - return (isPassedPreviousItem(item)); - } - return true; + return !item.getPassed() || (isPassedPreviousItem(item)); + } public boolean isCorrectConsecutiveDate(TaskQualityFormItem item) { if (item.getPassed()) { - return ((isPassedPreviousItem(item)) && (isLaterToPreviousItemDate(item))); + return (isPassedPreviousItem(item)) && (isLaterToPreviousItemDate(item)); } - return (item.getDate() == null); + + return item.getDate() == null; } public boolean isPassedPreviousItem(TaskQualityFormItem item) { Integer previousPosition = item.getPosition() - 1; + if ((previousPosition >= 0) && (previousPosition < taskQualityFormItems.size())) { return taskQualityFormItems.get(previousPosition).getPassed(); } + return true; } public boolean isLaterToPreviousItemDate(TaskQualityFormItem item) { Integer previousPosition = item.getPosition() - 1; - if ((previousPosition >= 0) - && (previousPosition < taskQualityFormItems.size())) { - Date previousDate = taskQualityFormItems.get(previousPosition) - .getDate(); - return ((previousDate != null) && (item.getDate() != null) && ((previousDate - .before(item.getDate())) || (previousDate.equals(item - .getDate())))); + if ((previousPosition >= 0) && (previousPosition < taskQualityFormItems.size())) { + Date previousDate = taskQualityFormItems.get(previousPosition).getDate(); + return (previousDate != null) && (item.getDate() != null) && + ((previousDate.before(item.getDate())) || (previousDate.equals(item.getDate()))); } + return true; } public boolean isByItems() { - if ((this.qualityForm != null) - && (this.qualityForm.getQualityFormType() != null)) { - return (this.qualityForm.getQualityFormType() - .equals(QualityFormType.BY_ITEMS)); - } - return true; + return !((this.qualityForm != null) && (this.qualityForm.getQualityFormType() != null)) || + (this.qualityForm.getQualityFormType().equals(QualityFormType.BY_ITEMS)); } @NotNull(message = "report progress not specified") @@ -177,12 +171,11 @@ public class TaskQualityForm extends BaseEntity { this.reportAdvance = BooleanUtils.toBoolean(reportAdvance); } - public static TaskQualityForm copy(TaskQualityForm origin, - OrderElement orderElement) { - TaskQualityForm copy = TaskQualityForm.create(orderElement, origin - .getQualityForm()); + public static TaskQualityForm copy(TaskQualityForm origin, OrderElement orderElement) { + TaskQualityForm copy = TaskQualityForm.create(orderElement, origin.getQualityForm()); copy.setTaskQualityFormItems(origin.getTaskQualityFormItems()); copy.setReportAdvance(origin.isReportAdvance()); + return copy; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/reports/dtos/HoursWorkedPerResourceDTO.java b/libreplan-business/src/main/java/org/libreplan/business/reports/dtos/HoursWorkedPerResourceDTO.java index a77bae0d4..7c01eb343 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/reports/dtos/HoursWorkedPerResourceDTO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/reports/dtos/HoursWorkedPerResourceDTO.java @@ -54,17 +54,16 @@ public class HoursWorkedPerResourceDTO implements Comparable { private HoursWorkedPerResourceDTO self; - public HoursWorkedPerResourceDTO(Resource resource, - WorkReportLine workReportLine) { + public HoursWorkedPerResourceDTO(Resource resource, WorkReportLine workReportLine) { this.workerName = resource.getName(); this.date = workReportLine.getDate(); LocalTime clockStart = workReportLine.getClockStart(); - this.clockStart = (clockStart != null) ? clockStart.toString("HH:mm") - : ""; + this.clockStart = (clockStart != null) ? clockStart.toString("HH:mm") : ""; + LocalTime clockFinish = workReportLine.getClockFinish(); - this.clockFinish = (clockFinish != null) ? clockFinish - .toString("HH:mm") : ""; + this.clockFinish = (clockFinish != null) ? clockFinish.toString("HH:mm") : ""; + this.effort = workReportLine.getEffort(); this.orderElementCode = workReportLine.getOrderElement().getCode(); this.orderElementName = workReportLine.getOrderElement().getName(); @@ -168,8 +167,7 @@ public class HoursWorkedPerResourceDTO implements Comparable { @Override public int compareTo(Object o) { - return this.workerName - .compareTo(((HoursWorkedPerResourceDTO) o).workerName); + return this.workerName.compareTo(((HoursWorkedPerResourceDTO) o).workerName); } /** diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/CriterionsBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/CriterionsBootstrap.java index 03fcf00ae..5f096a4d1 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/CriterionsBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/CriterionsBootstrap.java @@ -27,8 +27,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.libreplan.business.common.daos.IEntitySequenceDAO; import org.libreplan.business.common.entities.EntityNameEnum; import org.libreplan.business.resources.daos.ICriterionDAO; @@ -36,6 +34,7 @@ import org.libreplan.business.resources.daos.ICriterionTypeDAO; import org.libreplan.business.resources.entities.Criterion; import org.libreplan.business.resources.entities.CriterionType; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -47,11 +46,9 @@ import org.springframework.transaction.annotation.Transactional; * @author Diego Pino García */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class CriterionsBootstrap implements ICriterionsBootstrap { - private static final Log LOG = LogFactory.getLog(CriterionsBootstrap.class); - @Autowired private ICriterionDAO criterionDAO; @@ -73,8 +70,7 @@ public class CriterionsBootstrap implements ICriterionsBootstrap { if (criterionTypeDAO.findAll().isEmpty()) { Map> typesWithCriterions = getTypesWithCriterions(); // Insert predefined criterions - for (Entry> entry : typesWithCriterions - .entrySet()) { + for (Entry> entry : typesWithCriterions.entrySet()) { CriterionType criterionType = retrieveOrCreate(entry.getKey()); // Create predefined criterions for criterionType for (String criterionName : entry.getValue()) { @@ -84,10 +80,9 @@ public class CriterionsBootstrap implements ICriterionsBootstrap { } } - private void ensureCriterionExists(String criterionName, - CriterionType criterionType) { - Criterion criterion = Criterion.createPredefined(criterionName, - criterionType); + private void ensureCriterionExists(String criterionName, CriterionType criterionType) { + Criterion criterion = Criterion.createPredefined(criterionName, criterionType); + if (!criterionDAO.existsPredefinedCriterion(criterion)) { int numberOfDigits = getNumberOfDigitsCode(); criterionType.setGenerateCode(criterion, numberOfDigits); @@ -104,26 +99,26 @@ public class CriterionsBootstrap implements ICriterionsBootstrap { criterionTypeDAO.save(criterionType); return criterionType; } + return criterionTypeDAO.findPredefined(criterionType); } private Map> getTypesWithCriterions() { - HashMap> result = new HashMap>(); + HashMap> result = new HashMap<>(); for (ICriterionTypeProvider provider : providers) { - for (Entry> entry : provider - .getRequiredCriterions().entrySet()) { + for (Entry> entry : provider.getRequiredCriterions().entrySet()) { if (!result.containsKey(entry.getKey())) { result.put(entry.getKey(), new ArrayList()); } result.get(entry.getKey()).addAll(entry.getValue()); } } + return result; } protected Integer getNumberOfDigitsCode() { - return entitySequenceDAO - .getNumberOfDigitsCode(EntityNameEnum.CRITERION); + return entitySequenceDAO.getNumberOfDigitsCode(EntityNameEnum.CRITERION); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/PredefinedCriterionTypesProvider.java b/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/PredefinedCriterionTypesProvider.java index 3710dc41c..7252a21c2 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/PredefinedCriterionTypesProvider.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/bootstrap/PredefinedCriterionTypesProvider.java @@ -27,6 +27,7 @@ import java.util.Map; import org.libreplan.business.resources.entities.CriterionType; import org.libreplan.business.resources.entities.PredefinedCriterionTypes; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -37,7 +38,7 @@ import org.springframework.stereotype.Component; * @author Diego Pino García */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class PredefinedCriterionTypesProvider implements ICriterionTypeProvider { public PredefinedCriterionTypesProvider() { @@ -45,10 +46,12 @@ public class PredefinedCriterionTypesProvider implements ICriterionTypeProvider @Override public Map> getRequiredCriterions() { - Map> result = new HashMap>(); + Map> result = new HashMap<>(); + for (PredefinedCriterionTypes type : PredefinedCriterionTypes.values()) { result.put(CriterionType.fromPredefined(type), type.getPredefined()); } + return result; } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourceLoadRatiosCalculator.java b/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourceLoadRatiosCalculator.java index 98d7f23f0..36429f2c2 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourceLoadRatiosCalculator.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourceLoadRatiosCalculator.java @@ -23,9 +23,9 @@ import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import org.joda.time.LocalDate; -import org.libreplan.business.common.IAdHocTransactionService; import org.libreplan.business.planner.daos.IDayAssignmentDAO; import org.libreplan.business.planner.entities.DayAssignment; import org.libreplan.business.resources.entities.Resource; @@ -43,13 +43,11 @@ import org.springframework.transaction.annotation.Transactional; * {@link IResourceLoadRatiosCalculator} interface. * * @author Javier Moran Rua - * */ @Service @Scope(BeanDefinition.SCOPE_SINGLETON) -public class ResourceLoadRatiosCalculator implements - IResourceLoadRatiosCalculator { +public class ResourceLoadRatiosCalculator implements IResourceLoadRatiosCalculator { @Autowired private IDayAssignmentDAO dayAssigmentDAO; @@ -57,17 +55,14 @@ public class ResourceLoadRatiosCalculator implements @Autowired private IResourceDAO resourceDAO; - @Autowired - private IAdHocTransactionService adHocTransactionService; - - private static class LoadRatiosDataType implements - IResourceLoadRatiosCalculator.ILoadRatiosDataType { + private static class LoadRatiosDataType implements IResourceLoadRatiosCalculator.ILoadRatiosDataType { private EffortDuration load; + private EffortDuration overload; + private EffortDuration capacity; - public LoadRatiosDataType(EffortDuration load, EffortDuration overload, - EffortDuration capacity) { + public LoadRatiosDataType(EffortDuration load, EffortDuration overload, EffortDuration capacity) { this.load = load; this.overload = overload; this.capacity = capacity; @@ -94,8 +89,7 @@ public class ResourceLoadRatiosCalculator implements if (this.load.isZero() && this.overload.isZero()) { result = BigDecimal.ZERO; } else { - result = this.overload.dividedByAndResultAsBigDecimal(this.load - .plus(this.capacity)); + result = this.overload.dividedByAndResultAsBigDecimal(this.load.plus(this.capacity)); } return result.setScale(2, BigDecimal.ROUND_HALF_UP); @@ -104,12 +98,13 @@ public class ResourceLoadRatiosCalculator implements @Override public BigDecimal getAvailiabilityRatio() { BigDecimal result; + if (this.capacity.isZero()) { result = BigDecimal.ZERO; } else { - result = BigDecimal.ONE.subtract(this.load - .dividedByAndResultAsBigDecimal(this.capacity)); + result = BigDecimal.ONE.subtract(this.load.dividedByAndResultAsBigDecimal(this.capacity)); + if (result.compareTo(BigDecimal.ZERO) < 0) { result = BigDecimal.ZERO; } @@ -121,35 +116,39 @@ public class ResourceLoadRatiosCalculator implements @Override @Transactional(readOnly = true) public ILoadRatiosDataType calculateLoadRatios(final Resource resource, - final LocalDate startDate, final LocalDate endDate, - final Scenario scenario) { - + final LocalDate startDate, + final LocalDate endDate, + final Scenario scenario) { resourceDAO.reattach(resource); - EffortDuration totalLoad = EffortDuration.zero(), totalOverload = EffortDuration - .zero(), totalCapacity = EffortDuration.zero(); + EffortDuration + totalLoad = EffortDuration.zero(), + totalOverload = EffortDuration.zero(), + totalCapacity; - for (Map.Entry each : getAllEffortPerDateFor( - scenario, startDate, endDate, resource).entrySet()) { + Set> efforts = + getAllEffortPerDateFor(scenario, startDate, endDate, resource).entrySet(); + + for (Map.Entry each : efforts) { totalLoad = totalLoad.plus(each.getValue()); - totalOverload = addOverload(totalOverload, resource, - each.getValue(), each.getKey()); + totalOverload = addOverload(totalOverload, resource, each.getValue(), each.getKey()); } totalCapacity = calculateTotalCapacity(resource, startDate, endDate); + return new LoadRatiosDataType(totalLoad, totalOverload, totalCapacity); } private Map getAllEffortPerDateFor( - Scenario scenario, LocalDate startDate, LocalDate endDate, - Resource resource) { + Scenario scenario, LocalDate startDate, LocalDate endDate, Resource resource) { - HashMap result = new HashMap(); + HashMap result; + result = new HashMap<>(); - List l = dayAssigmentDAO.getAllFor(scenario, startDate, - endDate, resource); + List l = dayAssigmentDAO.getAllFor(scenario, startDate, endDate, resource); + + EffortDuration newValue; - EffortDuration newValue = EffortDuration.zero(); for (DayAssignment each : l) { if (result.containsKey(each.getDay())) { newValue = result.get(each.getDay()).plus(each.getDuration()); @@ -161,15 +160,16 @@ public class ResourceLoadRatiosCalculator implements return result; } - private EffortDuration calculateTotalCapacity(Resource resource, - LocalDate startDate, LocalDate endDate) { + private EffortDuration calculateTotalCapacity(Resource resource, LocalDate startDate, LocalDate endDate) { return resource.getCalendar().getWorkableDuration(startDate, endDate); } - private EffortDuration addOverload(EffortDuration currentOverload, - Resource resource, EffortDuration loadAtDate, LocalDate date) { + private EffortDuration addOverload( + EffortDuration currentOverload, Resource resource, EffortDuration loadAtDate, LocalDate date) { + EffortDuration result; EffortDuration capacityAtDay = getCapacityAtDate(resource, date); + if (capacityAtDay.compareTo(loadAtDate) < 0) { result = currentOverload.plus(loadAtDate.minus(capacityAtDay)); } else { diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourcesSearcher.java b/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourcesSearcher.java index ef31f1651..fb644306b 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourcesSearcher.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/daos/ResourcesSearcher.java @@ -70,6 +70,7 @@ public class ResourcesSearcher implements IResourcesSearcher { @Autowired private SessionFactory sessionFactory; + @Override public IResourcesQuery searchMachines() { return new Query<>(Machine.class); } @@ -104,7 +105,6 @@ public class ResourcesSearcher implements IResourcesSearcher { public IResourcesQuery byCriteria(Collection criteria) { Validate.noNullElements(criteria); this.criteria = new ArrayList<>(criteria); - return this; } @@ -205,13 +205,13 @@ public class ResourcesSearcher implements IResourcesSearcher { public IResourcesQuery searchBoth() { final IResourcesQuery searchWorkers = searchWorkers(); final IResourcesQuery searchMachines = searchMachines(); + return new IResourcesQuery() { @Override public IResourcesQuery byName(String name) { searchWorkers.byName(name); searchMachines.byName(name); - return this; } @@ -219,7 +219,6 @@ public class ResourcesSearcher implements IResourcesSearcher { public IResourcesQuery byCriteria(Collection criteria) { searchWorkers.byCriteria(criteria); searchMachines.byCriteria(criteria); - return this; } @@ -227,7 +226,6 @@ public class ResourcesSearcher implements IResourcesSearcher { public IResourcesQuery byResourceType(ResourceType type) { searchWorkers.byResourceType(type); searchMachines.byResourceType(type); - return this; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Criterion.java b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Criterion.java index 2977fe679..9c26517ad 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Criterion.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Criterion.java @@ -31,7 +31,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.apache.commons.collections.ComparatorUtils; +import org.apache.commons.collections4.ComparatorUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.EqualsBuilder; @@ -48,7 +48,8 @@ import org.libreplan.business.requirements.entities.CriterionRequirement; import org.libreplan.business.resources.daos.ICriterionDAO; /** - * A criterion stored in the database
+ * A criterion stored in the database. + *
* @author Óscar González Fernández * @author Fernando Bellas Permuy */ @@ -165,8 +166,7 @@ public class Criterion extends IntegrationEntity implements ICriterion, return getCaptionFor(ResourceEnum.WORKER, criteria); } - public static String getCaptionFor( - GenericResourceAllocation allocation) { + public static String getCaptionFor(GenericResourceAllocation allocation) { return getCaptionFor(allocation.getResourceType(), allocation.getCriterions()); } @@ -178,7 +178,7 @@ public class Criterion extends IntegrationEntity implements ICriterion, * @return */ public static String getCaptionFor(ResourceEnum resourceType, - Collection criteria) { + Collection criteria) { if (criteria.isEmpty()) { return allCaptionFor(resourceType); } @@ -191,12 +191,12 @@ public class Criterion extends IntegrationEntity implements ICriterion, private static String allCaptionFor(ResourceEnum resourceType) { switch (resourceType) { - case WORKER: - return allWorkersCaption(); - case MACHINE: - return allMachinesCaption(); - default: - throw new RuntimeException("cant handle " + resourceType); + case WORKER: + return allWorkersCaption(); + case MACHINE: + return allMachinesCaption(); + default: + throw new RuntimeException("cant handle " + resourceType); } } @@ -463,9 +463,7 @@ public class Criterion extends IntegrationEntity implements ICriterion, } @Override - public void setCodeAutogenerated(Boolean codeAutogenerated) { - // do nothing - } + public void setCodeAutogenerated(Boolean codeAutogenerated) { /* Do nothing */ } @Override public Boolean isCodeAutogenerated() { diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/CriterionSatisfaction.java b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/CriterionSatisfaction.java index 7d7c3f923..d266c2c57 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/CriterionSatisfaction.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/CriterionSatisfaction.java @@ -35,7 +35,9 @@ import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.resources.daos.ICriterionSatisfactionDAO; import org.libreplan.business.resources.daos.ICriterionTypeDAO; /** - * Declares a interval of time in which the criterion is satisfied
+ * Declares a interval of time in which the criterion is satisfied. + *
+ * * @author Óscar González Fernández * @author Fernando Bellas Permuy */ @@ -45,30 +47,55 @@ public class CriterionSatisfaction extends IntegrationEntity { static { BY_START_COMPARATOR = new Comparator() { - @Override - public int compare(CriterionSatisfaction o1, - CriterionSatisfaction o2) { + public int compare(CriterionSatisfaction o1, CriterionSatisfaction o2) { return o1.getStartDate().compareTo(o2.getStartDate()); } }; } + private LocalDate startDate; + + private LocalDate finishDate; + + private Criterion criterion; + + private Resource resource; + + private Boolean isDeleted = false; + + /** + * Constructor for hibernate. Do not use! + */ + public CriterionSatisfaction() {} + + private CriterionSatisfaction(LocalDate startDate, Criterion criterion, Resource resource) { + Validate.notNull(startDate, "startDate must be not null"); + Validate.notNull(criterion, "criterion must be not null"); + Validate.notNull(resource, "resource must be not null"); + + this.startDate = startDate; + this.criterion = criterion; + this.resource = resource; + } + + private CriterionSatisfaction(Criterion criterion, Resource resource, Interval interval) { + this(interval.getStart(), criterion, resource); + if (interval.getEnd() != null) { + this.finish(interval.getEnd()); + } + } + public static CriterionSatisfaction create() { return create(new CriterionSatisfaction()); } - public static CriterionSatisfaction create(LocalDate startDate, - Criterion criterion, Resource resource) { - return create( - new CriterionSatisfaction(startDate, criterion, resource)); + public static CriterionSatisfaction create(LocalDate startDate, Criterion criterion, Resource resource) { + return create(new CriterionSatisfaction(startDate, criterion, resource)); } - public static CriterionSatisfaction create(Criterion criterion, - Resource resource, Interval interval) { - + public static CriterionSatisfaction create(Criterion criterion, Resource resource, Interval interval) { return create(new CriterionSatisfaction(criterion, resource, interval)); - } /** @@ -76,24 +103,22 @@ public class CriterionSatisfaction extends IntegrationEntity { * not exist */ public static CriterionSatisfaction createUnvalidated(String code, - String criterionTypeName, String criterionName, Resource resource, - LocalDate startDate, LocalDate finishDate) - throws InstanceNotFoundException { + String criterionTypeName, + String criterionName, + Resource resource, + LocalDate startDate, + LocalDate finishDate) throws InstanceNotFoundException { - ICriterionTypeDAO criterionTypeDAO = - Registry.getCriterionTypeDAO(); + ICriterionTypeDAO criterionTypeDAO = Registry.getCriterionTypeDAO(); - /* Get CriterionType. */ - CriterionType criterionType = criterionTypeDAO.findUniqueByName( - criterionTypeName); + /* Get CriterionType */ + CriterionType criterionType = criterionTypeDAO.findUniqueByName(criterionTypeName); - /* Get Criterion. */ - Criterion criterion = criterionType.getCriterion( - criterionName); + /* Get Criterion */ + Criterion criterion = criterionType.getCriterion(criterionName); - /* Create instance of CriterionSatisfaction. */ - CriterionSatisfaction criterionSatisfaction = - create(new CriterionSatisfaction(), code); + /* Create instance of CriterionSatisfaction */ + CriterionSatisfaction criterionSatisfaction = create(new CriterionSatisfaction(), code); criterionSatisfaction.criterion = criterion; criterionSatisfaction.resource = resource; @@ -109,19 +134,19 @@ public class CriterionSatisfaction extends IntegrationEntity { * not exist */ public void updateUnvalidated(String criterionTypeName, - String criterionName, LocalDate startDate, LocalDate finishDate) - throws InstanceNotFoundException { + String criterionName, + LocalDate startDate, + LocalDate finishDate) throws InstanceNotFoundException { - CriterionType criterionType = null; + CriterionType criterionType; if (StringUtils.isBlank(criterionTypeName)) { criterionType = criterion.getType(); } else { - criterionType = Registry.getCriterionTypeDAO().findUniqueByName( - criterionTypeName); + criterionType = Registry.getCriterionTypeDAO().findUniqueByName(criterionTypeName); } - String newCriterionName = null; + String newCriterionName; if (StringUtils.isBlank(criterionName)) { newCriterionName = StringUtils.trim(criterion.getName()); @@ -138,44 +163,8 @@ public class CriterionSatisfaction extends IntegrationEntity { if (finishDate != null) { this.finishDate = finishDate; } - } - /** - * Constructor for hibernate. Do not use! - */ - public CriterionSatisfaction() { - - } - - private CriterionSatisfaction(LocalDate startDate, Criterion criterion, - Resource resource) { - Validate.notNull(startDate, "startDate must be not null"); - Validate.notNull(criterion, "criterion must be not null"); - Validate.notNull(resource, "resource must be not null"); - this.startDate = startDate; - this.criterion = criterion; - this.resource = resource; - } - - private CriterionSatisfaction(Criterion criterion, Resource resource, - Interval interval) { - this(interval.getStart(), criterion, resource); - if (interval.getEnd() != null) { - this.finish(interval.getEnd()); - } - } - - private LocalDate startDate; - - private LocalDate finishDate; - - private Criterion criterion; - - private Resource resource; - - private Boolean isDeleted = false; - @Override public String toString() { return ToStringBuilder.reflectionToString(this); @@ -187,6 +176,7 @@ public class CriterionSatisfaction extends IntegrationEntity { result.finishDate = finishDate; result.criterion = criterion; result.resource = resource; + return result; } @@ -237,10 +227,11 @@ public class CriterionSatisfaction extends IntegrationEntity { public void finish(LocalDate finish) { Validate.notNull(finish); - Validate.isTrue(getStartDate() == null - || getStartDate().compareTo(finish) <= 0); - Validate.isTrue(finishDate == null || isNewObject() - || getEndDate().equals(finish) || getEndDate().isBefore(finish)); + Validate.isTrue(getStartDate() == null || getStartDate().compareTo(finish) <= 0); + + Validate.isTrue( + finishDate == null || isNewObject() || getEndDate().equals(finish) || getEndDate().isBefore(finish)); + this.finishDate = finish; } @@ -260,10 +251,10 @@ public class CriterionSatisfaction extends IntegrationEntity { } public void setStartDate(LocalDate date) { - if(date != null){ - Validate.isTrue(startDate == null || isNewObject() - || getStartDate().equals(date) - || getStartDate().isAfter(date)); + if(date != null) { + + Validate.isTrue( + startDate == null || isNewObject() || getStartDate().equals(date) || getStartDate().isAfter(date)); } startDate = date; } @@ -297,17 +288,17 @@ public class CriterionSatisfaction extends IntegrationEntity { @AssertTrue(message = "criterion satisfaction with end date before start") public boolean isPositiveTimeInterval() { - /* Check if it makes sense to check the constraint .*/ + /* Check if it makes sense to check the constraint */ if (!isStartDateSpecified()) { return true; } - /* Check the constraint. */ + /* Check the constraint */ if (finishDate == null) { return true; } - return (finishDate.isAfter(startDate) || startDate.equals(finishDate)); + return finishDate.isAfter(startDate) || startDate.equals(finishDate); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java index 5597eca67..5b58e8ef1 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java @@ -30,7 +30,8 @@ import org.hibernate.validator.constraints.NotEmpty; import javax.validation.Valid; /** - * Entity + * Represents entity. It is another type of work resource. + * * @author Javier Moran Rua * @author Fernando Bellas Permuy */ @@ -42,25 +43,22 @@ public class Machine extends Resource { private String description; - private Set configurationUnits = new HashSet(); + private Set configurationUnits = new HashSet<>(); @Valid public Set getConfigurationUnits() { return Collections.unmodifiableSet(configurationUnits); } - public void addMachineWorkersConfigurationUnit( - MachineWorkersConfigurationUnit unit) { + public void addMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) { configurationUnits.add(unit); } - public void removeMachineWorkersConfigurationUnit( - MachineWorkersConfigurationUnit unit) { + public void removeMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) { configurationUnits.remove(unit); } - public static Machine createUnvalidated(String code, String name, - String description) { + public static Machine createUnvalidated(String code, String name, String description) { Machine machine = create(new Machine(), code); @@ -86,9 +84,7 @@ public class Machine extends Resource { /** * Used by Hibernate. Do not use! */ - protected Machine() { - - } + protected Machine() {} public static Machine create() { return create(new Machine()); @@ -120,8 +116,7 @@ public class Machine extends Resource { } @Override - protected boolean isCriterionSatisfactionOfCorrectType( - CriterionSatisfaction c) { + protected boolean isCriterionSatisfactionOfCorrectType(CriterionSatisfaction c) { return c.getResourceType().equals(ResourceEnum.MACHINE); } @@ -139,5 +134,4 @@ public class Machine extends Resource { public String getHumanId() { return name; } - } diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Resource.java b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Resource.java index af4e513e4..f21324792 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Resource.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Resource.java @@ -71,6 +71,7 @@ import org.libreplan.business.workingday.IntraDayDate.PartialDay; /** * This class acts as the base class for all resources. + * * @author Fernando Bellas Permuy * @author Susana Montes Pedreira * @author Jacobo Aragunde Perez @@ -135,7 +136,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti private Map> assignmentsByDayCached = null; private Set resourcesCostCategoryAssignments = - new HashSet(); + new HashSet(); private ResourceType resourceType = ResourceType.NON_LIMITING_RESOURCE; @@ -438,7 +439,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti private static class EnsureSatisfactionIsCorrect { private EnsureSatisfactionIsCorrect(Resource resource, - ICriterionType type, CriterionSatisfaction satisfaction) { + ICriterionType type, CriterionSatisfaction satisfaction) { Validate.notNull(resource); Validate.notNull(satisfaction.getResource()); Validate.notNull(satisfaction); @@ -469,7 +470,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public CriterionSatisfaction addSatisfaction(ICriterionType type, - CriterionSatisfaction satisfaction) { + CriterionSatisfaction satisfaction) { return new EnsureSatisfactionIsCorrect(this, type, satisfaction) .addSatisfaction(); } @@ -503,7 +504,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private CriterionSatisfaction createNewSatisfaction(Interval interval, - Criterion criterion) { + Criterion criterion) { CriterionSatisfaction newSatisfaction = CriterionSatisfaction.create(criterion, this, interval); return newSatisfaction; } @@ -521,7 +522,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti * */ private int findPlace(List orderedSatisfactions, - CriterionSatisfaction newSatisfaction) { + CriterionSatisfaction newSatisfaction) { int position = Collections.binarySearch(orderedSatisfactions, newSatisfaction, CriterionSatisfaction.BY_START_COMPARATOR); if (position >= 0) { @@ -538,7 +539,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public List finishEnforcedAt(Criterion criterion, - LocalDate date) { + LocalDate date) { ArrayList result = new ArrayList(); for (CriterionSatisfaction criterionSatisfaction : query() .exactly(criterion).at(date).result()) { @@ -549,7 +550,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public void modifySatisfaction(CriterionSatisfaction original, - Interval interval){ + Interval interval){ /* Create a temporal criterion satisfaction. */ CriterionType type = original.getCriterion().getType(); CriterionSatisfaction temporal = createNewSatisfaction(interval, @@ -570,13 +571,13 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti criterionSatisfactions.add(original); if(!canAdd){ throw new IllegalStateException( - "This interval "+original.getCriterion().getName()+" not is valid because exists overlap with other criterion satisfaction"); + "This interval "+original.getCriterion().getName()+" not is valid because exists overlap with other criterion satisfaction"); } }catch(IllegalArgumentException e){ throw new IllegalArgumentException (original.getCriterion().getName()+" : "+e.getMessage()); } }else{ - throw new IllegalStateException( + throw new IllegalStateException( "The criterion satisfaction "+original.getCriterion().getName()+" not is activated for this resource"); } } @@ -596,9 +597,9 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } CriterionSatisfaction previousSameCriterion = getPreviousSameCriterion - (criterion, satisfaction, satisfactions); + (criterion, satisfaction, satisfactions); CriterionSatisfaction posteriorSameCriterion = getNextSameCriterion - (criterion, satisfaction, satisfactions); + (criterion, satisfaction, satisfactions); boolean canAdd = ((previousSameCriterion == null || !previousSameCriterion.overlapsWith(interval)) && @@ -616,7 +617,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti CriterionSatisfaction posterior = getNext(type, satisfaction, satisfactions); return (previous == null || !previous.overlapsWith(interval)) && - ( posterior == null || !posterior.overlapsWith(interval)); + ( posterior == null || !posterior.overlapsWith(interval)); } public boolean _canAddSatisfaction( @@ -638,7 +639,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti boolean canAdd = ((previousSameCriterion == null || !previousSameCriterion.overlapsWith(interval)) && ( posteriorSameCriterion == null || - !posteriorSameCriterion.overlapsWith(interval))); + !posteriorSameCriterion.overlapsWith(interval))); if(!canAdd) { return false; @@ -657,14 +658,14 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public boolean canAddSatisfaction(ICriterionType type, - CriterionSatisfaction satisfaction) { + CriterionSatisfaction satisfaction) { EnsureSatisfactionIsCorrect ensureSatisfactionIsCorrect = new EnsureSatisfactionIsCorrect( this, type, satisfaction); return ensureSatisfactionIsCorrect.canAddSatisfaction(); } private CriterionSatisfaction getNext(ICriterionType type, - CriterionSatisfaction newSatisfaction,Set list) { + CriterionSatisfaction newSatisfaction,Set list) { List ordered = query().from(type).result(list); int position = findPlace(ordered, newSatisfaction); CriterionSatisfaction next = position != ordered.size() ? ordered @@ -673,7 +674,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private CriterionSatisfaction getPrevious(ICriterionType type, - CriterionSatisfaction newSatisfaction,Set list) { + CriterionSatisfaction newSatisfaction,Set list) { List ordered = query().from(type).result(list); int position = findPlace(ordered, newSatisfaction); CriterionSatisfaction previous = position > 0 ? ordered @@ -683,7 +684,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti private CriterionSatisfaction getNextSameCriterion(Criterion criterion, - CriterionSatisfaction newSatisfaction,Set list) { + CriterionSatisfaction newSatisfaction,Set list) { List ordered = query().from(criterion).result(list); int position = findPlace(ordered, newSatisfaction); CriterionSatisfaction next = position != ordered.size() ? ordered @@ -692,7 +693,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private CriterionSatisfaction getPreviousSameCriterion(Criterion criterion, - CriterionSatisfaction newSatisfaction,Set list) { + CriterionSatisfaction newSatisfaction,Set list) { List ordered = query().from(criterion).result(list); int position = findPlace(ordered, newSatisfaction); CriterionSatisfaction previous = position > 0 ? ordered @@ -753,7 +754,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti * @throws IllegalArgumentException in case of overlapping */ private void checkNotOverlaps(CriterionSatisfaction before, - CriterionSatisfaction after) { + CriterionSatisfaction after) { CriterionType criterionType = before.getCriterion().getType(); @@ -763,10 +764,10 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti * criterion satisfactions per resource). */ if (before.getCriterion().equals(after.getCriterion()) && - !before.goesBeforeWithoutOverlapping(after)) { - throw new IllegalArgumentException(createOverlapsMessage(before, - after)); - } + !before.goesBeforeWithoutOverlapping(after)) { + throw new IllegalArgumentException(createOverlapsMessage(before, + after)); + } /* * If CriterionType does not allow simultaneous criterion satisfactions @@ -774,7 +775,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti * of they refer to different Criterion objects). */ if (!criterionType.isAllowSimultaneousCriterionsPerResource() && - !before.goesBeforeWithoutOverlapping(after)) { + !before.goesBeforeWithoutOverlapping(after)) { throw new IllegalArgumentException(createOverlapsMessage(before, after)); } @@ -782,7 +783,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private String createOverlapsMessage(CriterionSatisfaction before, - CriterionSatisfaction after) { + CriterionSatisfaction after) { return new StringBuilder("the satisfaction").append(before).append( "overlaps with").append(after).toString(); } @@ -824,13 +825,13 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public void setResourceCalendar(String calendarCode) - throws InstanceNotFoundException, MultipleInstancesException { + throws InstanceNotFoundException, MultipleInstancesException { ResourceCalendar calendar; if (StringUtils.isBlank(calendarCode)) { calendar = Registry.getConfigurationDAO().getConfiguration(). - getDefaultCalendar().newDerivedResourceCalendar(); + getDefaultCalendar().newDerivedResourceCalendar(); } else { BaseCalendar baseCalendar = Registry.getBaseCalendarDAO() @@ -849,7 +850,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti public EffortDuration getAssignedDurationDiscounting( Map> allocationsFromWhichDiscountHours, LocalDate day) { - + EffortDuration result = zero(); for (DayAssignment dayAssignment : getAssignmentsForDay(day)) { @@ -886,19 +887,19 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public int getTotalWorkHours(LocalDate start, LocalDate endExclusive, - ICriterion criterion) { + ICriterion criterion) { return getTotalEffortFor(IntraDayDate.startOfDay(start), IntraDayDate.startOfDay(endExclusive), criterion) .roundToHours(); } public EffortDuration getTotalEffortFor(IntraDayDate startInclusive, - IntraDayDate endExclusive) { + IntraDayDate endExclusive) { return getTotalEffortFor(startInclusive, endExclusive, null); } public EffortDuration getTotalEffortFor(IntraDayDate startInclusive, - IntraDayDate endExclusive, ICriterion criterion) { + IntraDayDate endExclusive, ICriterion criterion) { return getTotalEffortFor(getCalendarOrDefault(), startInclusive, endExclusive, criterion); } @@ -909,8 +910,8 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private EffortDuration getTotalEffortFor(final ICalendar calendar, - IntraDayDate startInclusive, IntraDayDate endExclusive, - final ICriterion criterionToSatisfy) { + IntraDayDate startInclusive, IntraDayDate endExclusive, + final ICriterion criterionToSatisfy) { Iterable daysBetween = startInclusive .daysUntil(endExclusive); @@ -923,7 +924,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti .getCapacityOn(current); if (capacityCurrent != null && (criterionToSatisfy == null || satisfiesCriterionAt( - criterionToSatisfy, current.getDate()))) { + criterionToSatisfy, current.getDate()))) { return capacityCurrent; } return zero(); @@ -932,12 +933,12 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private boolean satisfiesCriterionAt(ICriterion criterionToSatisfy, - LocalDate current) { + LocalDate current) { return criterionToSatisfy.isSatisfiedBy(this, current); } public void addUnvalidatedSatisfaction(CriterionSatisfaction - criterionSatisfaction) { + criterionSatisfaction) { criterionSatisfactions.add(criterionSatisfaction); @@ -975,7 +976,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } private void validateSatisfaction(CriterionSatisfaction satisfaction, Set satisfactions) - throws ValidationException { + throws ValidationException { if ( !canAddSatisfaction(satisfaction, satisfactions) ) { String message = getReasonForNotAddingSatisfaction(satisfaction.getCriterion().getType()); @@ -1004,16 +1005,16 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public ResourcesCostCategoryAssignment - getResourcesCostCategoryAssignmentByCode(String code) - throws InstanceNotFoundException { + getResourcesCostCategoryAssignmentByCode(String code) + throws InstanceNotFoundException { if (StringUtils.isBlank(code)) { throw new InstanceNotFoundException(code, - ResourcesCostCategoryAssignment.class.getName()); + ResourcesCostCategoryAssignment.class.getName()); } for (ResourcesCostCategoryAssignment i : - resourcesCostCategoryAssignments) { + resourcesCostCategoryAssignments) { if (i.getCode().equalsIgnoreCase(StringUtils.trim(code))) { return i; @@ -1022,7 +1023,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } throw new InstanceNotFoundException(code, - ResourcesCostCategoryAssignment.class.getName()); + ResourcesCostCategoryAssignment.class.getName()); } @@ -1034,7 +1035,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } public void addUnvalidatedResourcesCostCategoryAssignment( - ResourcesCostCategoryAssignment assignment) { + ResourcesCostCategoryAssignment assignment) { resourcesCostCategoryAssignments.add(assignment); @@ -1093,7 +1094,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti * Check assignment overlapping. */ List assignmentsList = - new ArrayList(); + new ArrayList(); assignmentsList.addAll(getResourcesCostCategoryAssignments()); try { @@ -1112,7 +1113,7 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } @AssertTrue(message="there exist criterion satisfactions referring to " + - "criterion types not applicable to this resource") + "criterion types not applicable to this resource") public boolean isCriterionSatisfactionsWithCorrectTypeConstraint() { for (CriterionSatisfaction c : getCriterionSatisfactions()) { @@ -1126,13 +1127,13 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti } @AssertTrue(message="criterion satisfaction codes must be unique inside " + - "a resource") + "a resource") public boolean isNonRepeatedCriterionSatisfactionCodesConstraint() { return getFirstRepeatedCode(criterionSatisfactions) == null; } @AssertTrue(message="resource cost category assignments codes must be " + - "unique inside a resource") + "unique inside a resource") public boolean isNonRepeatedResourcesCostCategoryAssignmentCodesConstraint() { return getFirstRepeatedCode(resourcesCostCategoryAssignments) == null; } @@ -1174,30 +1175,30 @@ public abstract class Resource extends IntegrationEntity implements IHumanIdenti @AssertTrue(message = "You have exceeded the maximum limit of resources") public boolean isMaxResourcesConstraint() { return Registry.getTransactionService().runOnAnotherReadOnlyTransaction(new IOnTransaction() { - @Override - public Boolean execute() { - Configuration configuration = Registry.getConfigurationDAO().getConfiguration(); - if ( configuration == null ) { - return true; - } + @Override + public Boolean execute() { + Configuration configuration = Registry.getConfigurationDAO().getConfiguration(); + if ( configuration == null ) { + return true; + } - Integer maxResources = configuration.getMaxResources(); - - if ( maxResources != null && maxResources > 0 ) { - List resources = Registry.getResourceDAO().findAll(); - int resourcesNumber = resources.size(); - - if ( isNewObject() ) { - resourcesNumber++; - } - - if ( resourcesNumber > maxResources ) { - return false; - } - } - return true; + Integer maxResources = configuration.getMaxResources(); + + if ( maxResources != null && maxResources > 0 ) { + List resources = Registry.getResourceDAO().findAll(); + int resourcesNumber = resources.size(); + + if ( isNewObject() ) { + resourcesNumber++; } - }); + + if ( resourcesNumber > maxResources ) { + return false; + } + } + return true; + } + }); } public boolean isActiveBetween(LocalDate startDate, LocalDate endDate) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/ResourceEnum.java b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/ResourceEnum.java index 2bef4245b..19de56829 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/ResourceEnum.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/ResourceEnum.java @@ -21,10 +21,7 @@ package org.libreplan.business.resources.entities; - - /** - * * @author Diego Pino Garcia */ public enum ResourceEnum { @@ -32,21 +29,22 @@ public enum ResourceEnum { WORKER(Worker.class, _("WORKER")), MACHINE(Machine.class, _("MACHINE")); + private Class klass; + + private final String displayName; + + ResourceEnum(Class klass, String displayName) { + this.klass = klass; + this.displayName = displayName; + } + /** - * Forces to mark the string as needing translation + * Forces to mark the string as needing translation. */ private static String _(String string) { return string; } - private Class klass; - private final String displayName; - - private ResourceEnum(Class klass, String displayName) { - this.klass = klass; - this.displayName = displayName; - } - public Class asClass() { return klass; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java index 7a25c20c8..72dc1a901 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java +++ b/libreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java @@ -52,14 +52,14 @@ public class Worker extends Resource { } public static Worker create(String firstName, String surname, - String nif) { + String nif) { return create(new Worker(firstName, surname, nif)); } public static Worker createUnvalidated(String code, String firstName, - String surname, String nif) { + String surname, String nif) { Worker worker = create(new Worker(), code); @@ -110,6 +110,14 @@ public class Worker extends Resource { this.nif = nif; } + /** + * This method is needed by autocomplete component on _machineConfigurationUnits.zul + */ + @Override + public String toString () { + return this.getName() + " - " + this.getNif(); + } + public String getDescription() { return getSurname() + "," + getFirstName(); } @@ -180,18 +188,18 @@ public class Worker extends Resource { protected boolean areFirstNameSurnameNifSpecified() { - return !StringUtils.isBlank(firstName) && - !StringUtils.isBlank(surname) && - !StringUtils.isBlank(nif); + return !StringUtils.isBlank(firstName) && + !StringUtils.isBlank(surname) && + !StringUtils.isBlank(nif); - } + } - @Override - protected boolean isCriterionSatisfactionOfCorrectType( - CriterionSatisfaction c) { + @Override + protected boolean isCriterionSatisfactionOfCorrectType( + CriterionSatisfaction c) { return c.getResourceType().equals(ResourceEnum.WORKER); - } + } @Override public ResourceEnum getType() { diff --git a/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/PredefinedScenarios.java b/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/PredefinedScenarios.java index 25809c4d3..4110b813c 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/PredefinedScenarios.java +++ b/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/PredefinedScenarios.java @@ -36,7 +36,7 @@ public enum PredefinedScenarios { private final String name; - private PredefinedScenarios(String name) { + PredefinedScenarios(String name) { this.name = name; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/ScenariosBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/ScenariosBootstrap.java index b17cd248a..0d3f15cf1 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/ScenariosBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/scenarios/bootstrap/ScenariosBootstrap.java @@ -26,6 +26,7 @@ import org.libreplan.business.orders.entities.Order; import org.libreplan.business.scenarios.daos.IScenarioDAO; import org.libreplan.business.scenarios.entities.Scenario; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -36,7 +37,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class ScenariosBootstrap implements IScenariosBootstrap { @Autowired @@ -50,16 +51,16 @@ public class ScenariosBootstrap implements IScenariosBootstrap { @Override @Transactional public void loadRequiredData() { - for (PredefinedScenarios predefinedScenario : PredefinedScenarios - .values()) { - if (!scenarioDAO.existsByNameAnotherTransaction(predefinedScenario - .getName())) { + for (PredefinedScenarios predefinedScenario : PredefinedScenarios.values()) { + if (!scenarioDAO.existsByNameAnotherTransaction(predefinedScenario.getName())) { Scenario scenario = createAtDB(predefinedScenario); + if (predefinedScenario == PredefinedScenarios.MASTER) { mainScenario = scenario; } } } + if (mainScenario == null) { mainScenario = PredefinedScenarios.MASTER.getScenario(); } @@ -67,11 +68,14 @@ public class ScenariosBootstrap implements IScenariosBootstrap { private Scenario createAtDB(PredefinedScenarios predefinedScenario) { Scenario scenario = predefinedScenario.createScenario(); + for (Order each : orderDAO.getOrders()) { scenario.addOrder(each); } + scenarioDAO.save(scenario); scenario.dontPoseAsTransientObjectAnymore(); + return scenario; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java b/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java index d052e6984..244aa4145 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java @@ -27,7 +27,6 @@ import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.libreplan.business.common.daos.GenericDAOHibernate; import org.libreplan.business.common.exceptions.InstanceNotFoundException; @@ -49,8 +48,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) -public class ScenarioDAO extends GenericDAOHibernate implements - IScenarioDAO { +public class ScenarioDAO extends GenericDAOHibernate implements IScenarioDAO { @Autowired private IOrderVersionDAO orderVersionDAO; @@ -70,7 +68,7 @@ public class ScenarioDAO extends GenericDAOHibernate implements private List getNewOrders(Scenario scenario) { Collection values = scenario.getOrders().values(); - List newOrders = new ArrayList(); + List newOrders = new ArrayList<>(); for (OrderVersion each : values) { if (each.isNewObject()) { newOrders.add(each); @@ -86,9 +84,9 @@ public class ScenarioDAO extends GenericDAOHibernate implements throw new InstanceNotFoundException(null, Scenario.class.getName()); } - Scenario scenario = (Scenario) getSession().createCriteria( - Scenario.class).add( - Restrictions.eq("name", name.trim()).ignoreCase()) + Scenario scenario = (Scenario) getSession() + .createCriteria(Scenario.class) + .add(Restrictions.eq("name", name.trim()).ignoreCase()) .uniqueResult(); if (scenario == null) { @@ -132,10 +130,7 @@ public class ScenarioDAO extends GenericDAOHibernate implements } private boolean areDifferentInDB(Scenario one, Scenario other) { - if ((one.getId() == null) || (other.getId() == null)) { - return true; - } - return !one.getId().equals(other.getId()); + return (one.getId() == null) || (other.getId() == null) || !one.getId().equals(other.getId()); } @Override @@ -144,14 +139,15 @@ public class ScenarioDAO extends GenericDAOHibernate implements return Collections.emptyList(); } - Criteria c = getSession().createCriteria(Scenario.class).add( - Restrictions.eq("predecessor", scenario)); - return (List) c.list(); + return getSession() + .createCriteria(Scenario.class) + .add(Restrictions.eq("predecessor", scenario)) + .list(); } @Override public List getDerivedScenarios(Scenario scenario) { - List result = new ArrayList(); + List result = new ArrayList<>(); List children = findByPredecessor(scenario); result.addAll(children); @@ -165,8 +161,11 @@ public class ScenarioDAO extends GenericDAOHibernate implements @Override public void updateDerivedScenariosWithNewVersion( - OrderVersion previousOrderVersion, Order order, - Scenario currentScenario, OrderVersion newOrderVersion) { + OrderVersion previousOrderVersion, + Order order, + Scenario currentScenario, + OrderVersion newOrderVersion) { + for (Scenario each : getDerivedScenarios(currentScenario)) { if (each.usesVersion(previousOrderVersion, order)) { if (newOrderVersion == null) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineGroupTemplate.java b/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineGroupTemplate.java index 0cd0ace9b..96c62a7ce 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineGroupTemplate.java +++ b/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineGroupTemplate.java @@ -44,8 +44,8 @@ import org.libreplan.business.trees.ITreeParentNode; public class OrderLineGroupTemplate extends OrderElementTemplate implements ITreeParentNode { - private final CriterionRequirementTemplateHandler criterionRequirementTemplateHandler = CriterionRequirementTemplateHandler - .getInstance(); + private final CriterionRequirementTemplateHandler criterionRequirementTemplateHandler = + CriterionRequirementTemplateHandler.getInstance(); private final class ChildrenManipulator extends TreeNodeOnListWithSchedulingState { @@ -121,7 +121,7 @@ public class OrderLineGroupTemplate extends OrderElementTemplate implements } protected static T create(T beingBuilt, - OrderLineGroup group) { + OrderLineGroup group) { OrderElementTemplate.create(beingBuilt, group); List result = buildChildrenTemplates(beingBuilt, group.getChildren()); @@ -165,7 +165,7 @@ public class OrderLineGroupTemplate extends OrderElementTemplate implements private static List buildChildrenTemplates( OrderLineGroupTemplate parent, List children) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (OrderElement each : children) { OrderElementTemplate template = each.createTemplate(); template.setParent(parent); @@ -174,7 +174,7 @@ public class OrderLineGroupTemplate extends OrderElementTemplate implements return result; } - private List children = new ArrayList(); + private List children = new ArrayList<>(); @Override public List getChildrenTemplates() { @@ -207,7 +207,7 @@ public class OrderLineGroupTemplate extends OrderElementTemplate implements @Override public void replace(OrderElementTemplate previousChild, - OrderElementTemplate newChild) { + OrderElementTemplate newChild) { getManipulator().replace(previousChild, newChild); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineTemplate.java b/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineTemplate.java index 1cba6d221..37534bed0 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineTemplate.java +++ b/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineTemplate.java @@ -46,23 +46,26 @@ import org.libreplan.business.orders.entities.OrderLineGroup; public class OrderLineTemplate extends OrderElementTemplate { @Valid - private Set hoursGroups = new HashSet(); + private Set hoursGroups = new HashSet<>(); private Integer lastHoursGroupSequenceCode = 0; + private BigDecimal budget = BigDecimal.ZERO.setScale(2); + + private HoursGroupOrderLineTemplateHandler hoursGroupOrderLineTemplateHandler = + HoursGroupOrderLineTemplateHandler.getInstance(); + public static OrderLineTemplate create(OrderLine orderLine) { OrderLineTemplate beingBuilt = new OrderLineTemplate(); copyHoursGroup(orderLine.getHoursGroups(), beingBuilt); beingBuilt.setBudget(orderLine.getBudget()); + return create(beingBuilt, orderLine); } - private static void copyHoursGroup( - final Collection hoursGroups, - OrderLineTemplate orderLineTemplate) { + private static void copyHoursGroup(final Collection hoursGroups, OrderLineTemplate orderLineTemplate) { for (HoursGroup each: hoursGroups) { - orderLineTemplate.addHoursGroup(HoursGroup.copyFrom(each, - orderLineTemplate)); + orderLineTemplate.addHoursGroup(HoursGroup.copyFrom(each, orderLineTemplate)); } } @@ -70,17 +73,16 @@ public class OrderLineTemplate extends OrderElementTemplate { return createNew(new OrderLineTemplate()); } - private BigDecimal budget = BigDecimal.ZERO.setScale(2); - protected T setupElementParts(T orderElement) { super.setupElementParts(orderElement); setupHoursGroups((OrderLine) orderElement); setupBudget((OrderLine) orderElement); + return orderElement; } private void setupHoursGroups(OrderLine orderLine) { - Set result = new HashSet(); + Set result = new HashSet<>(); for (HoursGroup each: getHoursGroups()) { result.add(HoursGroup.copyFrom(each, orderLine)); } @@ -105,12 +107,13 @@ public class OrderLineTemplate extends OrderElementTemplate { public OrderLineGroupTemplate toContainer() { OrderLineGroupTemplate result = OrderLineGroupTemplate.createNew(); copyTo(result); + return result; } @Override public List getChildren() { - return new ArrayList(); + return new ArrayList<>(); } @Override @@ -123,18 +126,23 @@ public class OrderLineTemplate extends OrderElementTemplate { if (getWorkHours() != 0) { return false; } + if (!getDirectCriterionRequirements().isEmpty()) { return false; } + if (!getAdvanceAssignmentTemplates().isEmpty()) { return false; } + if (!getQualityForms().isEmpty()) { return false; } + if (!getLabels().isEmpty()) { return false; } + if (!getMaterialAssignments().isEmpty()) { return false; } @@ -144,10 +152,12 @@ public class OrderLineTemplate extends OrderElementTemplate { @Override public OrderElement createElement(OrderLineGroup parent) { - OrderLine line = setupSchedulingStateType(setupVersioningInfo(parent, - OrderLine.createOrderLineWithUnfixedPercentage(getWorkHours()))); + OrderLine line = setupSchedulingStateType( + setupVersioningInfo(parent, OrderLine.createOrderLineWithUnfixedPercentage(getWorkHours()))); + line.initializeTemplate(this); parent.add(line); + return setupElementParts(line); } @@ -161,7 +171,7 @@ public class OrderLineTemplate extends OrderElementTemplate { } public void incrementLastHoursGroupSequenceCode() { - if(lastHoursGroupSequenceCode==null){ + if (lastHoursGroupSequenceCode == null) { lastHoursGroupSequenceCode = 0; } lastHoursGroupSequenceCode++; @@ -178,7 +188,7 @@ public class OrderLineTemplate extends OrderElementTemplate { @Override public List getHoursGroups() { - return new ArrayList(hoursGroups); + return new ArrayList<>(hoursGroups); } public Set myHoursGroups() { @@ -206,9 +216,6 @@ public class OrderLineTemplate extends OrderElementTemplate { recalculateHoursGroups(); } - private HoursGroupOrderLineTemplateHandler hoursGroupOrderLineTemplateHandler = HoursGroupOrderLineTemplateHandler - .getInstance(); - public void setWorkHours(Integer workHours) throws IllegalArgumentException { hoursGroupOrderLineTemplateHandler.setWorkHours(this, workHours); } @@ -226,8 +233,7 @@ public class OrderLineTemplate extends OrderElementTemplate { } public void setBudget(BigDecimal budget) { - Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0, - "budget cannot be negative"); + Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0, "budget cannot be negative"); this.budget = budget.setScale(2); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderTemplate.java b/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderTemplate.java index 2d6fc98cd..02803db8c 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderTemplate.java +++ b/libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderTemplate.java @@ -36,14 +36,15 @@ import org.libreplan.business.scenarios.entities.Scenario; */ public class OrderTemplate extends OrderLineGroupTemplate { + private BaseCalendar calendar; + public static OrderTemplate create(Order order) { OrderTemplate beingBuilt = new OrderTemplate(); beingBuilt.calendar = order.getCalendar(); + return create(beingBuilt, order); } - private BaseCalendar calendar; - @Override public OrderElement createElement(OrderLineGroup parent) { throw new UnsupportedOperationException(); @@ -51,11 +52,11 @@ public class OrderTemplate extends OrderLineGroupTemplate { public Order createOrder(Scenario currentScenario) { Order order = Order.create(); - order.setVersionForScenario(currentScenario, OrderVersion - .createInitialVersion(currentScenario)); + order.setVersionForScenario(currentScenario, OrderVersion.createInitialVersion(currentScenario)); order.useSchedulingDataFor(currentScenario); order.setCalendar(calendar); order.initializeTemplate(this); + return setupGroupParts(setupSchedulingStateType(order)); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/PredefinedProfiles.java b/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/PredefinedProfiles.java index fbeb451a4..c6c08829a 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/PredefinedProfiles.java +++ b/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/PredefinedProfiles.java @@ -31,7 +31,7 @@ import static org.libreplan.business.users.entities.UserRole.*; * Profiles} * * @author Manuel Rego Casasnovas - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public enum PredefinedProfiles { diff --git a/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/ProfilesBootstrap.java b/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/ProfilesBootstrap.java index 4f6e46c14..576260b8f 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/ProfilesBootstrap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/users/bootstrap/ProfilesBootstrap.java @@ -21,6 +21,7 @@ package org.libreplan.business.users.bootstrap; import org.libreplan.business.users.daos.IProfileDAO; import org.libreplan.business.users.entities.Profile; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -33,7 +34,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Manuel Rego Casasnovas */ @Component -@Scope("singleton") +@Scope(BeanDefinition.SCOPE_SINGLETON) public class ProfilesBootstrap implements IProfileBootstrap { @Autowired diff --git a/libreplan-business/src/main/java/org/libreplan/business/users/daos/IUserDAO.java b/libreplan-business/src/main/java/org/libreplan/business/users/daos/IUserDAO.java index 1d868eb1b..8915ac425 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/users/daos/IUserDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/users/daos/IUserDAO.java @@ -35,22 +35,20 @@ import org.libreplan.business.users.entities.User; * * @author Fernando Bellas Permuy * @author Manuel Rego Casasnovas - * @author Vova Perebykivskiy + * @author Vova Perebykivskyi */ public interface IUserDAO extends IGenericDAO{ /** * NOTE: Username comparison is case-insensitive. */ - public User findByLoginName(String loginName) - throws InstanceNotFoundException; + public User findByLoginName(String loginName) throws InstanceNotFoundException; /** * NOTE: Username comparison is case-insensitive, and the method is executed * in another transaction. */ - public User findByLoginNameAnotherTransaction(String loginName) - throws InstanceNotFoundException; + public User findByLoginNameAnotherTransaction(String loginName) throws InstanceNotFoundException; /** * NOTE: Username comparison is case-insensitive. @@ -73,8 +71,7 @@ public interface IUserDAO extends IGenericDAO{ * @return a {@link User} object. * @throws InstanceNotFoundException */ - User findByLoginNameNotDisabled(String loginName) - throws InstanceNotFoundException; + User findByLoginNameNotDisabled(String loginName) throws InstanceNotFoundException; /** * Retrieves a list of the User entities which attribute 'disabled' has diff --git a/libreplan-business/src/main/java/org/libreplan/business/users/daos/UserDAO.java b/libreplan-business/src/main/java/org/libreplan/business/users/daos/UserDAO.java index 9160857a6..803d5724c 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/users/daos/UserDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/users/daos/UserDAO.java @@ -24,7 +24,7 @@ package org.libreplan.business.users.daos; import java.util.ArrayList; import java.util.List; -import org.hibernate.Criteria; +import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.libreplan.business.common.daos.GenericDAOHibernate; @@ -73,12 +73,13 @@ public class UserDAO extends GenericDAOHibernate implements IUserDAO @Override public User findByLoginNameNotDisabled(String loginName) throws InstanceNotFoundException { - Criteria c = getSession().createCriteria(User.class); - c.add(Restrictions.eq("loginName", loginName).ignoreCase()); - c.add(Restrictions.eq("disabled", false)); - User user = (User) c.uniqueResult(); + User user = (User) getSession() + .createCriteria(User.class) + .add(Restrictions.eq("loginName", loginName).ignoreCase()) + .add(Restrictions.eq("disabled", false)) + .uniqueResult(); - if ( user == null ) { + if (user == null) { throw new InstanceNotFoundException(loginName, User.class.getName()); } else { return user; @@ -88,11 +89,8 @@ public class UserDAO extends GenericDAOHibernate implements IUserDAO @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) - public User findByLoginNameAnotherTransaction(String loginName) - throws InstanceNotFoundException { - + public User findByLoginNameAnotherTransaction(String loginName) throws InstanceNotFoundException { return findByLoginName(loginName); - } @Override @@ -114,33 +112,32 @@ public class UserDAO extends GenericDAOHibernate implements IUserDAO @Override public List listNotDisabled() { - Criteria c = getSession().createCriteria(User.class); - c.add(Restrictions.eq("disabled", false)); - - return c.list(); + return getSession() + .createCriteria(User.class) + .add(Restrictions.eq("disabled", false)) + .list(); } @Override public List findByLastConnectedScenario(Scenario scenario) { - Criteria c = getSession().createCriteria(User.class); - c.add(Restrictions.eq("lastConnectedScenario", scenario)); - - return c.list(); + return getSession() + .createCriteria(User.class) + .add(Restrictions.eq("lastConnectedScenario", scenario)) + .list(); } private List getOrderAuthorizationsByUser(User user) { - List orderAuthorizations = getSession() + return getSession() .createCriteria(UserOrderAuthorization.class) - .add(Restrictions.eq("user", user)).list(); - - return orderAuthorizations; + .add(Restrictions.eq("user", user)) + .list(); } @Override public List getUnboundUsers(Worker worker) { List result = new ArrayList<>(); boolean condition; - for (User user : getUsersOrderByLoginame()) { + for (User user : getUsersOrderByLoginName()) { condition = (user.getWorker() == null) || (worker != null && !worker.isNewObject() && worker.getId().equals(user.getWorker().getId())); @@ -152,8 +149,11 @@ public class UserDAO extends GenericDAOHibernate implements IUserDAO return result; } - private List getUsersOrderByLoginame() { - return getSession().createCriteria(User.class).addOrder(org.hibernate.criterion.Order.asc("loginName")).list(); + private List getUsersOrderByLoginName() { + return getSession() + .createCriteria(User.class) + .addOrder(Order.asc("loginName")) + .list(); } @Override diff --git a/libreplan-business/src/main/java/org/libreplan/business/users/entities/User.java b/libreplan-business/src/main/java/org/libreplan/business/users/entities/User.java index 9bd42ec5c..f4ae9fe98 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/users/entities/User.java +++ b/libreplan-business/src/main/java/org/libreplan/business/users/entities/User.java @@ -70,7 +70,9 @@ public class User extends BaseEntity implements IHumanIdentifiable{ private Scenario lastConnectedScenario; - // if a user is a LibrePlan user or not (ldap) + /** + * If a user is a LibrePlan user or not (ldap). + */ private Boolean librePlanUser = true; private boolean expandCompanyPlanningViewCharts = false; @@ -100,8 +102,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{ /** * Necessary for Hibernate. Please, do not call it. */ - public User() { - } + public User() {} private User(String loginName, String password, Set roles, Set profiles) { this.loginName = loginName; @@ -171,7 +172,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{ /** * Retrieves UserRoles from related Profiles and returns them together with - * the UserRoles related directly to the User entity + * the UserRoles related directly to the User entity. * * @return A list of UserRole objects */ @@ -185,7 +186,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{ } /** - * Checks if current user is in the requested role + * Checks if current user is in the requested role. */ public boolean isInRole(UserRole role) { if ( roles.contains(role) ) { @@ -254,9 +255,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{ return !userDAO.existsByLoginNameAnotherTransaction(loginName); } else { try { - User u = userDAO.findByLoginNameAnotherTransaction(loginName); - - return u.getId().equals(getId()); + return userDAO.findByLoginNameAnotherTransaction(loginName).getId().equals(getId()); } catch (InstanceNotFoundException e) { return true; } @@ -366,6 +365,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{ this.name = name; } + @Override public String toString() { return name; } @@ -419,6 +419,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{ public Integer getProjectsFilterPeriodSince() { return projectsFilterPeriodSince; } + public void setProjectsFilterPeriodSince(Integer period) { projectsFilterPeriodSince = period; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/OnCopy.java b/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/OnCopy.java index 542b333ec..f9e758969 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/OnCopy.java +++ b/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/OnCopy.java @@ -28,11 +28,10 @@ import java.lang.annotation.Target; /** * @author Óscar González Fernández - * */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface OnCopy { - public Strategy value(); + Strategy value(); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/workingday/EffortDuration.java b/libreplan-business/src/main/java/org/libreplan/business/workingday/EffortDuration.java index 95548ff89..4599695db 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/workingday/EffortDuration.java +++ b/libreplan-business/src/main/java/org/libreplan/business/workingday/EffortDuration.java @@ -36,34 +36,45 @@ import org.apache.commons.lang3.math.Fraction; /** *

- * It represents some amount of effort. It's composed by some hours, minutes and - * seconds. Less granularity than a second can't be specified. + * It represents some amount of effort. + * It's composed by some hours, minutes and seconds. + * Less granularity than a second can't be specified. *

*

- * This object can represent the predicted amount of work that a task takes, the - * scheduled amount of work for a working day, the amount of effort that a - * worker can work in a given day, etc. + * This object can represent the predicted amount of work that a task takes, + * the scheduled amount of work for a working day, the amount of effort that a worker can work in a given day, etc. *

* * @author Óscar González Fernández - * */ public class EffortDuration implements Comparable { + private static final Pattern lenientEffortDurationSpecification = Pattern.compile("(\\d+)(\\s*:\\s*\\d+\\s*)*"); + + private static final Pattern contiguousDigitsPattern = Pattern.compile("\\d+"); + + private final int seconds; + + private EffortDuration(int seconds) { + Validate.isTrue(seconds >= 0, "seconds cannot be negative"); + this.seconds = seconds; + } public enum Granularity { - HOURS(3600), MINUTES(60), SECONDS(1); - - static Granularity[] fromMoreCoarseToLessCoarse() { - return Granularity.values(); - } + HOURS(3600), + MINUTES(60), + SECONDS(1); private final int secondsPerUnit; - private Granularity(int secondsPerUnit) { + Granularity(int secondsPerUnit) { this.secondsPerUnit = secondsPerUnit; } + static Granularity[] fromMoreCoarseToLessCoarse() { + return Granularity.values(); + } + public int toSeconds(int amount) { return secondsPerUnit * amount; } @@ -73,24 +84,20 @@ public class EffortDuration implements Comparable { } } - private static final Pattern lenientEffortDurationSpecification = Pattern.compile("(\\d+)(\\s*:\\s*\\d+\\s*)*"); - - private static final Pattern contiguousDigitsPattern = Pattern.compile("\\d+"); - /** - * If an {@link EffortDuration} can't be parsed null is - * returned. The hours field at least is required, the next fields are the - * minutes and seconds. If there is more than one field, they are separated - * by colons. + * If an {@link EffortDuration} can't be parsed null is returned. + * The hours field at least is required, the next fields are the minutes and seconds. + * If there is more than one field, they are separated by colons. * * @param string - * @return + * @return {@link EffortDuration} */ public static EffortDuration parseFromFormattedString(String string) { Matcher matcher = lenientEffortDurationSpecification.matcher(string); if (matcher.find()) { List parts = scan(contiguousDigitsPattern, string); assert parts.size() >= 1; + return EffortDuration.hours(retrieveNumber(0, parts)) .and(retrieveNumber(1, parts), Granularity.MINUTES) .and(retrieveNumber(2, parts), Granularity.SECONDS); @@ -99,7 +106,7 @@ public class EffortDuration implements Comparable { } private static List scan(Pattern pattern, String text) { - List result = new ArrayList(); + List result = new ArrayList<>(); Matcher matcher = pattern.matcher(text); while (matcher.find()) { result.add(matcher.group()); @@ -108,19 +115,15 @@ public class EffortDuration implements Comparable { } private static int retrieveNumber(int i, List parts) { - if (i >= parts.size()) { - return 0; - } - return Integer.parseInt(parts.get(i)); + return i >= parts.size() ? 0 : Integer.parseInt(parts.get(i)); } public interface IEffortFrom { - public EffortDuration from(T each); + EffortDuration from(T each); } - public static EffortDuration sum(Iterable collection, - IEffortFrom effortFrom) { + public static EffortDuration sum(Iterable collection, IEffortFrom effortFrom) { EffortDuration result = zero(); for (T each : collection) { result = result.plus(effortFrom.from(each)); @@ -130,7 +133,6 @@ public class EffortDuration implements Comparable { public static EffortDuration sum(EffortDuration... summands) { return sum(Arrays.asList(summands), new IEffortFrom() { - @Override public EffortDuration from(EffortDuration each) { return each; @@ -160,15 +162,8 @@ public class EffortDuration implements Comparable { public static EffortDuration fromHoursAsBigDecimal(BigDecimal hours) { BigDecimal secondsPerHour = new BigDecimal(3600); - return elapsing(hours.multiply(secondsPerHour).intValue(), - Granularity.SECONDS); - } - private final int seconds; - - private EffortDuration(int seconds) { - Validate.isTrue(seconds >= 0, "seconds cannot be negative"); - this.seconds = seconds; + return elapsing(hours.multiply(secondsPerHour).intValue(), Granularity.SECONDS); } public int getHours() { @@ -195,6 +190,7 @@ public class EffortDuration implements Comparable { public boolean equals(Object obj) { if (obj instanceof EffortDuration) { EffortDuration other = (EffortDuration) obj; + return getSeconds() == other.getSeconds(); } return false; @@ -206,8 +202,7 @@ public class EffortDuration implements Comparable { } public EnumMap decompose() { - EnumMap result = new EnumMap( - Granularity.class); + EnumMap result = new EnumMap<>(Granularity.class); int remainder = seconds; for (Granularity each : Granularity.fromMoreCoarseToLessCoarse()) { int value = each.convertFromSeconds(remainder); @@ -215,19 +210,22 @@ public class EffortDuration implements Comparable { result.put(each, value); } assert remainder == 0; + return result; } @Override public int compareTo(EffortDuration other) { Validate.notNull(other); + return seconds - other.seconds; } /** - * Multiplies this duration by a scalar
- * Warning: This method can cause an integer overflow and the result - * would be incorrect. + * Multiplies this duration by a scalar. + * + *
+ * Warning: This method can cause an integer overflow and the result would be incorrect. * @param n * @return a duration that is the multiply of n and this */ @@ -236,7 +234,8 @@ public class EffortDuration implements Comparable { } /** - * Divides this duration by a scalar + * Divides this duration by a scalar. + * * @param n * a number greater than zero * @return a new duration that is the result of dividing this @@ -249,9 +248,11 @@ public class EffortDuration implements Comparable { /** *

- * Divides this duration by other returning the quotient. + * Divides this duration by other returning the quotient. *

+ * * There can be a remainder left. + * * @see #remainderFor(EffortDuration) * @param other * @return @@ -266,25 +267,21 @@ public class EffortDuration implements Comparable { /** *

- * Divides this duration by other (using total seconds) returning the - * quotient as BigDecimal. + * Divides this duration by other (using total seconds) returning the quotient as BigDecimal. *

+ * * @param other * @return */ public BigDecimal dividedByAndResultAsBigDecimal(EffortDuration other) { - if (other.isZero()) { - return BigDecimal.ZERO; - } - else { - return new BigDecimal(this.getSeconds()).divide( - new BigDecimal(other.getSeconds()), 8, BigDecimal.ROUND_HALF_EVEN); - } + return other.isZero() + ? BigDecimal.ZERO + : new BigDecimal(this.getSeconds()) + .divide(new BigDecimal(other.getSeconds()), 8, BigDecimal.ROUND_HALF_EVEN); } /** - * Calculates the remainder resulting of doing the integer division of both - * durations + * Calculates the remainder resulting of doing the integer division of both durations. * * @see #divideBy(EffortDuration) * @param other @@ -292,13 +289,15 @@ public class EffortDuration implements Comparable { */ public EffortDuration remainderFor(EffortDuration other) { int dividend = divideBy(other); + return this.minus(other.multiplyBy(dividend)); } /** - * Pluses two {@link EffortDuration}.
- * Warning: This method can cause an integer overflow and the result - * would be incorrect. + * Pluses two {@link EffortDuration}. + *
+ * Warning: This method can cause an integer overflow and the result would be incorrect. + * * @param other * @return a duration that is the sum of this * {@link EffortDuration} and the other duration @@ -312,9 +311,9 @@ public class EffortDuration implements Comparable { } /** - * Substracts two {@link EffortDuration}. Because {@link EffortDuration - * durations} cannot be negative this must be bigger than the - * parameter or the same + * Substracts two {@link EffortDuration}. + * Because {@link EffortDuration durations} cannot be negative this must be bigger than the + * parameter or the same. * * @param duration * @return the result of substracting the two durations @@ -322,47 +321,43 @@ public class EffortDuration implements Comparable { * if the parameter is bigger than this */ public EffortDuration minus(EffortDuration duration) { - Validate.isTrue(this.compareTo(duration) >= 0, - "minued must not be smaller than subtrahend"); + Validate.isTrue(this.compareTo(duration) >= 0, "minued must not be smaller than subtrahend"); + return new EffortDuration(seconds - duration.seconds); } public BigDecimal toHoursAsDecimalWithScale(int scale) { BigDecimal result = BigDecimal.ZERO; final BigDecimal secondsPerHour = new BigDecimal(3600); + for (Entry each : decompose().entrySet()) { - BigDecimal seconds = new BigDecimal(each.getKey().toSeconds( - each.getValue())); - result = result.add(seconds.divide(secondsPerHour, scale, - BigDecimal.ROUND_HALF_UP)); + BigDecimal seconds = new BigDecimal(each.getKey().toSeconds(each.getValue())); + result = result.add(seconds.divide(secondsPerHour, scale, BigDecimal.ROUND_HALF_UP)); } return result; } /** *

- * Converts this duration in a number of hours. Uses a typical half up - * round, so for example one hour and half is converted to two hours. There - * is an exception though, when the duration is less than one hour and is - * not zero it's returned one. This is handy for avoiding infinite loops in - * some algorithms; when all code is converted to use {@link EffortDuration - * Effort Durations} this will no longer be necessary. + * Converts this duration in a number of hours. + * Uses a typical half up round, so for example one hour and half is converted to two hours. + * There is an exception though, when the duration is less than one hour and is not zero it's returned one. + * This is handy for avoiding infinite loops in some algorithms; + * when all code is converted to use {@link EffortDuration Effort Durations} this will no longer be necessary. *

+ * * So there are three cases: *
    - *
  • the duration is zero, 0 is returned
  • - *
  • if duration > 0 and duration < 1, 1 is returned
  • - *
  • if duration >= 1, typical half up round is done. For example 1 hour - * and 20 minutes returns 1 hour, 1 hour and 30 minutes 2 hours
  • + *
  • the duration is zero, 0 is returned
  • + *
  • if duration > 0 and duration < 1, 1 is returned
  • + *
  • if duration >= 1, typical half up round is done.
  • *
+ * For example 1 hour and 20 minutes returns 1 hour, 1 hour and 30 minutes 2 hours. * * @return an integer number of hours */ public int roundToHours() { - if (this.isZero()) { - return 0; - } - return Math.max(1, roundHalfUpToHours(this.decompose())); + return this.isZero() ? 0 : Math.max(1, roundHalfUpToHours(this.decompose())); } public static EffortDuration min(EffortDuration... durations) { @@ -381,6 +376,7 @@ public class EffortDuration implements Comparable { int seconds = components.get(Granularity.SECONDS); int minutes = components.get(Granularity.MINUTES) + (seconds < 30 ? 0 : 1); int hours = components.get(Granularity.HOURS) + (minutes < 30 ? 0 : 1); + return hours; } @@ -389,29 +385,25 @@ public class EffortDuration implements Comparable { Integer hours = valuesForEachUnit.get(Granularity.HOURS); Integer minutes = valuesForEachUnit.get(Granularity.MINUTES); Integer seconds = valuesForEachUnit.get(Granularity.SECONDS); + return String.format("%d:%02d:%02d", hours, minutes, seconds); } public String toFormattedString() { - EnumMap byGranularity = this.atNearestMinute() - .decompose(); + EnumMap byGranularity = this.atNearestMinute().decompose(); int hours = byGranularity.get(Granularity.HOURS); int minutes = byGranularity.get(Granularity.MINUTES); - if (minutes == 0) { - return String.format("%d", hours); - } else { - return String.format("%d:%02d", hours, minutes); - } + + return minutes == 0 ? String.format("%d", hours) : String.format("%d:%02d", hours, minutes); } public EffortDuration atNearestMinute() { EnumMap decompose = this.decompose(); int seconds = decompose.get(Granularity.SECONDS); - if (seconds >= 30) { - return this.plus(EffortDuration.seconds(60 - seconds)); - } else { - return this.minus(EffortDuration.seconds(seconds)); - } + + return seconds >= 30 + ? this.plus(EffortDuration.seconds(60 - seconds)) + : this.minus(EffortDuration.seconds(seconds)); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportDAO.java b/libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportDAO.java index 3c16fef78..331f55d11 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportDAO.java @@ -34,7 +34,6 @@ import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.joda.time.LocalDate; import org.libreplan.business.common.IAdHocTransactionService; -import org.libreplan.business.common.IOnTransaction; import org.libreplan.business.common.daos.IntegrationEntityDAO; import org.libreplan.business.common.entities.PersonalTimesheetsPeriodicityEnum; import org.libreplan.business.common.exceptions.InstanceNotFoundException; @@ -51,14 +50,13 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; /** - * Dao for {@link WorkReportDAO} + * Dao for {@link WorkReportDAO}. * * @author Diego Pino García */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) -public class WorkReportDAO extends IntegrationEntityDAO - implements IWorkReportDAO { +public class WorkReportDAO extends IntegrationEntityDAO implements IWorkReportDAO { @Autowired private IAdHocTransactionService adHocTransactionService; @@ -69,11 +67,15 @@ public class WorkReportDAO extends IntegrationEntityDAO @Autowired private IWorkReportTypeDAO workReportTypeDAO; + private final String WORK_REPORT_TYPE_COLUMN = "workReportType"; + @SuppressWarnings("unchecked") @Override public List getAllByWorkReportType(WorkReportType workReportType) { - final Criteria criteria = getSession().createCriteria(WorkReport.class); - return criteria.add(Restrictions.eq("workReportType", workReportType)).list(); + return getSession() + .createCriteria(WorkReport.class) + .add(Restrictions.eq(WORK_REPORT_TYPE_COLUMN, workReportType)) + .list(); } @Override @@ -89,25 +91,20 @@ public class WorkReportDAO extends IntegrationEntityDAO private void forceOrdersUnproxied() { List elements = adHocTransactionService - .runOnAnotherReadOnlyTransaction(new IOnTransaction>() { + .runOnAnotherReadOnlyTransaction(() -> getOrderElementsAssociatedWithWorkReports()); - @Override - public List execute() { - return getOrderElementsAssociatedWithWorkReports(); - } - }); orderDAO.loadOrdersAvoidingProxyFor(elements); } private List getOrderElementsAssociatedWithWorkReports() { - Set result = new HashSet(); - result.addAll(elementsFrom(getSession().createQuery( - "select w.orderElement from WorkReport w"))); - result - .addAll(elementsFrom(getSession() - .createQuery( - "select line.orderElement from WorkReport w JOIN w.workReportLines line"))); - return new ArrayList(result); + Set result = new HashSet<>(); + + result.addAll(elementsFrom(getSession().createQuery("select w.orderElement from WorkReport w"))); + + result.addAll(elementsFrom( + getSession().createQuery("select line.orderElement from WorkReport w JOIN w.workReportLines line"))); + + return new ArrayList<>(result); } @SuppressWarnings("unchecked") @@ -119,9 +116,11 @@ public class WorkReportDAO extends IntegrationEntityDAO public int getFirstReportYear() { final String query = "select min(w.date) from WorkReportLine w"; Date minDate = (Date) getSession().createQuery(query).uniqueResult(); + if (minDate != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(minDate); + return calendar.get(Calendar.YEAR); } return 0; @@ -131,9 +130,11 @@ public class WorkReportDAO extends IntegrationEntityDAO public int getLastReportYear() { final String query = "select max(w.date) from WorkReportLine w"; Date maxDate = (Date) getSession().createQuery(query).uniqueResult(); + if (maxDate != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(maxDate); + return calendar.get(Calendar.YEAR); } return 0; @@ -141,26 +142,23 @@ public class WorkReportDAO extends IntegrationEntityDAO @Override @SuppressWarnings("unchecked") - public WorkReport getPersonalTimesheetWorkReport(Resource resource, - LocalDate date, PersonalTimesheetsPeriodicityEnum periodicity) { + public WorkReport getPersonalTimesheetWorkReport( + Resource resource, LocalDate date, PersonalTimesheetsPeriodicityEnum periodicity) { + Criteria criteria = getSession().createCriteria(WorkReport.class); - criteria.add(Restrictions.eq("workReportType", - getPersonalTimesheetsWorkReportType())); - List personalTimesheets = criteria.add( - Restrictions.eq("resource", resource)).list(); + criteria.add(Restrictions.eq(WORK_REPORT_TYPE_COLUMN, getPersonalTimesheetsWorkReportType())); + List personalTimesheets = criteria.add(Restrictions.eq("resource", resource)).list(); LocalDate start = periodicity.getStart(date); LocalDate end = periodicity.getEnd(date); for (WorkReport workReport : personalTimesheets) { - Set workReportLines = workReport - .getWorkReportLines(); - if (workReportLines.size() > 0) { - LocalDate workReportDate = LocalDate - .fromDateFields(workReportLines.iterator().next() - .getDate()); - if (workReportDate.compareTo(start) >= 0 - && workReportDate.compareTo(end) <= 0) { + Set workReportLines = workReport.getWorkReportLines(); + + if ( !workReportLines.isEmpty() ) { + LocalDate workReportDate = LocalDate.fromDateFields(workReportLines.iterator().next().getDate()); + + if (workReportDate.compareTo(start) >= 0 && workReportDate.compareTo(end) <= 0) { return workReport; } } @@ -172,37 +170,33 @@ public class WorkReportDAO extends IntegrationEntityDAO private WorkReportType getPersonalTimesheetsWorkReportType() { WorkReportType workReportType; try { - workReportType = workReportTypeDAO - .findUniqueByName(PredefinedWorkReportTypes.PERSONAL_TIMESHEETS - .getName()); - } catch (NonUniqueResultException e) { - throw new RuntimeException(e); - } catch (InstanceNotFoundException e) { + workReportType = + workReportTypeDAO.findUniqueByName(PredefinedWorkReportTypes.PERSONAL_TIMESHEETS.getName()); + + } catch (NonUniqueResultException | InstanceNotFoundException e) { throw new RuntimeException(e); } + return workReportType; } @Override public boolean isAnyPersonalTimesheetAlreadySaved() { - WorkReportType workReportType = getPersonalTimesheetsWorkReportType(); - - Criteria criteria = getSession().createCriteria(WorkReport.class); - criteria.add(Restrictions.eq("workReportType", workReportType)); - return criteria.list().isEmpty(); + return getSession() + .createCriteria(WorkReport.class) + .add(Restrictions.eq(WORK_REPORT_TYPE_COLUMN, getPersonalTimesheetsWorkReportType())) + .list() + .isEmpty(); } @Override @SuppressWarnings("unchecked") - public List findPersonalTimesheetsByResourceAndOrderElement( - Resource resource) { - Criteria criteria = getSession().createCriteria(WorkReport.class); - - criteria.add(Restrictions.eq("workReportType", - getPersonalTimesheetsWorkReportType())); - criteria.add(Restrictions.eq("resource", resource)); - - return criteria.list(); + public List findPersonalTimesheetsByResourceAndOrderElement(Resource resource) { + return getSession() + .createCriteria(WorkReport.class) + .add(Restrictions.eq(WORK_REPORT_TYPE_COLUMN, getPersonalTimesheetsWorkReportType())) + .add(Restrictions.eq("resource", resource)) + .list(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/IWorkReportsElements.java b/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/IWorkReportsElements.java index 3830305f4..1ca369ce9 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/IWorkReportsElements.java +++ b/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/IWorkReportsElements.java @@ -27,8 +27,7 @@ import org.libreplan.business.resources.entities.Resource; import org.libreplan.business.workreports.valueobjects.DescriptionValue; /** - * Interface which must be implemented by {@link WorkReport} and - * {@link WorkReportLine} + * Interface which must be implemented by {@link WorkReport} and {@link WorkReportLine}. * * @author Ignacio Diaz Teijido * diff --git a/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/WorkReport.java b/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/WorkReport.java index 6677c8fb3..0a04bb3fd 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/WorkReport.java +++ b/libreplan-business/src/main/java/org/libreplan/business/workreports/entities/WorkReport.java @@ -55,12 +55,46 @@ import org.libreplan.business.workreports.valueobjects.DescriptionValue; * @author Susana Montes Pedreira * @author Manuel Rego Casasnovas */ -public class WorkReport extends IntegrationEntity implements - IWorkReportsElements { +public class WorkReport extends IntegrationEntity implements IWorkReportsElements { - public static final String DATE = "date"; - public static final String RESOURCE = "resource"; - public static final String ORDERELEMENT = "orderElement"; + private Date date; + + private WorkReportType workReportType; + + private Resource resource; + + private OrderElement orderElement; + + private Set