Added test for BAC value.

Code refactoring.
(cherry picked from commit 0f00d11)
This commit is contained in:
Vova Perebykivskiy 2016-04-15 19:30:05 +03:00 committed by Dgray16
parent 0763cbfe02
commit 529d3b738e
75 changed files with 2235 additions and 2585 deletions

View file

@ -33,11 +33,10 @@ import org.zkoss.zk.ui.event.Event;
public class CommandOnTaskContextualized<T> {
public static <T> CommandOnTaskContextualized<T> create(
ICommandOnTask<T> commandOnTask, IDomainAndBeansMapper<T> mapper,
IContext<T> context) {
return new CommandOnTaskContextualized<T>(commandOnTask, mapper,
context);
public static <T> CommandOnTaskContextualized<T> create(ICommandOnTask<T> commandOnTask,
IDomainAndBeansMapper<T> mapper, IContext<T> context) {
return new CommandOnTaskContextualized<T>(commandOnTask, mapper, context);
}
private final ICommandOnTask<T> commandOnTask;
@ -46,16 +45,17 @@ public class CommandOnTaskContextualized<T> {
private final IDomainAndBeansMapper<T> mapper;
private CommandOnTaskContextualized(ICommandOnTask<T> commandOnTask,
IDomainAndBeansMapper<T> mapper, IContext<T> context) {
private CommandOnTaskContextualized(ICommandOnTask<T> commandOnTask, IDomainAndBeansMapper<T> mapper,
IContext<T> context) {
this.commandOnTask = commandOnTask;
this.mapper = mapper;
this.context = context;
}
public void doAction(TaskComponent taskComponent) {
doAction(ContextRelativeToOtherComponent.makeRelativeTo(context,
taskComponent), domainObjectFor(taskComponent.getTask()));
doAction(
ContextRelativeToOtherComponent.makeRelativeTo(context, taskComponent),
domainObjectFor(taskComponent.getTask()));
}
public void doAction(Task task) {
@ -67,8 +67,9 @@ public class CommandOnTaskContextualized<T> {
}
private void doAction(IContext<T> context, T domainObject) {
IContextWithPlannerTask<T> contextWithTask = ContextWithPlannerTask
.create(context, mapper.findAssociatedBean(domainObject));
IContextWithPlannerTask<T> contextWithTask =
ContextWithPlannerTask.create(context, mapper.findAssociatedBean(domainObject));
commandOnTask.doAction(contextWithTask, domainObject);
}

View file

@ -119,8 +119,7 @@ public class TaskList extends XulElement implements AfterCompose {
return result;
}
public List<DependencyComponent> asDependencyComponents(
Collection<? extends Dependency> dependencies) {
public List<DependencyComponent> asDependencyComponents(Collection<? extends Dependency> dependencies) {
List<DependencyComponent> result = new ArrayList<DependencyComponent>();
for (Dependency dependency : dependencies) {
result.add(new DependencyComponent(taskComponentByTask
@ -134,8 +133,7 @@ public class TaskList extends XulElement implements AfterCompose {
return asDependencyComponents(Arrays.asList(dependency)).get(0);
}
private synchronized void addTaskComponent(TaskRow beforeThis,
final TaskComponent taskComponent, boolean relocate) {
private synchronized void addTaskComponent(TaskRow beforeThis, final TaskComponent taskComponent, boolean relocate) {
insertBefore(taskComponent.getRow(), beforeThis);
addContextMenu(taskComponent);
addListenerForTaskComponentEditForm(taskComponent);
@ -168,8 +166,7 @@ public class TaskList extends XulElement implements AfterCompose {
return null;
}
private void addListenerForTaskComponentEditForm(
final TaskComponent taskComponent) {
private void addListenerForTaskComponentEditForm(final TaskComponent taskComponent) {
if ( doubleClickCommand == null ) {
return;
}
@ -293,24 +290,22 @@ public class TaskList extends XulElement implements AfterCompose {
private Menupopup getContextMenuFor(TaskComponent taskComponent) {
if ( contextMenus.get(taskComponent) == null ) {
MenuBuilder<TaskComponent> menuBuilder = MenuBuilder.on(getPage(),
getTaskComponents());
MenuBuilder<TaskComponent> menuBuilder = MenuBuilder.on(getPage(), getTaskComponents());
if ( disabilityConfiguration.isAddingDependenciesEnabled() ) {
menuBuilder.item(_("Add Dependency"),
"/common/img/ico_dependency.png",
menuBuilder.item(_("Add Dependency"), "/common/img/ico_dependency.png",
new ItemAction<TaskComponent>() {
@Override
public void onEvent(TaskComponent choosen,
Event event) {
public void onEvent(TaskComponent choosen, Event event) {
choosen.addDependency();
}
});
}
for (CommandOnTaskContextualized<?> command : commandsOnTasksContextualized) {
if ( command.accepts(taskComponent) ) {
menuBuilder.item(command.getName(), command.getIcon(),
command.toItemAction());
menuBuilder.item(command.getName(), command.getIcon(), command.toItemAction());
}
}
Menupopup result = menuBuilder.createWithoutSettingContext();
@ -358,14 +353,13 @@ public class TaskList extends XulElement implements AfterCompose {
getGanttPanel().getDependencyList().redrawDependencies();
}
private void reload(List<Task> tasks, List<Task> tasksPendingToAdd,
boolean relocate) {
private void reload(List<Task> tasks, List<Task> tasksPendingToAdd, boolean relocate) {
for (Task task : tasks) {
if ( visibleTasks.contains(task) ) {
addPendingTasks(tasksPendingToAdd, rowFor(task),
relocate);
addPendingTasks(tasksPendingToAdd, rowFor(task), relocate);
}
final boolean isShown = visibleTasks.contains(task);
if ( predicate.accepts(task) != isShown ) {
if ( isShown ) {
makeDisappear(task);
@ -391,8 +385,7 @@ public class TaskList extends XulElement implements AfterCompose {
return taskComponent == null ? null : taskComponent.getRow();
}
private void addPendingTasks(List<Task> tasksPendingToAdd,
TaskRow insertBefore, boolean relocate) {
private void addPendingTasks(List<Task> tasksPendingToAdd, TaskRow insertBefore, boolean relocate) {
if ( tasksPendingToAdd.isEmpty() ) {
return;
}

View file

@ -29,8 +29,7 @@ package org.libreplan.business;
*/
public class BusinessGlobalNames {
public final static String BUSINESS_SPRING_CONFIG_FILE =
"classpath:/libreplan-business-spring-config.xml";
public final static String BUSINESS_SPRING_CONFIG_FILE = "classpath:/libreplan-business-spring-config.xml";
private BusinessGlobalNames () {}

View file

@ -28,30 +28,22 @@ import org.libreplan.business.common.Registry;
public enum PredefinedAdvancedTypes {
CHILDREN("children", new BigDecimal(100), new BigDecimal(0.01), true,
false),
PERCENTAGE(
"percentage", new BigDecimal(100), new BigDecimal(0.01), true,
false),
UNITS("units", new BigDecimal(Integer.MAX_VALUE),
new BigDecimal(1), false, false),
SUBCONTRACTOR("subcontractor",
new BigDecimal(100), new BigDecimal(0.01), true, false),
TIMESHEETS("timesheets",
new BigDecimal(100), new BigDecimal(0.01), true, false, true);
CHILDREN("children", new BigDecimal(100), new BigDecimal(0.01), true, false),
PERCENTAGE("percentage", new BigDecimal(100), new BigDecimal(0.01), true, false),
UNITS("units", new BigDecimal(Integer.MAX_VALUE), new BigDecimal(1), false, false),
SUBCONTRACTOR("subcontractor", new BigDecimal(100), new BigDecimal(0.01), true, false),
TIMESHEETS("timesheets", new BigDecimal(100), new BigDecimal(0.01), true, false, true);
private PredefinedAdvancedTypes(String name, BigDecimal defaultMaxValue,
BigDecimal precision, boolean percentage, boolean qualityForm) {
private PredefinedAdvancedTypes(String name, BigDecimal defaultMaxValue, BigDecimal precision, boolean percentage,
boolean qualityForm) {
this(name, defaultMaxValue, precision, percentage, qualityForm, false);
}
private PredefinedAdvancedTypes(String name, BigDecimal defaultMaxValue,
BigDecimal precision, boolean percentage, boolean qualityForm,
boolean readOnly) {
private PredefinedAdvancedTypes(String name, BigDecimal defaultMaxValue, BigDecimal precision, boolean percentage,
boolean qualityForm, boolean readOnly) {
this.name = name;
this.defaultMaxValue = defaultMaxValue.setScale(4,
BigDecimal.ROUND_HALF_UP);
this.defaultMaxValue = defaultMaxValue.setScale(4, BigDecimal.ROUND_HALF_UP);
this.unitPrecision = precision.setScale(4, BigDecimal.ROUND_HALF_UP);
this.percentage = percentage;
this.qualityForm = qualityForm;
@ -71,8 +63,10 @@ public enum PredefinedAdvancedTypes {
private final boolean readOnly;
public AdvanceType createType() {
AdvanceType advanceType = AdvanceType.create(name, defaultMaxValue,
false, unitPrecision, true, percentage, qualityForm);
AdvanceType advanceType =
AdvanceType.create(name, defaultMaxValue, false, unitPrecision, true, percentage, qualityForm);
advanceType.setReadOnly(readOnly);
return advanceType;
}

View file

@ -53,8 +53,7 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class BaseCalendarDAO extends IntegrationEntityDAO<BaseCalendar>
implements IBaseCalendarDAO {
public class BaseCalendarDAO extends IntegrationEntityDAO<BaseCalendar> implements IBaseCalendarDAO {
@Override
public List<BaseCalendar> getBaseCalendars() {
@ -65,8 +64,7 @@ public class BaseCalendarDAO extends IntegrationEntityDAO<BaseCalendar>
}
private void removeResourceCalendarInstances(List<BaseCalendar> list) {
for (Iterator<BaseCalendar> iterator = list.iterator(); iterator
.hasNext();) {
for (Iterator<BaseCalendar> iterator = list.iterator(); iterator.hasNext();) {
BaseCalendar baseCalendar = iterator.next();
if ( baseCalendar instanceof ResourceCalendar ) {
iterator.remove();

View file

@ -56,11 +56,9 @@ import org.libreplan.business.workingday.ResourcesPerDay;
* some exceptions of its parent calendar.
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class BaseCalendar extends IntegrationEntity implements ICalendar,
IHumanIdentifiable, Comparable<BaseCalendar> {
public class BaseCalendar extends IntegrationEntity implements ICalendar, IHumanIdentifiable, Comparable<BaseCalendar> {
private static final Capacity DEFAULT_VALUE = Capacity.zero()
.overAssignableWithoutLimit();
private static final Capacity DEFAULT_VALUE = Capacity.zero().overAssignableWithoutLimit();
public static BaseCalendar create() {
return create(new BaseCalendar(CalendarData.create()));

View file

@ -71,8 +71,7 @@ public abstract class BaseEntity implements INewObject {
private static final Log LOG = LogFactory.getLog(BaseEntity.class);
private static final ValidatorFactory validatorFactory = Validation
.buildDefaultValidatorFactory();
private static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
private static final Validator validator = validatorFactory.getValidator();
@ -134,8 +133,7 @@ public abstract class BaseEntity implements INewObject {
@SuppressWarnings("unchecked")
public void validate() throws ValidationException {
Set<ConstraintViolation<BaseEntity>> violations = validator
.validate(this);
Set<ConstraintViolation<BaseEntity>> violations = validator.validate(this);
if ( !violations.isEmpty() ) {
throw new ValidationException(violations);
}
@ -153,8 +151,7 @@ public abstract class BaseEntity implements INewObject {
}
public String getExtraInformation() {
return "[ id: " + getId() + ", newObject: "
+ isNewObject() + "]";
return "[ id: " + getId() + ", newObject: " + isNewObject() + "]";
}
}

View file

@ -38,8 +38,7 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class ConfigurationDAO extends GenericDAOHibernate<Configuration, Long>
implements IConfigurationDAO {
public class ConfigurationDAO extends GenericDAOHibernate<Configuration, Long> implements IConfigurationDAO {
@Override
public Configuration getConfiguration() {
@ -59,10 +58,8 @@ public class ConfigurationDAO extends GenericDAOHibernate<Configuration, Long>
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
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";
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();

View file

@ -58,8 +58,7 @@ import org.springframework.transaction.annotation.Transactional;
* @param <PK>
* Primary key class
*/
public class GenericDAOHibernate<E extends BaseEntity,
PK extends Serializable> implements IGenericDAO<E, PK> {
public class GenericDAOHibernate<E extends BaseEntity, PK extends Serializable> implements IGenericDAO<E, PK> {
private Class<E> entityClass;
@ -68,8 +67,8 @@ public class GenericDAOHibernate<E extends BaseEntity,
@SuppressWarnings("unchecked")
public GenericDAOHibernate() {
this.entityClass = (Class<E>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
this.entityClass =
(Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public GenericDAOHibernate(Class<E> entityClass) {
@ -142,8 +141,8 @@ public class GenericDAOHibernate<E extends BaseEntity,
/* Check version. */
Long versionValueInDB = (Long) getSession().createCriteria(entityClass)
.add(Restrictions.idEq(id)).setProjection(
Projections.property("version")).uniqueResult();
.add(Restrictions.idEq(id))
.setProjection(Projections.property("version")).uniqueResult();
if ( versionValueInDB == null ) {
return;

View file

@ -47,8 +47,7 @@ import org.libreplan.business.resources.entities.Criterion;
import org.libreplan.business.resources.entities.ResourceEnum;
import org.libreplan.business.templates.entities.OrderLineTemplate;
public class HoursGroup extends IntegrationEntity implements Cloneable,
ICriterionRequirable {
public class HoursGroup extends IntegrationEntity implements Cloneable, ICriterionRequirable {
private static final Log LOG = LogFactory.getLog(HoursGroup.class);
@ -197,22 +196,19 @@ public class HoursGroup extends IntegrationEntity implements Cloneable,
* if the new sum of percentages in the parent {@link OrderLine}
* surpasses one
*/
public void setPercentage(BigDecimal proportion)
throws IllegalArgumentException {
public void setPercentage(BigDecimal proportion) throws IllegalArgumentException {
BigDecimal oldPercentage = this.percentage;
this.percentage = proportion;
if ( !isPercentageValidForParent() ) {
this.percentage = oldPercentage;
throw new IllegalArgumentException(
_("Total percentage should be less than 100%"));
throw new IllegalArgumentException(_("Total percentage should be less than 100%"));
}
}
private boolean isPercentageValidForParent() {
return (parentOrderLine != null) ? parentOrderLine.isPercentageValid()
: orderLineTemplate.isPercentageValid();
return (parentOrderLine != null) ? parentOrderLine.isPercentageValid() : orderLineTemplate.isPercentageValid();
}
public BigDecimal getPercentage() {
@ -265,10 +261,8 @@ public class HoursGroup extends IntegrationEntity implements Cloneable,
criterionRequirements.add(requirement);
}
public boolean canAddCriterionRequirement(
CriterionRequirement newRequirement) {
if ((isValidResourceType(newRequirement))
&& (!existSameCriterionRequirement(newRequirement))) {
public boolean canAddCriterionRequirement(CriterionRequirement newRequirement) {
if ( (isValidResourceType(newRequirement)) && (!existSameCriterionRequirement(newRequirement)) ) {
return false;
}
return true;
@ -278,9 +272,7 @@ public class HoursGroup extends IntegrationEntity implements Cloneable,
public void removeCriterionRequirement(CriterionRequirement requirement) {
criterionRequirements.remove(requirement);
if ( requirement instanceof IndirectCriterionRequirement ) {
((IndirectCriterionRequirement) requirement).getParent()
.getChildren().remove(
(IndirectCriterionRequirement) requirement);
((IndirectCriterionRequirement) requirement).getParent().getChildren().remove(requirement);
}
requirement.setCriterion(null);
requirement.setHoursGroup(null);

View file

@ -353,15 +353,13 @@ public class Order extends OrderLineGroup implements Comparable {
@SuppressWarnings("unused")
@AssertTrue(message = "the project must have a start date")
private boolean isIfSchedulingModeIsForwardOrderMustHaveStartDateConstraint() {
return getSchedulingMode() != SchedulingMode.FORWARD
|| getInitDate() != null;
return getSchedulingMode() != SchedulingMode.FORWARD || getInitDate() != null;
}
@SuppressWarnings("unused")
@AssertTrue(message = "the project must have a deadline")
private boolean isIfSchedulingModeIsBackwardsOrderMustHaveDeadlineConstraint() {
return getSchedulingMode() != SchedulingMode.BACKWARDS
|| getDeadline() != null;
return getSchedulingMode() != SchedulingMode.BACKWARDS || getDeadline() != null;
}
@SuppressWarnings("unused")

View file

@ -151,19 +151,15 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
return current;
}
private void schedulingDataNowPointsTo(DeepCopy deepCopy,
OrderVersion version) {
current = getCurrentSchedulingData().pointsTo(deepCopy, version,
schedulingVersionFor(version));
private void schedulingDataNowPointsTo(DeepCopy deepCopy, OrderVersion version) {
current = getCurrentSchedulingData().pointsTo(deepCopy, version, schedulingVersionFor(version));
for (OrderElement each : getChildren()) {
each.schedulingDataNowPointsTo(deepCopy, version);
}
}
protected void addNeededReplaces(DeepCopy deepCopy,
OrderVersion newOrderVersion) {
SchedulingDataForVersion currentVersion = getCurrentSchedulingData()
.getVersion();
protected void addNeededReplaces(DeepCopy deepCopy, OrderVersion newOrderVersion) {
SchedulingDataForVersion currentVersion = getCurrentSchedulingData().getVersion();
SchedulingDataForVersion newSchedulingVersion = schedulingVersionFor(newOrderVersion);
deepCopy.replace(currentVersion, newSchedulingVersion);
for (OrderElement each : getChildren()) {
@ -192,8 +188,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
if ( schedulingState != null ) {
return schedulingState;
}
return schedulingState = SchedulingState.createSchedulingState(
getSchedulingStateType(), getChildrenStates(),
return schedulingState = SchedulingState.createSchedulingState(getSchedulingStateType(), getChildrenStates(),
getCurrentSchedulingData().onTypeChangeListener());
}
@ -227,8 +222,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
useSchedulingDataFor(orderVersion, true);
}
public void useSchedulingDataFor(OrderVersion orderVersion,
boolean recursive) {
public void useSchedulingDataFor(OrderVersion orderVersion, boolean recursive) {
Validate.notNull(orderVersion);
SchedulingDataForVersion schedulingVersion = schedulingVersionFor(orderVersion);
if ( recursive ) {
@ -718,15 +712,12 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
* @throws DuplicateValueTrueReportGlobalAdvanceException
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
public void addAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
public void addAdvanceAssignment(DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
checkNoOtherGlobalAdvanceAssignment(newAdvanceAssignment);
checkAncestorsNoOtherAssignmentWithSameAdvanceType(this,
newAdvanceAssignment);
checkChildrenNoOtherAssignmentWithSameAdvanceType(this,
newAdvanceAssignment);
checkAncestorsNoOtherAssignmentWithSameAdvanceType(this, newAdvanceAssignment);
checkChildrenNoOtherAssignmentWithSameAdvanceType(this, newAdvanceAssignment);
if ( getReportGlobalAdvanceAssignment() == null ) {
newAdvanceAssignment.setReportGlobalAdvance(true);
@ -737,8 +728,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
if ( this.getParent() != null ) {
addChildrenAdvanceInParents(this.getParent());
this.getParent().addIndirectAdvanceAssignment(
newAdvanceAssignment.createIndirectAdvanceFor(this.getParent()));
this.getParent().addIndirectAdvanceAssignment(newAdvanceAssignment.createIndirectAdvanceFor(this.getParent()));
}
}
@ -760,8 +750,9 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
private boolean itsChildsHasAdvances(OrderElement orderElement) {
for (OrderElement child : orderElement.getChildren()) {
if ((!child.getIndirectAdvanceAssignments().isEmpty())
|| (!child.getDirectAdvanceAssignments().isEmpty())) {
if ( (!child.getIndirectAdvanceAssignments().isEmpty()) ||
(!child.getDirectAdvanceAssignments().isEmpty()) ) {
return true;
}
if ( itsChildsHasAdvances(child) ) {
@ -771,9 +762,9 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
return false;
}
protected void checkNoOtherGlobalAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
protected void checkNoOtherGlobalAdvanceAssignment(DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException {
if ( !newAdvanceAssignment.getReportGlobalAdvance() ) {
return;
}
@ -1053,8 +1044,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
return result;
}
private void schedulingDataForVersionFromBottomToTop(
List<SchedulingDataForVersion> result) {
private void schedulingDataForVersionFromBottomToTop(List<SchedulingDataForVersion> result) {
for (OrderElement each : getChildren()) {
each.schedulingDataForVersionFromBottomToTop(result);
}
@ -1495,7 +1485,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
if ( getOrder().equals(this) ) {
return super.isCodeAutogenerated();
}
return getOrder() != null ? getOrder().isCodeAutogenerated() : false;
return (getOrder() != null) ? getOrder().isCodeAutogenerated() : false;
}
@AssertTrue(message = "a quality form cannot be assigned twice to the same task")
@ -1511,11 +1501,9 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
return true;
}
public void removeDirectAdvancesInList(
Set<DirectAdvanceAssignment> directAdvanceAssignments) {
public void removeDirectAdvancesInList(Set<DirectAdvanceAssignment> directAdvanceAssignments) {
for (DirectAdvanceAssignment each : directAdvanceAssignments) {
removeAdvanceAssignment(getAdvanceAssignmentByType(each
.getAdvanceType()));
removeAdvanceAssignment(getAdvanceAssignmentByType(each.getAdvanceType()));
}
for (OrderElement each : getChildren()) {
@ -1529,8 +1517,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
result.addAll(directAdvanceAssignments);
if ( getParent() != null ) {
result.addAll(getParent()
.getDirectAdvanceAssignmentsAndAllInAncest());
result.addAll(getParent().getDirectAdvanceAssignmentsAndAllInAncest());
}
return result;
@ -1541,9 +1528,9 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
// Set PERCENTAGE type as spread if any
String type = PredefinedAdvancedTypes.PERCENTAGE.getTypeName();
for (DirectAdvanceAssignment each : directAdvanceAssignments) {
if (each.getAdvanceType() != null
&& each.getAdvanceType().getType() != null
&& each.getAdvanceType().getType().equals(type)) {
if ( each.getAdvanceType() != null &&
each.getAdvanceType().getType() != null &&
each.getAdvanceType().getType().equals(type) ) {
each.setReportGlobalAdvance(true);
return;
}
@ -1551,8 +1538,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri
// Otherwise, set first advance assignment
if ( !directAdvanceAssignments.isEmpty() ) {
directAdvanceAssignments.iterator().next()
.setReportGlobalAdvance(true);
directAdvanceAssignments.iterator().next().setReportGlobalAdvance(true);
return;
}
}

View file

@ -45,8 +45,7 @@ import org.libreplan.business.templates.entities.OrderLineTemplate;
public class OrderLine extends OrderElement {
private HoursGroupOrderLineHandler hoursGroupOrderLineHandler = HoursGroupOrderLineHandler
.getInstance();
private HoursGroupOrderLineHandler hoursGroupOrderLineHandler = HoursGroupOrderLineHandler.getInstance();
public static OrderLine create() {
OrderLine result = new OrderLine();
@ -59,8 +58,7 @@ public class OrderLine extends OrderElement {
return orderLine;
}
public static OrderLine createUnvalidatedWithUnfixedPercentage(String code,
int hours) {
public static OrderLine createUnvalidatedWithUnfixedPercentage(String code, int hours) {
OrderLine orderLine = createOrderLineWithUnfixedPercentage(hours);
return create(orderLine, code);
}
@ -400,4 +398,8 @@ public class OrderLine extends OrderElement {
return convertedToContainer;
}
@Override
public void setParent(OrderLineGroup parent) {
super.setParent(parent);
}
}

View file

@ -67,15 +67,12 @@ import org.libreplan.business.trees.ITreeParentNode;
*
* @author Manuel Rego Casasnovas <rego@igalia.com>
*/
public class OrderLineGroup extends OrderElement implements
ITreeParentNode<OrderElement> {
public class OrderLineGroup extends OrderElement implements ITreeParentNode<OrderElement> {
private final class ChildrenManipulator extends
TreeNodeOnListWithSchedulingState<OrderElement> {
private final class ChildrenManipulator extends TreeNodeOnListWithSchedulingState<OrderElement> {
private ChildrenManipulator(OrderLineGroup parent,
List<OrderElement> children) {
private ChildrenManipulator(List<OrderElement> children) {
super(children);
}
@ -92,8 +89,7 @@ public class OrderLineGroup extends OrderElement implements
@Override
protected SchedulingState getSchedulingStateFrom(OrderElement node) {
if ( !node.isSchedulingDataInitialized() ) {
node.useSchedulingDataFor(getCurrentSchedulingData()
.getOriginOrderVersion());
node.useSchedulingDataFor(getCurrentSchedulingData().getOriginOrderVersion());
}
return node.getSchedulingState();
}
@ -123,8 +119,7 @@ public class OrderLineGroup extends OrderElement implements
private void removeChildTask(OrderElement removedChild) {
TaskSource taskSource = removedChild.getTaskSource();
TaskElement childTask = taskSource.getTask();
TaskGroup group = (TaskGroup) getThis().getTaskSource()
.getTask();
TaskGroup group = (TaskGroup) getThis().getTaskSource().getTask();
group.remove(childTask);
childTask.detachDependencies();
}
@ -184,8 +179,7 @@ public class OrderLineGroup extends OrderElement implements
public void addChildrenAdvanceOrderLineGroup() {
boolean spread = (getReportGlobalAdvanceAssignment() == null);
IndirectAdvanceAssignment indirectAdvanceAssignment = IndirectAdvanceAssignment
.create(spread);
IndirectAdvanceAssignment indirectAdvanceAssignment = IndirectAdvanceAssignment.create(spread);
AdvanceType advanceType = PredefinedAdvancedTypes.CHILDREN.getType();
indirectAdvanceAssignment.setAdvanceType(advanceType);
indirectAdvanceAssignment.setOrderElement(this);
@ -194,8 +188,7 @@ public class OrderLineGroup extends OrderElement implements
public void removeChildrenAdvanceOrderLineGroup() {
for (IndirectAdvanceAssignment advance : getIndirectAdvanceAssignments()) {
if (advance.getAdvanceType().getUnitName().equals(
PredefinedAdvancedTypes.CHILDREN.getTypeName())) {
if ( advance.getAdvanceType().getUnitName().equals(PredefinedAdvancedTypes.CHILDREN.getTypeName()) ) {
indirectAdvanceAssignments.remove(advance);
updateSpreadAdvance();
}
@ -208,9 +201,9 @@ public class OrderLineGroup extends OrderElement implements
// Set CHILDREN type as spread if any
String type = PredefinedAdvancedTypes.CHILDREN.getTypeName();
for (IndirectAdvanceAssignment each : indirectAdvanceAssignments) {
if (each.getAdvanceType() != null
&& each.getAdvanceType().getType() != null
&& each.getAdvanceType().getType().equals(type)) {
if ( each.getAdvanceType() != null &&
each.getAdvanceType().getType() != null &&
each.getAdvanceType().getType().equals(type) ) {
each.setReportGlobalAdvance(true);
return;
}
@ -218,8 +211,7 @@ public class OrderLineGroup extends OrderElement implements
// Otherwise, set first indirect advance assignment
if ( !indirectAdvanceAssignments.isEmpty() ) {
indirectAdvanceAssignments.iterator().next()
.setReportGlobalAdvance(true);
indirectAdvanceAssignments.iterator().next().setReportGlobalAdvance(true);
return;
}
@ -289,21 +281,17 @@ public class OrderLineGroup extends OrderElement implements
}
private void addIndirectAdvanceAssignments(OrderElement orderElement) {
orderElement
.removeDirectAdvancesInList(getDirectAdvanceAssignmentsAndAllInAncest());
orderElement.removeDirectAdvancesInList(getDirectAdvanceAssignmentsAndAllInAncest());
for (DirectAdvanceAssignment directAdvanceAssignment : orderElement.directAdvanceAssignments) {
IndirectAdvanceAssignment indirectAdvanceAssignment = IndirectAdvanceAssignment
.create();
indirectAdvanceAssignment.setAdvanceType(directAdvanceAssignment
.getAdvanceType());
IndirectAdvanceAssignment indirectAdvanceAssignment = IndirectAdvanceAssignment.create();
indirectAdvanceAssignment.setAdvanceType(directAdvanceAssignment.getAdvanceType());
indirectAdvanceAssignment.setOrderElement(this);
this.addIndirectAdvanceAssignment(indirectAdvanceAssignment);
}
if ( orderElement instanceof OrderLineGroup ) {
for (IndirectAdvanceAssignment indirectAdvanceAssignment : ((OrderLineGroup) orderElement)
.getIndirectAdvanceAssignments()) {
for (IndirectAdvanceAssignment indirectAdvanceAssignment : orderElement.getIndirectAdvanceAssignments()) {
this.addIndirectAdvanceAssignment(indirectAdvanceAssignment);
}
}
@ -315,20 +303,16 @@ public class OrderLineGroup extends OrderElement implements
private void removeIndirectAdvanceAssignments(OrderElement orderElement) {
for (DirectAdvanceAssignment directAdvanceAssignment : orderElement.directAdvanceAssignments) {
this.removeIndirectAdvanceAssignment(directAdvanceAssignment
.getAdvanceType());
this.removeIndirectAdvanceAssignment(directAdvanceAssignment.getAdvanceType());
}
if (orderElement instanceof OrderLineGroup) {
for (IndirectAdvanceAssignment indirectAdvanceAssignment : ((OrderLineGroup) orderElement)
.getIndirectAdvanceAssignments()) {
this.removeIndirectAdvanceAssignment(indirectAdvanceAssignment
.getAdvanceType());
for (IndirectAdvanceAssignment indirectAdvanceAssignment : orderElement.getIndirectAdvanceAssignments()) {
this.removeIndirectAdvanceAssignment(indirectAdvanceAssignment.getAdvanceType());
}
}
if (children.isEmpty() && (indirectAdvanceAssignments.size() == 1)
&& existChildrenAdvance()) {
if ( children.isEmpty() && (indirectAdvanceAssignments.size() == 1) && existChildrenAdvance() ) {
removeChildrenAdvanceOrderLineGroup();
}
}
@ -339,7 +323,7 @@ public class OrderLineGroup extends OrderElement implements
}
private ChildrenManipulator getManipulator() {
return new ChildrenManipulator(this, children);
return new ChildrenManipulator(children);
}
@Override
@ -369,8 +353,8 @@ public class OrderLineGroup extends OrderElement implements
return result;
}
private static Set<DirectAdvanceAssignment> copyDirectAdvanceAssignments(
OrderElement origin, OrderElement destination) {
private static Set<DirectAdvanceAssignment> copyDirectAdvanceAssignments(OrderElement origin,
OrderElement destination) {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
for (DirectAdvanceAssignment each : origin.directAdvanceAssignments) {
result.add(DirectAdvanceAssignment.copy(each, destination));
@ -378,8 +362,7 @@ public class OrderLineGroup extends OrderElement implements
return result;
}
private static Set<MaterialAssignment> copyMaterialAssignments(
OrderElement origin, OrderElement destination) {
private static Set<MaterialAssignment> copyMaterialAssignments(OrderElement origin, OrderElement destination) {
Set<MaterialAssignment> result = new HashSet<MaterialAssignment>();
for (MaterialAssignment each : origin.materialAssignments) {
result.add(MaterialAssignment.copy(each, destination));
@ -387,8 +370,7 @@ public class OrderLineGroup extends OrderElement implements
return result;
}
private static Set<Label> copyLabels(
OrderElement origin, OrderElement destination) {
private static Set<Label> copyLabels(OrderElement origin, OrderElement destination) {
Set<Label> result = new HashSet<Label>();
for (Label each : origin.labels) {
destination.addLabel(each);
@ -397,8 +379,7 @@ public class OrderLineGroup extends OrderElement implements
return result;
}
private static Set<TaskQualityForm> copyTaskQualityForms(
OrderElement origin, OrderElement destination) {
private static Set<TaskQualityForm> copyTaskQualityForms(OrderElement origin, OrderElement destination) {
Set<TaskQualityForm> result = new HashSet<TaskQualityForm>();
for (TaskQualityForm each : origin.taskQualityForms) {
result.add(TaskQualityForm.copy(each, destination));
@ -461,14 +442,18 @@ public class OrderLineGroup extends OrderElement implements
for (IndirectAdvanceAssignment indirectAdvanceAssignment : indirectAdvanceAssignments) {
if ( indirectAdvanceAssignment.getReportGlobalAdvance() ) {
if (indirectAdvanceAssignment.getAdvanceType().getUnitName()
.equals(PredefinedAdvancedTypes.CHILDREN.getTypeName())) {
if ( indirectAdvanceAssignment.getAdvanceType().getUnitName().equals(
PredefinedAdvancedTypes.CHILDREN.getTypeName()) ) {
if ( date == null ) {
return getAdvancePercentageChildren();
}
return getAdvancePercentageChildren(date);
} else {
DirectAdvanceAssignment directAdvanceAssignment = calculateFakeDirectAdvanceAssignment(indirectAdvanceAssignment);
DirectAdvanceAssignment directAdvanceAssignment =
calculateFakeDirectAdvanceAssignment(indirectAdvanceAssignment);
if ( date == null ) {
return directAdvanceAssignment.getAdvancePercentage();
}
@ -498,11 +483,9 @@ public class OrderLineGroup extends OrderElement implements
childPercentage = orderElement.getAdvancePercentage(date);
}
Integer childHours = orderElement.getWorkHours();
result = result.add(childPercentage.multiply(new BigDecimal(
childHours)));
result = result.add(childPercentage.multiply(new BigDecimal(childHours)));
}
result = result.divide(new BigDecimal(hours).setScale(2), 4,
RoundingMode.DOWN);
result = result.divide(new BigDecimal(hours).setScale(2), 4, RoundingMode.DOWN);
}
@ -512,52 +495,47 @@ public class OrderLineGroup extends OrderElement implements
@Override
public DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment(
IndirectAdvanceAssignment indirectAdvanceAssignment) {
if ( indirectAdvanceAssignment.getAdvanceType().getUnitName().equals(
PredefinedAdvancedTypes.CHILDREN.getTypeName()) ) {
return calculateFakeDirectAdvanceAssignmentChildren(indirectAdvanceAssignment);
} else {
Set<DirectAdvanceAssignment> directAdvanceAssignments = getAllDirectAdvanceAssignments(indirectAdvanceAssignment
.getAdvanceType());
return mergeAdvanceAssignments(new ArrayList<DirectAdvanceAssignment>(
directAdvanceAssignments));
Set<DirectAdvanceAssignment> directAdvanceAssignments =
getAllDirectAdvanceAssignments(indirectAdvanceAssignment.getAdvanceType());
return mergeAdvanceAssignments(new ArrayList<DirectAdvanceAssignment>(directAdvanceAssignments));
}
}
private DirectAdvanceAssignment calculateFakeDirectAdvanceAssignmentChildren(
IndirectAdvanceAssignment indirectAdvanceAssignment) {
DirectAdvanceAssignment newDirectAdvanceAssignment = DirectAdvanceAssignment
.create();
DirectAdvanceAssignment newDirectAdvanceAssignment = DirectAdvanceAssignment.create();
newDirectAdvanceAssignment.setFake(true);
newDirectAdvanceAssignment.setMaxValue(new BigDecimal(100));
newDirectAdvanceAssignment.setAdvanceType(indirectAdvanceAssignment
.getAdvanceType());
newDirectAdvanceAssignment.setAdvanceType(indirectAdvanceAssignment.getAdvanceType());
newDirectAdvanceAssignment.setOrderElement(this);
Set<DirectAdvanceAssignment> directAdvanceAssignments = new HashSet<DirectAdvanceAssignment>();
for (OrderElement orderElement : children) {
directAdvanceAssignments.addAll(orderElement
.getAllDirectAdvanceAssignmentsReportGlobal());
directAdvanceAssignments.addAll(orderElement.getAllDirectAdvanceAssignmentsReportGlobal());
}
List<AdvanceMeasurement> advanceMeasurements = new ArrayList<AdvanceMeasurement>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
advanceMeasurements.addAll(directAdvanceAssignment
.getAdvanceMeasurements());
advanceMeasurements.addAll(directAdvanceAssignment.getAdvanceMeasurements());
}
List<LocalDate> measurementDates = getMeasurementDates(advanceMeasurements);
SortedSet<AdvanceMeasurement> newAdvanceMeasurements = new TreeSet<AdvanceMeasurement>(
new AdvanceMeasurementComparator());
SortedSet<AdvanceMeasurement> newAdvanceMeasurements = new TreeSet<AdvanceMeasurement>(new AdvanceMeasurementComparator());
for (LocalDate localDate : measurementDates) {
BigDecimal value = getAdvancePercentageChildren(localDate)
.multiply(new BigDecimal(100));
AdvanceMeasurement advanceMeasurement = AdvanceMeasurement.create(
localDate, value);
BigDecimal value = getAdvancePercentageChildren(localDate).multiply(new BigDecimal(100));
AdvanceMeasurement advanceMeasurement = AdvanceMeasurement.create(localDate, value);
advanceMeasurement.setAdvanceAssignment(newDirectAdvanceAssignment);
newAdvanceMeasurements.add(advanceMeasurement);
}
newDirectAdvanceAssignment
.setAdvanceMeasurements(newAdvanceMeasurements);
newDirectAdvanceAssignment.setAdvanceMeasurements(newAdvanceMeasurements);
return newDirectAdvanceAssignment;
}
@ -847,8 +825,7 @@ public class OrderLineGroup extends OrderElement implements
}
@Override
public Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(
AdvanceType advanceType) {
public Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(AdvanceType advanceType) {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
@ -859,17 +836,14 @@ public class OrderLineGroup extends OrderElement implements
}
for (OrderElement orderElement : children) {
result
.addAll(orderElement
.getAllDirectAdvanceAssignments(advanceType));
result.addAll(orderElement.getAllDirectAdvanceAssignments(advanceType));
}
return result;
}
@Override
public Set<IndirectAdvanceAssignment> getAllIndirectAdvanceAssignments(
AdvanceType advanceType) {
public Set<IndirectAdvanceAssignment> getAllIndirectAdvanceAssignments(AdvanceType advanceType) {
Set<IndirectAdvanceAssignment> result = new HashSet<IndirectAdvanceAssignment>();
IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirectAdvanceAssignment(advanceType);
@ -878,18 +852,15 @@ public class OrderLineGroup extends OrderElement implements
}
for (OrderElement orderElement : children) {
result.addAll(orderElement
.getAllIndirectAdvanceAssignments(advanceType));
result.addAll(orderElement.getAllIndirectAdvanceAssignments(advanceType));
}
return result;
}
public IndirectAdvanceAssignment getIndirectAdvanceAssignment(
AdvanceType advanceType) {
public IndirectAdvanceAssignment getIndirectAdvanceAssignment(AdvanceType advanceType) {
for (IndirectAdvanceAssignment indirectAdvanceAssignment : indirectAdvanceAssignments) {
if (indirectAdvanceAssignment.getAdvanceType().getUnitName()
.equals(advanceType.getUnitName())) {
if ( indirectAdvanceAssignment.getAdvanceType().getUnitName().equals(advanceType.getUnitName()) ) {
return indirectAdvanceAssignment;
}
}
@ -907,8 +878,7 @@ public class OrderLineGroup extends OrderElement implements
}
for (OrderElement orderElement : children) {
result.addAll(orderElement
.getAllDirectAdvanceAssignmentsReportGlobal());
result.addAll(orderElement.getAllDirectAdvanceAssignmentsReportGlobal());
}
return result;
@ -932,34 +902,29 @@ public class OrderLineGroup extends OrderElement implements
return Collections.unmodifiableSet(indirectAdvanceAssignments);
}
public void addIndirectAdvanceAssignment(
IndirectAdvanceAssignment indirectAdvanceAssignment) {
if ((!existsIndirectAdvanceAssignmentWithTheSameType(indirectAdvanceAssignment
.getAdvanceType()))
&& (!existsDirectAdvanceAssignmentWithTheSameType(indirectAdvanceAssignment
.getAdvanceType()))) {
public void addIndirectAdvanceAssignment(IndirectAdvanceAssignment indirectAdvanceAssignment) {
if ( (!existsIndirectAdvanceAssignmentWithTheSameType(indirectAdvanceAssignment.getAdvanceType())) &&
(!existsDirectAdvanceAssignmentWithTheSameType(indirectAdvanceAssignment.getAdvanceType())) ) {
indirectAdvanceAssignments.add(indirectAdvanceAssignment);
}
if ( parent != null ) {
parent.addIndirectAdvanceAssignment(indirectAdvanceAssignment
.createIndirectAdvanceFor(parent));
parent.addIndirectAdvanceAssignment(indirectAdvanceAssignment.createIndirectAdvanceFor(parent));
}
}
public void removeIndirectAdvanceAssignment(AdvanceType advanceType) {
DirectAdvanceAssignment tempAdavanceAssignmet = DirectAdvanceAssignment
.create();
DirectAdvanceAssignment tempAdavanceAssignmet = DirectAdvanceAssignment.create();
tempAdavanceAssignmet.setAdvanceType(advanceType);
try {
checkChildrenNoOtherAssignmentWithSameAdvanceType(this,
tempAdavanceAssignmet);
checkChildrenNoOtherAssignmentWithSameAdvanceType(this, tempAdavanceAssignmet);
String unitName = advanceType.getUnitName();
IndirectAdvanceAssignment toRemove = null;
for (IndirectAdvanceAssignment indirectAdvanceAssignment : indirectAdvanceAssignments) {
if (unitName.equals(indirectAdvanceAssignment.getAdvanceType()
.getUnitName())) {
if ( unitName.equals(indirectAdvanceAssignment.getAdvanceType().getUnitName()) ) {
toRemove = indirectAdvanceAssignment;
}
}
@ -978,12 +943,10 @@ public class OrderLineGroup extends OrderElement implements
}
}
public boolean existsIndirectAdvanceAssignmentWithTheSameType(
AdvanceType type) {
public boolean existsIndirectAdvanceAssignmentWithTheSameType(AdvanceType type) {
String unitName = type.getUnitName();
for (IndirectAdvanceAssignment indirectAdvanceAssignment : indirectAdvanceAssignments) {
if (unitName.equals(indirectAdvanceAssignment.getAdvanceType()
.getUnitName())) {
if ( unitName.equals(indirectAdvanceAssignment.getAdvanceType().getUnitName()) ) {
return true;
}
}
@ -991,9 +954,9 @@ public class OrderLineGroup extends OrderElement implements
}
@Override
protected void checkNoOtherGlobalAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
protected void checkNoOtherGlobalAdvanceAssignment(DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException {
if ( !newAdvanceAssignment.getReportGlobalAdvance() ) {
return;
}

View file

@ -39,10 +39,8 @@ public class SchedulingDataForVersion extends BaseEntity {
public static class Data {
private static Data from(SchedulingDataForVersion version,
OrderVersion orderVersion) {
return new Data(orderVersion, version, version
.getTaskSource(), version.getSchedulingStateType());
private static Data from(SchedulingDataForVersion version, OrderVersion orderVersion) {
return new Data(orderVersion, version, version.getTaskSource(), version.getSchedulingStateType());
}
private SchedulingDataForVersion originVersion;
@ -61,6 +59,7 @@ public class SchedulingDataForVersion extends BaseEntity {
SchedulingDataForVersion version,
TaskSource taskSource,
Type schedulingStateType) {
Validate.notNull(schedulingStateType);
this.originOrderVersion = orderVersion;
this.originVersion = version;
@ -77,8 +76,7 @@ public class SchedulingDataForVersion extends BaseEntity {
return schedulingStateType;
}
private void setSchedulingStateType(
SchedulingState.Type schedulingStateType) {
private void setSchedulingStateType(SchedulingState.Type schedulingStateType) {
this.schedulingStateType = schedulingStateType;
hasPendingChanges = true;
}
@ -109,14 +107,12 @@ public class SchedulingDataForVersion extends BaseEntity {
}
public void requestedCreationOf(TaskSource taskSource) {
Validate.isTrue(this.getTaskSource() == null,
"there must be no task source");
Validate.isTrue(this.getTaskSource() == null, "there must be no task source");
this.setTaskSource(taskSource);
}
public void replaceCurrentTaskSourceWith(TaskSource newTaskSource) {
Validate.isTrue(this.getTaskSource() != null,
"there must be a task source to replace");
Validate.isTrue(this.getTaskSource() != null, "there must be a task source to replace");
this.setTaskSource(newTaskSource);
}
@ -162,8 +158,7 @@ public class SchedulingDataForVersion extends BaseEntity {
}
private static Type defaultTypeFor(OrderElement orderElement) {
return orderElement.isLeaf() ? Type.SCHEDULING_POINT
: Type.NO_SCHEDULED;
return orderElement.isLeaf() ? Type.SCHEDULING_POINT : Type.NO_SCHEDULED;
}
@NotNull
@ -193,6 +188,7 @@ public class SchedulingDataForVersion extends BaseEntity {
void removeSpuriousDayAssignments(Scenario scenario) {
TaskSource taskSource = getTaskSource();
if ( taskSource != null ) {
TaskElement task = taskSource.getTask();
task.removeDayAssignmentsFor(scenario);

View file

@ -68,8 +68,7 @@ public class AssignedEffortForResource {
* @return A {@link IAssignedEffortForResource} that calculates the load
* associated for all allocations but the provided ones.
*/
public static IAssignedEffortForResource effortDiscounting(
Collection<? extends BaseEntity> allocations) {
public static IAssignedEffortForResource effortDiscounting(Collection<? extends BaseEntity> allocations) {
return new AssignedEffortDiscounting(allocations);
}

View file

@ -51,10 +51,11 @@ public class CompanyEarnedValueCalculator extends EarnedValueCalculator implemen
@Override
@Transactional(readOnly = true)
public SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkScheduled(AvailabilityTimeLine.Interval interval) {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> estimatedCostPerTask = databaseSnapshots
.snapshotEstimatedCostPerTask();
Collection<TaskElement> list = filterTasksByDate(
estimatedCostPerTask.keySet(), interval);
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> estimatedCostPerTask =
databaseSnapshots.snapshotEstimatedCostPerTask();
Collection<TaskElement> list = filterTasksByDate(estimatedCostPerTask.keySet(), interval);
SortedMap<LocalDate, BigDecimal> estimatedCost = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement each : list) {
@ -63,21 +64,17 @@ public class CompanyEarnedValueCalculator extends EarnedValueCalculator implemen
return accumulateResult(estimatedCost);
}
private List<TaskElement> filterTasksByDate(
Collection<TaskElement> tasks,
AvailabilityTimeLine.Interval interval) {
private List<TaskElement> filterTasksByDate(Collection<TaskElement> tasks, AvailabilityTimeLine.Interval interval) {
List<TaskElement> result = new ArrayList<TaskElement>();
for(TaskElement task : tasks) {
if (interval.includes(task.getStartAsLocalDate())
|| interval.includes(task.getEndAsLocalDate())) {
if ( interval.includes(task.getStartAsLocalDate()) || interval.includes(task.getEndAsLocalDate()) ) {
result.add(task);
}
}
return result;
}
private List<WorkReportLine> filterWorkReportLinesByDate(
Collection<WorkReportLine> lines,
private List<WorkReportLine> filterWorkReportLinesByDate(Collection<WorkReportLine> lines,
AvailabilityTimeLine.Interval interval) {
List<WorkReportLine> result = new ArrayList<WorkReportLine>();
for(WorkReportLine line: lines) {
@ -90,12 +87,12 @@ public class CompanyEarnedValueCalculator extends EarnedValueCalculator implemen
private void addCost(SortedMap<LocalDate, BigDecimal> currentCost,
SortedMap<LocalDate, BigDecimal> additionalCost) {
for (LocalDate day : additionalCost.keySet()) {
if ( !currentCost.containsKey(day) ) {
currentCost.put(day, BigDecimal.ZERO);
}
currentCost.put(day, currentCost.get(day).add(
additionalCost.get(day)));
currentCost.put(day, currentCost.get(day).add(additionalCost.get(day)));
}
}

View file

@ -73,6 +73,7 @@ public class GenericResourceAllocation extends
public static Map<Set<Criterion>, List<GenericResourceAllocation>> byCriterions(
Collection<GenericResourceAllocation> genericAllocations) {
Map<Set<Criterion>, List<GenericResourceAllocation>> result = new HashMap<Set<Criterion>, List<GenericResourceAllocation>>();
for (GenericResourceAllocation genericResourceAllocation : genericAllocations) {
Set<Criterion> criterions = genericResourceAllocation.getCriterions();
@ -128,8 +129,8 @@ public class GenericResourceAllocation extends
return first.getType().getResource();
}
public static GenericResourceAllocation create(Task task,
ResourceEnum resourceType, Collection<? extends Criterion> criterions) {
public static GenericResourceAllocation create(Task task, ResourceEnum resourceType,
Collection<? extends Criterion> criterions) {
Validate.notNull(resourceType);
GenericResourceAllocation result = new GenericResourceAllocation(task);
result.criterions = new HashSet<Criterion>(criterions);
@ -208,8 +209,7 @@ public class GenericResourceAllocation extends
public GenericAllocation(List<Resource> resources) {
this.resources = resources;
hoursDistributor = new EffortDistributor(resources,
getAssignedEffortForResource(),
hoursDistributor = new EffortDistributor(resources, getAssignedEffortForResource(),
new ResourcesSatisfyingCriterionsSelector());
}
@ -227,8 +227,7 @@ public class GenericResourceAllocation extends
@Override
protected AvailabilityTimeLine getResourcesAvailability() {
return AvailabilityCalculator.buildSumOfAvailabilitiesFor(
getCriterions(), resources);
return AvailabilityCalculator.buildSumOfAvailabilitiesFor(getCriterions(), resources);
}
@Override

View file

@ -24,10 +24,14 @@ package org.libreplan.business.planner.entities;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.List;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.SortedMap;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.Date;
import org.joda.time.LocalDate;
import org.libreplan.business.advance.entities.AdvanceMeasurement;
@ -44,6 +48,7 @@ import org.springframework.stereotype.Component;
* Cost calulator in terms of hours.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
*/
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
@ -58,16 +63,17 @@ public class HoursCostCalculator implements ICostCalculator {
}
@Override
public SortedMap<LocalDate, BigDecimal> getAdvanceCost(Task task,
LocalDate filterStartDate, LocalDate filterEndDate) {
DirectAdvanceAssignment advanceAssignment = (task.getOrderElement() != null) ? task
.getOrderElement().getReportGlobalAdvanceAssignment() : null;
public SortedMap<LocalDate, BigDecimal> getAdvanceCost(Task task, LocalDate filterStartDate,
LocalDate filterEndDate) {
DirectAdvanceAssignment advanceAssignment =
(task.getOrderElement() != null) ? task.getOrderElement().getReportGlobalAdvanceAssignment() : null;
if ( advanceAssignment == null ) {
return new TreeMap<LocalDate, BigDecimal>();
}
return calculateHoursPerDay(task.getHoursSpecifiedAtOrder(),
return calculateHoursPerDay(
task.getHoursSpecifiedAtOrder(),
advanceAssignment.getAdvanceMeasurements(),
filterStartDate, filterEndDate);
}
@ -76,16 +82,17 @@ public class HoursCostCalculator implements ICostCalculator {
Integer totalHours,
SortedSet<AdvanceMeasurement> advanceMeasurements,
LocalDate filterStartDate, LocalDate filterEndDate) {
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
for (AdvanceMeasurement advanceMeasurement : advanceMeasurements) {
LocalDate day = advanceMeasurement.getDate();
if( ((filterStartDate == null) || day.compareTo(filterStartDate) >= 0) &&
((filterEndDate == null) || day.compareTo(filterEndDate) <= 0) ) {
BigDecimal cost = advanceMeasurement.getValue().setScale(2)
.multiply(new BigDecimal(totalHours))
.divide(new BigDecimal(100),
new MathContext(2, RoundingMode.HALF_UP));
.divide(new BigDecimal(100), new MathContext(2, RoundingMode.HALF_UP));
result.put(day, cost);
}
}
@ -98,35 +105,99 @@ public class HoursCostCalculator implements ICostCalculator {
return getEstimatedCost(task, null, null);
}
/**
* BCWS values are calculating here.
* MAX(BCWS) equals addition of all dayAssignments.
*/
@Override
public SortedMap<LocalDate, BigDecimal> getEstimatedCost(Task task,
LocalDate filterStartDate, LocalDate filterEndDate) {
public SortedMap<LocalDate, BigDecimal> getEstimatedCost(
Task task,
LocalDate filterStartDate,
LocalDate filterEndDate) {
if ( task.isSubcontracted() ) {
return getAdvanceCost(task);
}
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
List<DayAssignment> dayAssignments = task
.getDayAssignments(FilterType.WITHOUT_DERIVED);
List<DayAssignment> dayAssignments = task.getDayAssignments(FilterType.WITHOUT_DERIVED);
if ( dayAssignments.isEmpty() ) {
return result;
}
int additionOfAllAssignmentsMinutes = 0;
for (DayAssignment dayAssignment : dayAssignments) {
LocalDate day = dayAssignment.getDay();
if( ( (filterStartDate == null) || day.compareTo(filterStartDate) >= 0) &&
( (filterEndDate == null) || day.compareTo(filterEndDate) <= 0) ) {
BigDecimal cost = new BigDecimal(dayAssignment.getHours());
String currentTime = dayAssignment.getDuration().toFormattedString();
SimpleDateFormat format1 = new SimpleDateFormat("hh:mm");
SimpleDateFormat format2 = new SimpleDateFormat("hh");
Date date = null;
try {
if ( isParsableWithFormat1(currentTime) )
date = format1.parse(currentTime);
else if ( isParsableWithFormat2(currentTime) )
date = format2.parse(currentTime);
} catch (ParseException e) {
e.printStackTrace();
}
Time time = new Time(date.getTime());
BigDecimal hours = new BigDecimal(time.getHours());
additionOfAllAssignmentsMinutes += time.getMinutes();
if ( !result.containsKey(day) ) {
result.put(day, BigDecimal.ZERO);
}
result.put(day, result.get(day).add(cost));
/**
* On last day assignment app will check addition of minutes of all assignments.
* If it is between 30 and 60 - add 1 hour to the last value of result.
* If it is more than 60 then divide on 60 and calculate hours.
* E.G. 120 minutes / 60 = 2 hours.
*/
if ( dayAssignment.equals(dayAssignments.get(dayAssignments.size() - 1)) ){
if ( additionOfAllAssignmentsMinutes >= 30 && additionOfAllAssignmentsMinutes <= 60 )
hours = BigDecimal.valueOf(hours.intValue() + 1);
if ( additionOfAllAssignmentsMinutes > 60 )
hours = BigDecimal.valueOf(hours.intValue() + (additionOfAllAssignmentsMinutes / 60));
}
result.put(day, result.get(day).add(hours));
}
}
return result;
}
return result;
private boolean isParsableWithFormat1(String input){
boolean parsable = true;
try {
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
format.parse(input);
} catch (ParseException e) {
parsable = false;
}
return parsable;
}
private boolean isParsableWithFormat2(String input){
boolean parsable = true;
try {
SimpleDateFormat format = new SimpleDateFormat("hh");
format.parse(input);
} catch (ParseException e) {
parsable = false;
}
return parsable;
}
@Override

View file

@ -32,13 +32,10 @@ import org.libreplan.business.calendars.entities.AvailabilityTimeLine;
*/
public interface ICompanyEarnedValueCalculator extends IEarnedValueCalculator {
SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkScheduled(
AvailabilityTimeLine.Interval interval);
SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkScheduled(AvailabilityTimeLine.Interval interval);
SortedMap<LocalDate, BigDecimal> calculateActualCostWorkPerformed(
AvailabilityTimeLine.Interval interval);
SortedMap<LocalDate, BigDecimal> calculateActualCostWorkPerformed(AvailabilityTimeLine.Interval interval);
SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkPerformed(
AvailabilityTimeLine.Interval interval);
SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkPerformed(AvailabilityTimeLine.Interval interval);
}

View file

@ -52,8 +52,7 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
@Transactional(readOnly = true)
@Override
public SortedMap<LocalDate, BigDecimal> calculateActualCostWorkPerformed(
Order order) {
public SortedMap<LocalDate, BigDecimal> calculateActualCostWorkPerformed(Order order) {
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement taskElement : getAllTaskElements(order)) {
if ( taskElement instanceof Task ) {
@ -63,8 +62,7 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
return accumulateResult(result);
}
private SortedMap<LocalDate, BigDecimal> accumulateResult(
SortedMap<LocalDate, BigDecimal> map) {
private SortedMap<LocalDate, BigDecimal> accumulateResult(SortedMap<LocalDate, BigDecimal> map) {
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
if ( map.isEmpty() ) {
return result;
@ -81,12 +79,12 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
private void addCost(SortedMap<LocalDate, BigDecimal> currentCost,
SortedMap<LocalDate, BigDecimal> additionalCost) {
for (LocalDate day : additionalCost.keySet()) {
if ( !currentCost.containsKey(day) ) {
currentCost.put(day, BigDecimal.ZERO);
}
currentCost.put(day,
currentCost.get(day).add(additionalCost.get(day)));
currentCost.put(day, currentCost.get(day).add(additionalCost.get(day)));
}
}
@ -104,14 +102,12 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
@Transactional(readOnly = true)
public BigDecimal getBudgetAtCompletion(Order order) {
SortedMap<LocalDate, BigDecimal> budgedtedCost = calculateBudgetedCostWorkScheduled(order);
return !budgedtedCost.isEmpty() ? budgedtedCost.get(budgedtedCost
.lastKey()) : BigDecimal.ZERO;
return !budgedtedCost.isEmpty() ? budgedtedCost.get(budgedtedCost.lastKey()) : BigDecimal.ZERO;
}
@Override
@Transactional(readOnly = true)
public SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkScheduled(
Order order) {
public SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkScheduled(Order order) {
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement taskElement : getAllTaskElements(order)) {
if ( taskElement instanceof Task ) {
@ -132,8 +128,7 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
return getValueAt(budgetedCost, date);
}
private BigDecimal getValueAt(SortedMap<LocalDate, BigDecimal> map,
LocalDate date) {
private BigDecimal getValueAt(SortedMap<LocalDate, BigDecimal> map, LocalDate date) {
if ( map.isEmpty() ) {
return BigDecimal.ZERO;
}
@ -154,8 +149,7 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
@Override
@Transactional(readOnly = true)
public SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkPerformed(
Order order) {
public SortedMap<LocalDate, BigDecimal> calculateBudgetedCostWorkPerformed(Order order) {
SortedMap<LocalDate, BigDecimal> estimatedCost = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement taskElement : getAllTaskElements(order)) {
if ( taskElement instanceof Task ) {
@ -170,8 +164,7 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
}
@Override
public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost,
BigDecimal actualCost) {
public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost, BigDecimal actualCost) {
if ( BigDecimal.ZERO.compareTo(actualCost) == 0 ) {
return BigDecimal.ZERO;
}
@ -182,14 +175,12 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
}
@Override
public BigDecimal getCostVariance(BigDecimal budgetedCost,
BigDecimal actualCost) {
public BigDecimal getCostVariance(BigDecimal budgetedCost, BigDecimal actualCost) {
return budgetedCost.subtract(actualCost);
}
@Override
public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion,
BigDecimal costPerformanceIndex) {
public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion, BigDecimal costPerformanceIndex) {
if ( BigDecimal.ZERO.compareTo(costPerformanceIndex) == 0 ) {
return BigDecimal.ZERO;
}
@ -199,8 +190,7 @@ public class OrderEarnedValueCalculator extends EarnedValueCalculator implements
}
@Override
public BigDecimal getEstimateToComplete(BigDecimal estimateAtCompletion,
BigDecimal actualCostWorkPerformed) {
public BigDecimal getEstimateToComplete(BigDecimal estimateAtCompletion, BigDecimal actualCostWorkPerformed) {
return estimateAtCompletion.subtract(actualCostWorkPerformed);
}

View file

@ -89,11 +89,11 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
private static final Log LOG = LogFactory.getLog(ResourceAllocation.class);
public static <T extends ResourceAllocation<?>> List<T> getSatisfied(
Collection<T> resourceAllocations) {
public static <T extends ResourceAllocation<?>> List<T> getSatisfied(Collection<T> resourceAllocations) {
Validate.notNull(resourceAllocations);
Validate.noNullElements(resourceAllocations);
List<T> result = new ArrayList<T>();
for (T each : resourceAllocations) {
if ( each.isSatisfied() ) {
result.add(each);
@ -116,10 +116,11 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
public static <R extends ResourceAllocation<?>> Map<Resource, List<R>> byResource(
Collection<? extends R> allocations) {
Map<Resource, List<R>> result = new HashMap<Resource, List<R>>();
for (R resourceAllocation : allocations) {
for (Resource resource : resourceAllocation
.getAssociatedResources()) {
for (Resource resource : resourceAllocation.getAssociatedResources()) {
if ( !result.containsKey(resource) ) {
result.put(resource, new ArrayList<R>());
}
@ -129,15 +130,13 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
return result;
}
public static <R extends ResourceAllocation<?>> List<R> sortedByStartDate(
Collection<? extends R> allocations) {
public static <R extends ResourceAllocation<?>> List<R> sortedByStartDate(Collection<? extends R> allocations) {
List<R> result = new ArrayList<R>(allocations);
Collections.sort(result, byStartDateComparator());
return result;
}
public static <R extends ResourceAllocation<?>> Map<Task, List<R>> byTask(
List<? extends R> allocations) {
public static <R extends ResourceAllocation<?>> Map<Task, List<R>> byTask(List<? extends R> allocations) {
Map<Task, List<R>> result = new LinkedHashMap<Task, List<R>>();
for (R resourceAllocation : allocations) {
if ( resourceAllocation.getTask() != null ) {
@ -149,8 +148,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
return result;
}
private static <E extends ResourceAllocation<?>> void initializeIfNeeded(
Map<Task, List<E>> result, Task task) {
private static <E extends ResourceAllocation<?>> void initializeIfNeeded(Map<Task, List<E>> result, Task task) {
if ( !result.containsKey(task) ) {
result.put(task, new ArrayList<E>());
}
@ -160,16 +158,14 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
return new Comparator<ResourceAllocation<?>>() {
@Override
public int compare(ResourceAllocation<?> o1,
ResourceAllocation<?> o2) {
public int compare(ResourceAllocation<?> o1, ResourceAllocation<?> o2) {
if ( o1.getIntraDayStartDate() == null ) {
return -1;
}
if ( o2.getIntraDayStartDate() == null ) {
return 1;
}
return o1.getIntraDayStartDate().compareTo(
o2.getIntraDayStartDate());
return o1.getIntraDayStartDate().compareTo(o2.getIntraDayStartDate());
}
};
}
@ -178,15 +174,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
FORWARD {
@Override
public IntraDayDate getDateFromWhichToAllocate(Task task) {
return IntraDayDate.max(task.getFirstDayNotConsolidated(),
task.getIntraDayStartDate());
return IntraDayDate.max(task.getFirstDayNotConsolidated(), task.getIntraDayStartDate());
}
@Override
void limitAvailabilityOn(AvailabilityTimeLine availability,
IntraDayDate dateFromWhichToAllocate) {
availability.invalidUntil(dateFromWhichToAllocate
.asExclusiveEnd());
void limitAvailabilityOn(AvailabilityTimeLine availability, IntraDayDate dateFromWhichToAllocate) {
availability.invalidUntil(dateFromWhichToAllocate.asExclusiveEnd());
}
},
BACKWARD {
@ -196,23 +189,19 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
@Override
void limitAvailabilityOn(AvailabilityTimeLine availability,
IntraDayDate dateFromWhichToAllocate) {
void limitAvailabilityOn(AvailabilityTimeLine availability, IntraDayDate dateFromWhichToAllocate) {
availability.invalidFrom(dateFromWhichToAllocate.getDate());
}
};
public abstract IntraDayDate getDateFromWhichToAllocate(Task task);
abstract void limitAvailabilityOn(AvailabilityTimeLine availability,
IntraDayDate dateFromWhichToAllocate);
abstract void limitAvailabilityOn(AvailabilityTimeLine availability, IntraDayDate dateFromWhichToAllocate);
}
public static AllocationsSpecified allocating(
List<ResourcesPerDayModification> resourceAllocations) {
resourceAllocations = new ArrayList<ResourcesPerDayModification>(
resourceAllocations);
public static AllocationsSpecified allocating(List<ResourcesPerDayModification> resourceAllocations) {
resourceAllocations = new ArrayList<ResourcesPerDayModification>(resourceAllocations);
sortBySpecificFirst(resourceAllocations);
return new AllocationsSpecified(resourceAllocations);
}
@ -225,14 +214,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
* @param resourceAllocations
* Sorted with specific allocations before generic ones
*/
private static <T extends AllocationModification> void sortBySpecificFirst(
List<T> resourceAllocations) {
private static <T extends AllocationModification> void sortBySpecificFirst(List<T> resourceAllocations) {
Collections.sort(resourceAllocations,
new Comparator<AllocationModification>() {
@Override
public int compare(AllocationModification o1,
AllocationModification o2) {
public int compare(AllocationModification o1, AllocationModification o2) {
if ( o1.isSpecific() && o2.isSpecific() ) {
return 0;
}
@ -247,16 +234,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
});
}
private static void checkStartLessOrEqualToEnd(IntraDayDate startInclusive,
IntraDayDate endExclusive) {
Validate.isTrue(startInclusive.compareTo(endExclusive) <= 0,
"the end must be equal or posterior to the start");
private static void checkStartLessOrEqualToEnd(IntraDayDate startInclusive, IntraDayDate endExclusive) {
Validate.isTrue(startInclusive.compareTo(endExclusive) <= 0, "the end must be equal or posterior to the start");
}
private static void checkStartLessOrEqualToEnd(LocalDate start,
LocalDate end) {
Validate.isTrue(start.compareTo(end) <= 0,
"the end must be equal or posterior to the start");
private static void checkStartLessOrEqualToEnd(LocalDate start, LocalDate end) {
Validate.isTrue(start.compareTo(end) <= 0, "the end must be equal or posterior to the start");
}
/**
@ -333,9 +316,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
public interface INotFulfilledReceiver {
public void cantFulfill(
ResourcesPerDayModification allocationAttempt,
CapacityResult capacityResult);
public void cantFulfill(ResourcesPerDayModification allocationAttempt, CapacityResult capacityResult);
}
public IntraDayDate untilAllocating(EffortDuration effort) {
@ -350,39 +331,35 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
private static INotFulfilledReceiver doNothing() {
return new INotFulfilledReceiver() {
@Override
public void cantFulfill(
ResourcesPerDayModification allocationAttempt,
CapacityResult capacityResult) {
public void cantFulfill(ResourcesPerDayModification allocationAttempt, CapacityResult capacityResult) {
}
};
}
public IntraDayDate untilAllocating(EffortDuration effort,
final INotFulfilledReceiver receiver) {
public IntraDayDate untilAllocating(EffortDuration effort, final INotFulfilledReceiver receiver) {
return untilAllocating(Direction.FORWARD, effort, receiver);
}
public IntraDayDate untilAllocating(Direction direction,
EffortDuration toAllocate, final INotFulfilledReceiver receiver) {
UntilFillingHoursAllocator allocator = new UntilFillingHoursAllocator(
direction,
task, allocations) {
public IntraDayDate untilAllocating(
Direction direction,
EffortDuration toAllocate,
final INotFulfilledReceiver receiver) {
UntilFillingHoursAllocator allocator = new UntilFillingHoursAllocator(direction, task, allocations) {
@Override
protected <T extends DayAssignment> void setNewDataForAllocation(
ResourceAllocation<T> allocation,
IntraDayDate resultDate,
ResourcesPerDay resourcesPerDay, List<T> dayAssignments) {
ResourcesPerDay resourcesPerDay,
List<T> dayAssignments) {
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();
}
@ -392,23 +369,21 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
IntraDayDate dateFromWhichToAllocate,
ResourcesPerDayModification resourcesPerDayModification,
EffortDuration effortToAllocate) {
ICalendar calendar = getCalendar(resourcesPerDayModification);
ResourcesPerDay resourcesPerDay = resourcesPerDayModification
.getGoal();
AvailabilityTimeLine availability = resourcesPerDayModification
.getAvailability();
getDirection().limitAvailabilityOn(availability,
dateFromWhichToAllocate);
return ThereAreHoursOnWorkHoursCalculator
.thereIsAvailableCapacityFor(calendar,
availability, resourcesPerDay,
ResourcesPerDay resourcesPerDay = resourcesPerDayModification.getGoal();
AvailabilityTimeLine availability = resourcesPerDayModification.getAvailability();
getDirection().limitAvailabilityOn(availability, dateFromWhichToAllocate);
return ThereAreHoursOnWorkHoursCalculator.thereIsAvailableCapacityFor(
calendar,
availability,
resourcesPerDay,
effortToAllocate);
}
private CombinedWorkHours getCalendar(
ResourcesPerDayModification resourcesPerDayModification) {
return CombinedWorkHours.minOf(resourcesPerDayModification
.getBeingModified().getTaskCalendar(),
private CombinedWorkHours getCalendar(ResourcesPerDayModification resourcesPerDayModification) {
return CombinedWorkHours.minOf(
resourcesPerDayModification.getBeingModified().getTaskCalendar(),
resourcesPerDayModification.getResourcesCalendar());
}
@ -626,9 +601,8 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
public boolean areIntendedResourcesPerDaySatisfied() {
CalculatedValue calculatedValue = getTask().getCalculatedValue();
return calculatedValue == CalculatedValue.RESOURCES_PER_DAY
|| ObjectUtils.equals(getNonConsolidatedResourcePerDay(),
getIntendedResourcesPerDay());
return calculatedValue == CalculatedValue.RESOURCES_PER_DAY ||
ObjectUtils.equals(getNonConsolidatedResourcePerDay(), getIntendedResourcesPerDay());
}
public ResourceAllocation(Task task) {
@ -704,16 +678,14 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
return visit(this, new IVisitor<ResourcesPerDayModification>() {
@Override
public ResourcesPerDayModification on(
SpecificResourceAllocation specificAllocation) {
return ResourcesPerDayModification.create(specificAllocation,
getReassignationResourcesPerDay());
public ResourcesPerDayModification on(SpecificResourceAllocation specificAllocation) {
return ResourcesPerDayModification.create(specificAllocation, getReassignationResourcesPerDay());
}
@Override
public ResourcesPerDayModification on(
GenericResourceAllocation genericAllocation) {
return ResourcesPerDayModification.create(genericAllocation,
public ResourcesPerDayModification on(GenericResourceAllocation genericAllocation) {
return ResourcesPerDayModification.create(
genericAllocation,
getReassignationResourcesPerDay(),
getAssociatedResources());
}
@ -725,15 +697,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
@Override
public EffortModification on(GenericResourceAllocation genericAllocation) {
return EffortModification.create(genericAllocation,
getEffortForReassignation(),
getAssociatedResources());
return EffortModification.create(genericAllocation, getEffortForReassignation(), getAssociatedResources());
}
@Override
public EffortModification on(SpecificResourceAllocation specificAllocation) {
return EffortModification.create(specificAllocation,
getEffortForReassignation());
return EffortModification.create(specificAllocation, getEffortForReassignation());
}
});
}
@ -749,26 +718,28 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
List<T> distributeForDay(PartialDay day, EffortDuration effort);
}
protected abstract class AssignmentsAllocator implements IAllocatable,
IEffortDistributor<T> {
protected abstract class AssignmentsAllocator implements IAllocatable, IEffortDistributor<T> {
@Override
public final void allocate(ResourcesPerDay resourcesPerDay) {
Task currentTask = getTask();
AllocateResourcesPerDayOnInterval allocator = new AllocateResourcesPerDayOnInterval(
currentTask.getIntraDayStartDate(),
currentTask.getIntraDayEndDate());
allocator.allocate(resourcesPerDay);
}
private List<T> createAssignments(ResourcesPerDay resourcesPerDay,
IntraDayDate startInclusive, IntraDayDate endExclusive) {
private List<T> createAssignments(
ResourcesPerDay resourcesPerDay,
IntraDayDate startInclusive,
IntraDayDate endExclusive) {
List<T> assignmentsCreated = new ArrayList<T>();
for (PartialDay day : getDays(startInclusive, endExclusive)) {
EffortDuration durationForDay = calculateTotalToDistribute(day,
resourcesPerDay);
assignmentsCreated
.addAll(distributeForDay(day, durationForDay));
EffortDuration durationForDay = calculateTotalToDistribute(day, resourcesPerDay);
assignmentsCreated.addAll(distributeForDay(day, durationForDay));
}
return onlyNonZeroHours(assignmentsCreated);
}
@ -780,89 +751,67 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
@Override
public IAllocateResourcesPerDay resourcesPerDayFromEndUntil(
IntraDayDate start) {
IntraDayDate startInclusive = IntraDayDate.max(start,
getStartSpecifiedByTask());
public IAllocateResourcesPerDay resourcesPerDayFromEndUntil(IntraDayDate start) {
IntraDayDate startInclusive = IntraDayDate.max(start, getStartSpecifiedByTask());
IntraDayDate endDate = task.getIntraDayEndDate();
return new AllocateResourcesPerDayOnInterval(startInclusive,
endDate);
return new AllocateResourcesPerDayOnInterval(startInclusive, endDate);
}
private Iterable<PartialDay> getDays(IntraDayDate startInclusive,
IntraDayDate endExclusive) {
private Iterable<PartialDay> getDays(IntraDayDate startInclusive, IntraDayDate endExclusive) {
checkStartLessOrEqualToEnd(startInclusive, endExclusive);
Iterable<PartialDay> daysUntil = startInclusive
.daysUntil(endExclusive);
Iterable<PartialDay> daysUntil = startInclusive.daysUntil(endExclusive);
return daysUntil;
}
private final class AllocateResourcesPerDayOnInterval implements
IAllocateResourcesPerDay {
private final class AllocateResourcesPerDayOnInterval implements IAllocateResourcesPerDay {
private final IntraDayDate startInclusive;
private final IntraDayDate endExclusive;
private AllocateResourcesPerDayOnInterval(
IntraDayDate startInclusive, IntraDayDate endExclusive) {
private AllocateResourcesPerDayOnInterval(IntraDayDate startInclusive, IntraDayDate endExclusive) {
this.startInclusive = startInclusive;
this.endExclusive = IntraDayDate.max(startInclusive,
endExclusive);
this.endExclusive = IntraDayDate.max(startInclusive, endExclusive);
}
@Override
public void allocate(ResourcesPerDay resourcesPerDay) {
setIntendedResourcesPerDay(resourcesPerDay);
List<T> assignmentsCreated = createAssignments(resourcesPerDay,
startInclusive, endExclusive);
resetAllAllocationAssignmentsTo(assignmentsCreated,
startInclusive,
endExclusive);
List<T> assignmentsCreated = createAssignments(resourcesPerDay, startInclusive, endExclusive);
resetAllAllocationAssignmentsTo(assignmentsCreated, startInclusive, endExclusive);
updateResourcesPerDay();
}
}
@Override
public IAllocateEffortOnInterval onIntervalWithinTask(
final LocalDate start, final LocalDate end) {
public IAllocateEffortOnInterval onIntervalWithinTask(final LocalDate start, final LocalDate end) {
checkStartLessOrEqualToEnd(start, end);
return new OnSubIntervalAllocator(
new AllocationIntervalInsideTask(start, end));
return new OnSubIntervalAllocator(new AllocationIntervalInsideTask(start, end));
}
@Override
public IAllocateEffortOnInterval onIntervalWithinTask(
IntraDayDate start, IntraDayDate end) {
public IAllocateEffortOnInterval onIntervalWithinTask(IntraDayDate start, IntraDayDate end) {
checkStartLessOrEqualToEnd(start, end);
return new OnSubIntervalAllocator(new AllocationIntervalInsideTask(
start, end));
return new OnSubIntervalAllocator(new AllocationIntervalInsideTask(start, end));
}
@Override
public IAllocateEffortOnInterval onInterval(
final LocalDate startInclusive, final LocalDate endExclusive) {
public IAllocateEffortOnInterval onInterval(final LocalDate startInclusive, final LocalDate endExclusive) {
checkStartLessOrEqualToEnd(startInclusive, endExclusive);
return new OnSubIntervalAllocator(new AllocationInterval(
startInclusive, endExclusive));
return new OnSubIntervalAllocator(new AllocationInterval(startInclusive, endExclusive));
}
@Override
public IAllocateEffortOnInterval onInterval(IntraDayDate start,
IntraDayDate end) {
public IAllocateEffortOnInterval onInterval(IntraDayDate start, IntraDayDate end) {
checkStartLessOrEqualToEnd(start, end);
return new OnSubIntervalAllocator(
new AllocationInterval(start,
end));
return new OnSubIntervalAllocator(new AllocationInterval(start, end));
}
private class OnSubIntervalAllocator implements
IAllocateEffortOnInterval {
private class OnSubIntervalAllocator implements IAllocateEffortOnInterval {
private final AllocationInterval allocationInterval;
private OnSubIntervalAllocator(
AllocationInterval allocationInterval) {
private OnSubIntervalAllocator(AllocationInterval allocationInterval) {
this.allocationInterval = allocationInterval;
}
@ -873,8 +822,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
@Override
public void allocate(EffortDuration duration) {
List<T> assignmentsCreated = createAssignments(
allocationInterval, duration);
List<T> assignmentsCreated = createAssignments(allocationInterval, duration);
allocationInterval.resetAssignments(assignmentsCreated);
}
@ -885,25 +833,23 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
private void allocateDurationsByDay(AllocationInterval interval,
List<EffortDuration> durationsByDay) {
List<EffortDuration> rightSlice = interval
.getRightSlice(durationsByDay);
private void allocateDurationsByDay(AllocationInterval interval, List<EffortDuration> durationsByDay) {
List<EffortDuration> rightSlice = interval.getRightSlice(durationsByDay);
AvailabilityTimeLine availability = getAvailability();
List<T> assignments = createAssignments(interval, availability,
rightSlice.toArray(new EffortDuration[rightSlice.size()]));
List<T> 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);
final AllocationInterval interval = new AllocationInterval(getStartSpecifiedByTask(), end);
return getIAllocateEffortOnInterval(interval);
}
private IAllocateEffortOnInterval getIAllocateEffortOnInterval(
final AllocationInterval interval) {
private IAllocateEffortOnInterval getIAllocateEffortOnInterval(final AllocationInterval interval) {
return new IAllocateEffortOnInterval() {
@Override
@ -918,12 +864,9 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
@Override
public void allocate(List<EffortDuration> durationsByDay) {
List<EffortDuration> rightSlice = interval
.getRightSlice(durationsByDay);
List<EffortDuration> rightSlice = interval.getRightSlice(durationsByDay);
AvailabilityTimeLine availability = getAvailability();
createAssignments(interval, availability,
rightSlice.toArray(new EffortDuration[rightSlice
.size()]));
createAssignments(interval, availability, rightSlice.toArray(new EffortDuration[rightSlice.size()]));
}
};
@ -931,8 +874,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
@Override
public IAllocateEffortOnInterval fromEndUntil(IntraDayDate start) {
final AllocationInterval interval = new AllocationInterval(start,
task.getIntraDayEndDate());
final AllocationInterval interval = new AllocationInterval(start, task.getIntraDayEndDate());
return new IAllocateEffortOnInterval() {
@Override
@ -953,30 +895,26 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
};
}
private void allocateTheWholeAllocation(AllocationInterval interval,
EffortDuration durationToAssign) {
List<T> assignmentsCreated = createAssignments(interval,
durationToAssign);
ResourceAllocation.this.allocateTheWholeAllocation(interval,
assignmentsCreated);
private void allocateTheWholeAllocation(AllocationInterval interval, EffortDuration durationToAssign) {
List<T> assignmentsCreated = createAssignments(interval, durationToAssign);
ResourceAllocation.this.allocateTheWholeAllocation(interval, assignmentsCreated);
}
protected abstract AvailabilityTimeLine getResourcesAvailability();
private List<T> createAssignments(AllocationInterval interval,
EffortDuration durationToAssign) {
private List<T> createAssignments(AllocationInterval interval, EffortDuration durationToAssign) {
AvailabilityTimeLine availability = getAvailability();
Iterable<PartialDay> days = getDays(interval.getStartInclusive(),
interval.getEndExclusive());
EffortDuration[] durationsEachDay = secondsDistribution(
availability, days, durationToAssign);
Iterable<PartialDay> days = getDays(interval.getStartInclusive(), interval.getEndExclusive());
EffortDuration[] durationsEachDay = secondsDistribution(availability, days, durationToAssign);
return createAssignments(interval, availability, durationsEachDay);
}
private List<T> createAssignments(AllocationInterval interval,
private List<T> createAssignments(
AllocationInterval interval,
AvailabilityTimeLine availability,
EffortDuration[] durationsEachDay) {
List<T> result = new ArrayList<T>();
int i = 0;
for (PartialDay day : getDays(interval.getStartInclusive(),
@ -995,8 +933,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
AvailabilityTimeLine resourcesAvailability = getResourcesAvailability();
BaseCalendar taskCalendar = getTask().getCalendar();
if ( taskCalendar != null ) {
return taskCalendar.getAvailability()
.and(resourcesAvailability);
return taskCalendar.getAvailability().and(resourcesAvailability);
} else {
return resourcesAvailability;
}
@ -1013,34 +950,31 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
private EffortDuration[] secondsDistribution(
AvailabilityTimeLine availability, Iterable<PartialDay> days,
AvailabilityTimeLine availability,
Iterable<PartialDay> days,
EffortDuration duration) {
List<Capacity> capacities = new ArrayList<Capacity>();
for (PartialDay each : days) {
capacities.add(getCapacity(availability, each));
}
Distributor distributor = Distributor.among(capacities);
return distributor.distribute(duration).toArray(
new EffortDuration[0]);
return distributor.distribute(duration).toArray(new EffortDuration[0]);
}
private Capacity getCapacity(AvailabilityTimeLine availability,
PartialDay day) {
private Capacity getCapacity(AvailabilityTimeLine availability, PartialDay day) {
if ( availability.isValid(day.getDate()) ) {
return getCapacityAt(day);
} else {
return Capacity.create(zero())
.notOverAssignableWithoutLimit();
return Capacity.create(zero()).notOverAssignableWithoutLimit();
}
}
protected abstract Capacity getCapacityAt(PartialDay each);
private Share getShareAt(PartialDay day,
AvailabilityTimeLine availability) {
private Share getShareAt(PartialDay day, AvailabilityTimeLine availability) {
if ( availability.isValid(day.getDate()) ) {
EffortDuration capacityAtDay = getAllocationCalendar()
.getCapacityOn(day);
EffortDuration capacityAtDay = getAllocationCalendar().getCapacityOn(day);
return new Share(-capacityAtDay.getSeconds());
} else {
return new Share(Integer.MAX_VALUE);
@ -1089,21 +1023,19 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
protected abstract void copyAssignments(Scenario from, Scenario to);
protected void resetAssignmentsTo(List<T> assignments) {
resetAllAllocationAssignmentsTo(assignments,
task.getIntraDayStartDate(),
task.getIntraDayEndDate());
resetAllAllocationAssignmentsTo(assignments, task.getIntraDayStartDate(), task.getIntraDayEndDate());
}
protected void allocateTheWholeAllocation(AllocationInterval interval,
List<T> assignments) {
resetAllAllocationAssignmentsTo(assignments,
interval.getStartInclusive(), interval.getEndExclusive());
protected void allocateTheWholeAllocation(AllocationInterval interval, List<T> assignments) {
resetAllAllocationAssignmentsTo(assignments, interval.getStartInclusive(), interval.getEndExclusive());
updateResourcesPerDay();
}
protected void resetAllAllocationAssignmentsTo(List<T> assignments,
protected void resetAllAllocationAssignmentsTo(
List<T> assignments,
IntraDayDate intraDayStart,
IntraDayDate intraDayEnd) {
removingAssignments(withoutConsolidated(getAssignments()));
addingAssignments(assignments);
updateOriginalTotalAssigment();
@ -1121,13 +1053,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
private final IntraDayDate end;
AllocationInterval(IntraDayDate originalStart,
IntraDayDate originalEnd, IntraDayDate start, IntraDayDate end) {
AllocationInterval(IntraDayDate originalStart, IntraDayDate originalEnd, IntraDayDate start, IntraDayDate end) {
this.originalStart = originalStart;
this.originalEnd = originalEnd;
IntraDayDate startConsideringConsolidated = task
.hasConsolidations() ? IntraDayDate
.max(task.getFirstDayNotConsolidated(), start) : start;
IntraDayDate startConsideringConsolidated =
task.hasConsolidations() ? IntraDayDate.max(task.getFirstDayNotConsolidated(), start) : start;
this.start = IntraDayDate.min(startConsideringConsolidated, end);
this.end = IntraDayDate.max(this.start, end);
@ -1138,26 +1069,23 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
AllocationInterval(LocalDate startInclusive, LocalDate endExclusive) {
this(IntraDayDate.startOfDay(startInclusive), IntraDayDate
.startOfDay(endExclusive));
this(IntraDayDate.startOfDay(startInclusive), IntraDayDate.startOfDay(endExclusive));
}
public List<EffortDuration> getRightSlice(List<EffortDuration> original) {
List<EffortDuration> result = new ArrayList<EffortDuration>(
original);
final int numberOfDaysToFill = originalStart
.numberOfDaysUntil(originalEnd);
List<EffortDuration> result = new ArrayList<EffortDuration>(original);
final int numberOfDaysToFill = originalStart.numberOfDaysUntil(originalEnd);
for (int i = 0; i < numberOfDaysToFill - original.size(); i++) {
result.add(zero());
}
return result.subList(originalStart.numberOfDaysUntil(start),
return result.subList(
originalStart.numberOfDaysUntil(start),
result.size() - end.numberOfDaysUntil(originalEnd));
}
public void resetAssignments(List<T> assignmentsCreated) {
resetAssigmentsFittingAllocationDatesToResultingAssignments(this,
assignmentsCreated);
resetAssigmentsFittingAllocationDatesToResultingAssignments(this, assignmentsCreated);
}
public IntraDayDate getStartInclusive() {
@ -1169,35 +1097,30 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
public List<DayAssignment> getAssignmentsOnInterval() {
return getAssignments(this.start.getDate(),
this.end.asExclusiveEnd());
return getAssignments(this.start.getDate(), this.end.asExclusiveEnd());
}
public List<DayAssignment> getNoConsolidatedAssignmentsOnInterval() {
return DayAssignment.withConsolidatedValue(
getAssignmentsOnInterval(), false);
return DayAssignment.withConsolidatedValue(getAssignmentsOnInterval(), false);
}
public List<DayAssignment> getConsolidatedAssignmentsOnInterval() {
return DayAssignment.withConsolidatedValue(
getAssignmentsOnInterval(), true);
return DayAssignment.withConsolidatedValue(getAssignmentsOnInterval(), true);
}
}
class AllocationIntervalInsideTask extends AllocationInterval {
AllocationIntervalInsideTask(LocalDate startInclusive,
LocalDate endExclusive) {
this(IntraDayDate.startOfDay(startInclusive), IntraDayDate
.startOfDay(endExclusive));
AllocationIntervalInsideTask(LocalDate startInclusive, LocalDate endExclusive) {
this(IntraDayDate.startOfDay(startInclusive), IntraDayDate.startOfDay(endExclusive));
}
AllocationIntervalInsideTask(IntraDayDate startInclusive,
IntraDayDate endExclusive) {
super(startInclusive, endExclusive, IntraDayDate.max(
startInclusive, getTask()
.getFirstDayNotConsolidated()), IntraDayDate.min(
endExclusive, task.getIntraDayEndDate()));
AllocationIntervalInsideTask(IntraDayDate startInclusive, IntraDayDate endExclusive) {
super(
startInclusive,
endExclusive,
IntraDayDate.max(startInclusive, getTask().getFirstDayNotConsolidated()),
IntraDayDate.min(endExclusive, task.getIntraDayEndDate()));
}
@Override
@ -1206,9 +1129,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
}
protected void resetAssigmentsForInterval(
AllocationIntervalInsideTask interval,
List<T> assignmentsCreated) {
protected void resetAssigmentsForInterval(AllocationIntervalInsideTask interval, List<T> assignmentsCreated) {
IntraDayDate originalStart = getIntraDayStartDate();
IntraDayDate originalEnd = getIntraDayEndDate();
@ -1218,21 +1139,17 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
// 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()));
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
getDayAssignmentsState().setIntraDayEnd(
IntraDayDate.max(originalEnd, interval.getEndExclusive()));
getDayAssignmentsState().setIntraDayEnd(IntraDayDate.max(originalEnd, interval.getEndExclusive()));
}
private void updateAssignments(AllocationInterval interval,
List<T> assignmentsCreated) {
private void updateAssignments(AllocationInterval interval, List<T> assignmentsCreated) {
removingAssignments(withoutConsolidated(interval
.getAssignmentsOnInterval()));
removingAssignments(withoutConsolidated(interval.getAssignmentsOnInterval()));
addingAssignments(assignmentsCreated);
updateOriginalTotalAssigment();
@ -1240,8 +1157,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
void updateAssignmentsConsolidatedValues() {
LocalDate firstNotConsolidated = task.getFirstDayNotConsolidated()
.getDate();
LocalDate firstNotConsolidated = task.getFirstDayNotConsolidated().getDate();
for (T each : getAssignments()) {
each.setConsolidated(each.getDay().isBefore(firstNotConsolidated));
}
@ -1249,13 +1165,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
private void resetAssigmentsFittingAllocationDatesToResultingAssignments(
AllocationInterval interval, List<T> assignmentsCreated) {
updateAssignments(interval, assignmentsCreated);
LocalDate startConsideringAssignments = getStartConsideringAssignments();
IntraDayDate start = IntraDayDate
.startOfDay(startConsideringAssignments);
if (interval.getStartInclusive()
.areSameDay(startConsideringAssignments)) {
IntraDayDate start = IntraDayDate.startOfDay(startConsideringAssignments);
if ( interval.getStartInclusive().areSameDay(startConsideringAssignments) ) {
start = interval.getStartInclusive();
}
getDayAssignmentsState().setIntraDayStart(start);
@ -1268,8 +1183,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
getDayAssignmentsState().setIntraDayEnd(end);
}
private static <T extends DayAssignment> List<T> withoutConsolidated(
List<? extends T> assignments) {
private static <T extends DayAssignment> List<T> withoutConsolidated(List<? extends T> assignments) {
List<T> result = new ArrayList<T>();
for (T each : assignments) {
if ( !each.isConsolidated() ) {
@ -1280,22 +1194,17 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
protected final void addingAssignments(Collection<? extends T> assignments) {
getDayAssignmentsState().addingAssignments(
withoutAlreadyPresent(assignments));
getDayAssignmentsState().addingAssignments(withoutAlreadyPresent(assignments));
}
private List<? extends T> withoutAlreadyPresent(
Collection<? extends T> assignments) {
private List<? extends T> withoutAlreadyPresent(Collection<? extends T> assignments) {
if( assignments.isEmpty() ){
return Collections.emptyList();
}
LocalDate min = Collections.min(assignments,
DayAssignment.byDayComparator()).getDay();
LocalDate max = Collections.max(assignments,
DayAssignment.byDayComparator()).getDay();
Set<LocalDate> daysPresent = DayAssignment.byDay(
getAssignments(min, max.plusDays(1))).keySet();
LocalDate min = Collections.min(assignments, DayAssignment.byDayComparator()).getDay();
LocalDate max = Collections.max(assignments, DayAssignment.byDayComparator()).getDay();
Set<LocalDate> daysPresent = DayAssignment.byDay(getAssignments(min, max.plusDays(1))).keySet();
List<T> result = new ArrayList<T>();
for (T each : assignments) {
@ -1312,19 +1221,17 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
@SuppressWarnings("unchecked")
public void allocateLimitingDayAssignments(
List<? extends DayAssignment> assignments, IntraDayDate start,
IntraDayDate end) {
List<? extends DayAssignment> assignments, IntraDayDate start, IntraDayDate end) {
assert isLimiting();
resetAllAllocationAssignmentsTo((List<T>) assignments, start, end);
}
private void removingAssignments(
List<? extends DayAssignment> assignments) {
private void removingAssignments(List<? extends DayAssignment> assignments) {
getDayAssignmentsState().removingAssignments(assignments);
}
public final EffortDuration calculateTotalToDistribute(PartialDay day,
ResourcesPerDay resourcesPerDay) {
public final EffortDuration calculateTotalToDistribute(PartialDay day, ResourcesPerDay resourcesPerDay) {
return getAllocationCalendar().asDurationOn(day, resourcesPerDay);
}
@ -1332,8 +1239,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
return calculateResourcesPerDayFromAssignments(getAssignments());
}
private ResourcesPerDay calculateResourcesPerDayFromAssignments(
Collection<? extends T> assignments) {
private ResourcesPerDay calculateResourcesPerDayFromAssignments(Collection<? extends T> assignments) {
if ( assignments.isEmpty() ) {
return ResourcesPerDay.amount(0);
}
@ -1341,24 +1247,24 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
Map<LocalDate, List<T>> byDay = DayAssignment.byDay(assignments);
LocalDate min = Collections.min(byDay.keySet());
LocalDate max = Collections.max(byDay.keySet());
Iterable<PartialDay> daysToIterate = startFor(min).daysUntil(
endFor(max));
Iterable<PartialDay> daysToIterate = startFor(min).daysUntil(endFor(max));
EffortDuration sumTotalEffort = zero();
EffortDuration sumWorkableEffort = zero();
final ResourcesPerDay ONE_RESOURCE_PER_DAY = ResourcesPerDay.amount(1);
for (PartialDay day : daysToIterate) {
List<T> assignmentsAtDay = avoidNull(byDay.get(day.getDate()),
Collections.<T> emptyList());
EffortDuration incrementWorkable = getAllocationCalendar()
.asDurationOn(day, ONE_RESOURCE_PER_DAY);
List<T> assignmentsAtDay = avoidNull(byDay.get(day.getDate()), Collections.<T> emptyList());
EffortDuration incrementWorkable = getAllocationCalendar().asDurationOn(day, ONE_RESOURCE_PER_DAY);
sumWorkableEffort = sumWorkableEffort.plus(incrementWorkable);
sumTotalEffort = sumTotalEffort.plus(sumDuration(assignmentsAtDay));
}
if ( sumWorkableEffort.equals(zero()) ) {
return ResourcesPerDay.amount(0);
}
return ResourcesPerDay.calculateFrom(sumTotalEffort, sumWorkableEffort);
}
@ -1408,9 +1314,12 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
public ResourceAllocation<T> copy(Scenario scenario) {
Validate.notNull(scenario);
ResourceAllocation<T> copy = createCopy(scenario);
copy.assignmentsState = copy.toTransientStateWithInitial(
getUnorderedFor(scenario), getIntraDayStartDateFor(scenario),
getUnorderedFor(scenario),
getIntraDayStartDateFor(scenario),
getIntraDayEndFor(scenario));
copy.resourcesPerDay = resourcesPerDay;
copy.intendedTotalAssignment = intendedTotalAssignment;
copy.task = task;
@ -1420,8 +1329,10 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
private DayAssignmentsState toTransientStateWithInitial(
Collection<? extends T> initialAssignments, IntraDayDate start,
Collection<? extends T> initialAssignments,
IntraDayDate start,
IntraDayDate end) {
TransientState result = new TransientState(initialAssignments);
result.setIntraDayStart(start);
result.setIntraDayEnd(end);
@ -1508,8 +1419,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
protected List<T> getOrderedDayAssignments() {
if ( dayAssignmentsOrdered == null ) {
dayAssignmentsOrdered = DayAssignment
.orderedByDay(getUnorderedAssignments());
dayAssignmentsOrdered = DayAssignment.orderedByDay(getUnorderedAssignments());
}
return dayAssignmentsOrdered;
}
@ -1563,8 +1473,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
}
protected void removingAssignments(
List<? extends DayAssignment> assignments){
protected void removingAssignments(List<? extends DayAssignment> assignments){
removeAssignments(assignments);
clearCachedData();
for (DayAssignment each : assignments) {
@ -1572,11 +1481,9 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
}
protected abstract void removeAssignments(
List<? extends DayAssignment> assignments);
protected abstract void removeAssignments(List<? extends DayAssignment> assignments);
protected abstract void addAssignments(
Collection<? extends T> assignments);
protected abstract void addAssignments(Collection<? extends T> assignments);
@SuppressWarnings("unchecked")
public void mergeAssignments(ResourceAllocation<?> modification) {
@ -1678,11 +1585,9 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
return new ExplicitlySpecifiedScenarioState(container);
}
protected abstract IDayAssignmentsContainer<T> retrieveContainerFor(
Scenario scenario);
protected abstract IDayAssignmentsContainer<T> retrieveContainerFor(Scenario scenario);
protected abstract IDayAssignmentsContainer<T> retrieveOrCreateContainerFor(
Scenario scenario);
protected abstract IDayAssignmentsContainer<T> 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
@ -1691,12 +1596,10 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
* is changed since the assignments are cached and the assignments for the
* previous one would be returned<br />
*/
private class NoExplicitlySpecifiedScenario extends
DayAssignmentsState {
private class NoExplicitlySpecifiedScenario extends DayAssignmentsState {
@Override
protected final void removeAssignments(
List<? extends DayAssignment> assignments) {
protected final void removeAssignments(List<? extends DayAssignment> assignments) {
modificationsNotAllowed();
}
@ -1716,9 +1619,8 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
private void modificationsNotAllowed() {
throw new IllegalStateException(
"modifications to assignments can't be done "
+ "if the scenario on which to work on is not explicitly specified");
throw new IllegalStateException("modifications to assignments can't be done " +
"if the scenario on which to work on is not explicitly specified");
}
@Override
@ -1738,8 +1640,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
@Override
IntraDayDate getIntraDayEnd() {
return retrieveOrCreateContainerFor(currentScenario())
.getIntraDayEnd();
return retrieveOrCreateContainerFor(currentScenario()).getIntraDayEnd();
}
@Override
@ -1754,8 +1655,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
private class ExplicitlySpecifiedScenarioState extends
DayAssignmentsState {
private class ExplicitlySpecifiedScenarioState extends DayAssignmentsState {
private final IDayAssignmentsContainer<T> container;
@ -1775,8 +1675,7 @@ public abstract class ResourceAllocation<T extends DayAssignment> extends
}
@Override
protected void removeAssignments(
List<? extends DayAssignment> assignments) {
protected void removeAssignments(List<? extends DayAssignment> assignments) {
container.removeAll(assignments);
}

View file

@ -46,6 +46,7 @@ import org.libreplan.business.workingday.EffortDuration;
public class SpecificDayAssignment extends DayAssignment {
private abstract class ParentState {
abstract SpecificResourceAllocation getResourceAllocation();
abstract ParentState setParent(
@ -66,11 +67,9 @@ public class SpecificDayAssignment extends DayAssignment {
}
@Override
ParentState setParent(
SpecificResourceAllocation specificResourceAllocation) {
ParentState setParent(SpecificResourceAllocation specificResourceAllocation) {
if ( parent != null && parent != specificResourceAllocation ) {
throw new IllegalStateException(
"the allocation cannot be changed once it has been set");
throw new IllegalStateException("the allocation cannot be changed once it has been set");
}
this.parent = specificResourceAllocation;
return this;
@ -121,9 +120,9 @@ public class SpecificDayAssignment extends DayAssignment {
}
public static Set<SpecificDayAssignment> copy(
SpecificDayAssignmentsContainer container,
public static Set<SpecificDayAssignment> copy(SpecificDayAssignmentsContainer container,
Collection<? extends SpecificDayAssignment> specificDaysAssignment) {
Set<SpecificDayAssignment> result = new HashSet<SpecificDayAssignment>();
for (SpecificDayAssignment s : specificDaysAssignment) {
SpecificDayAssignment created = copyFromWithoutParent(s);
@ -135,16 +134,15 @@ public class SpecificDayAssignment extends DayAssignment {
return result;
}
private static SpecificDayAssignment copyFromWithoutParent(
SpecificDayAssignment assignment) {
SpecificDayAssignment copy = create(assignment.getDay(),
assignment.getDuration(), assignment.getResource());
private static SpecificDayAssignment copyFromWithoutParent(SpecificDayAssignment assignment) {
SpecificDayAssignment copy = create(assignment.getDay(), assignment.getDuration(), assignment.getResource());
copy.setConsolidated(assignment.isConsolidated());
return copy;
}
public static List<SpecificDayAssignment> copyToAssignmentsWithoutParent(
Collection<? extends SpecificDayAssignment> assignments) {
List<SpecificDayAssignment> result = new ArrayList<SpecificDayAssignment>();
for (SpecificDayAssignment each : assignments) {
result.add(copyFromWithoutParent(each));

View file

@ -38,14 +38,12 @@ import org.libreplan.business.workingday.IntraDayDate;
* for a {@link ResourceAllocation} at a {@link Scenario} <br />
* @author Óscar González Fernández <ogonzalez@igalia.com>
*/
public class SpecificDayAssignmentsContainer extends BaseEntity implements
IDayAssignmentsContainer<SpecificDayAssignment> {
public class SpecificDayAssignmentsContainer extends BaseEntity
implements IDayAssignmentsContainer<SpecificDayAssignment> {
public static SpecificDayAssignmentsContainer create(
SpecificResourceAllocation specificResourceAllocation,
public static SpecificDayAssignmentsContainer create(SpecificResourceAllocation specificResourceAllocation,
Scenario scenario) {
return create(new SpecificDayAssignmentsContainer(specificResourceAllocation,
scenario));
return create(new SpecificDayAssignmentsContainer(specificResourceAllocation, scenario));
}
private SpecificResourceAllocation resourceAllocation;
@ -71,8 +69,7 @@ public class SpecificDayAssignmentsContainer extends BaseEntity implements
return new HashSet<SpecificDayAssignment>(dayAssignments);
}
private SpecificDayAssignmentsContainer(
SpecificResourceAllocation resourceAllocation, Scenario scenario) {
private SpecificDayAssignmentsContainer(SpecificResourceAllocation resourceAllocation, Scenario scenario) {
Validate.notNull(resourceAllocation);
Validate.notNull(scenario);
this.resourceAllocation = resourceAllocation;
@ -112,8 +109,7 @@ public class SpecificDayAssignmentsContainer extends BaseEntity implements
dayAssignments.addAll(copyToThisContainer(assignments));
}
private Set<SpecificDayAssignment> copyToThisContainer(
Collection<? extends SpecificDayAssignment> assignments) {
private Set<SpecificDayAssignment> copyToThisContainer(Collection<? extends SpecificDayAssignment> assignments) {
return SpecificDayAssignment.copy(this, assignments);
}

View file

@ -60,12 +60,10 @@ import org.libreplan.business.workingday.ResourcesPerDay;
* Represents the relation between {@link Task} and a specific {@link Worker}.
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class SpecificResourceAllocation extends
ResourceAllocation<SpecificDayAssignment> implements IAllocatable {
public class SpecificResourceAllocation extends ResourceAllocation<SpecificDayAssignment> implements IAllocatable {
public static SpecificResourceAllocation create(Task task) {
return create(new SpecificResourceAllocation(
task));
return create(new SpecificResourceAllocation(task));
}
/**
@ -80,11 +78,9 @@ public class SpecificResourceAllocation extends
* @param task
* @return
*/
public static SpecificResourceAllocation createForLimiting(Resource resource,
Task task) {
public static SpecificResourceAllocation createForLimiting(Resource resource, Task task) {
assert resource.isLimitingResource();
SpecificResourceAllocation result = create(new SpecificResourceAllocation(
task));
SpecificResourceAllocation result = create(new SpecificResourceAllocation(task));
result.setResource(resource);
result.setResourcesPerDayToAmount(1);
return result;
@ -96,42 +92,35 @@ public class SpecificResourceAllocation extends
private Set<SpecificDayAssignmentsContainer> specificDayAssignmentsContainers = new HashSet<SpecificDayAssignmentsContainer>();
@Valid
private Set<SpecificDayAssignmentsContainer> getSpecificDayAssignmentsContainers() {
return new HashSet<SpecificDayAssignmentsContainer>(
specificDayAssignmentsContainers);
public Set<SpecificDayAssignmentsContainer> getSpecificDayAssignmentsContainers() {
return new HashSet<SpecificDayAssignmentsContainer>(specificDayAssignmentsContainers);
}
public static SpecificResourceAllocation createForTesting(
ResourcesPerDay resourcesPerDay, Task task) {
return create(new SpecificResourceAllocation(
resourcesPerDay, task));
public static SpecificResourceAllocation createForTesting(ResourcesPerDay resourcesPerDay, Task task) {
return create(new SpecificResourceAllocation(resourcesPerDay, task));
}
public SpecificResourceAllocation() {
}
@Override
protected SpecificDayAssignmentsContainer retrieveOrCreateContainerFor(
Scenario scenario) {
protected SpecificDayAssignmentsContainer retrieveOrCreateContainerFor(Scenario scenario) {
SpecificDayAssignmentsContainer retrieved = retrieveContainerFor(scenario);
if ( retrieved != null ) {
return retrieved;
}
SpecificDayAssignmentsContainer result = SpecificDayAssignmentsContainer
.create(this, scenario);
SpecificDayAssignmentsContainer result = SpecificDayAssignmentsContainer.create(this, scenario);
specificDayAssignmentsContainers.add(result);
return result;
}
@Override
protected SpecificDayAssignmentsContainer retrieveContainerFor(
Scenario scenario) {
protected SpecificDayAssignmentsContainer retrieveContainerFor(Scenario scenario) {
Map<Scenario, SpecificDayAssignmentsContainer> containers = containersByScenario();
return containers.get(scenario);
}
private SpecificResourceAllocation(ResourcesPerDay resourcesPerDay,
Task task) {
private SpecificResourceAllocation(ResourcesPerDay resourcesPerDay, Task task) {
super(resourcesPerDay, task);
}
@ -165,15 +154,12 @@ public class SpecificResourceAllocation extends
}
@Override
public IAllocateResourcesPerDay resourcesPerDayUntil(
IntraDayDate endExclusive) {
return new SpecificAssignmentsAllocator()
.resourcesPerDayUntil(endExclusive);
public IAllocateResourcesPerDay resourcesPerDayUntil(IntraDayDate endExclusive) {
return new SpecificAssignmentsAllocator().resourcesPerDayUntil(endExclusive);
}
@Override
public IAllocateResourcesPerDay resourcesPerDayFromEndUntil(
IntraDayDate start) {
public IAllocateResourcesPerDay resourcesPerDayFromEndUntil(IntraDayDate start) {
SpecificAssignmentsAllocator allocator = new SpecificAssignmentsAllocator();
return allocator.resourcesPerDayFromEndUntil(start);
}
@ -192,10 +178,8 @@ public class SpecificResourceAllocation extends
AssignmentsAllocator {
@Override
public List<SpecificDayAssignment> distributeForDay(PartialDay day,
EffortDuration effort) {
return Arrays.asList(SpecificDayAssignment.create(day.getDate(),
effort, resource));
public List<SpecificDayAssignment> distributeForDay(PartialDay day, EffortDuration effort) {
return Arrays.asList(SpecificDayAssignment.create(day.getDate(), effort, resource));
}
@Override
@ -221,29 +205,23 @@ public class SpecificResourceAllocation extends
}
@Override
public IAllocateEffortOnInterval onIntervalWithinTask(IntraDayDate start,
IntraDayDate end) {
return new SpecificAssignmentsAllocator().onIntervalWithinTask(start,
end);
public IAllocateEffortOnInterval onIntervalWithinTask(IntraDayDate start, IntraDayDate end) {
return new SpecificAssignmentsAllocator().onIntervalWithinTask(start, end);
}
@Override
public IAllocateEffortOnInterval onInterval(LocalDate startInclusive,
LocalDate endExclusive) {
return new SpecificAssignmentsAllocator().onInterval(startInclusive,
endExclusive);
public IAllocateEffortOnInterval onInterval(LocalDate startInclusive, LocalDate endExclusive) {
return new SpecificAssignmentsAllocator().onInterval(startInclusive, endExclusive);
}
@Override
public IAllocateEffortOnInterval onInterval(IntraDayDate start,
IntraDayDate end) {
public IAllocateEffortOnInterval onInterval(IntraDayDate start, IntraDayDate end) {
return new SpecificAssignmentsAllocator().onInterval(start, end);
}
@Override
protected ICalendar getCalendarGivenTaskCalendar(ICalendar taskCalendar) {
return CombinedWorkHours.minOf(taskCalendar, getResource()
.getCalendar());
return CombinedWorkHours.minOf(taskCalendar, getResource().getCalendar());
}
@Override
@ -327,39 +305,35 @@ public class SpecificResourceAllocation extends
* @param effortForNotConsolidatedPart
* @param endExclusive
*/
public void allocateWholeAllocationKeepingProportions(
EffortDuration effortForNotConsolidatedPart, IntraDayDate end) {
AllocationInterval interval = new AllocationInterval(
getIntraDayStartDate(), end);
public void allocateWholeAllocationKeepingProportions(EffortDuration effortForNotConsolidatedPart,
IntraDayDate end) {
List<DayAssignment> nonConsolidatedAssignments = interval
.getNoConsolidatedAssignmentsOnInterval();
ProportionalDistributor distributor = ProportionalDistributor
.create(asSeconds(nonConsolidatedAssignments));
AllocationInterval interval = new AllocationInterval(getIntraDayStartDate(), end);
EffortDuration[] effortsPerDay = asEfforts(distributor
.distribute(effortForNotConsolidatedPart.getSeconds()));
allocateTheWholeAllocation(
interval,
assignmentsForEfforts(nonConsolidatedAssignments, effortsPerDay));
List<DayAssignment> nonConsolidatedAssignments = interval.getNoConsolidatedAssignmentsOnInterval();
ProportionalDistributor distributor = ProportionalDistributor.create(asSeconds(nonConsolidatedAssignments));
EffortDuration[] effortsPerDay = asEfforts(distributor.distribute(effortForNotConsolidatedPart.getSeconds()));
allocateTheWholeAllocation(interval, assignmentsForEfforts(nonConsolidatedAssignments, effortsPerDay));
}
private EffortDuration[] asEfforts(int[] secondsArray) {
EffortDuration[] result = new EffortDuration[secondsArray.length];
for (int i = 0; i < result.length; i++) {
result[i] = EffortDuration.seconds(secondsArray[i]);
}
return result;
}
private List<SpecificDayAssignment> assignmentsForEfforts(
List<DayAssignment> assignments, EffortDuration[] newEffortsPerDay) {
private List<SpecificDayAssignment> assignmentsForEfforts(List<DayAssignment> assignments,
EffortDuration[] newEffortsPerDay) {
List<SpecificDayAssignment> result = new ArrayList<SpecificDayAssignment>();
int i = 0;
for (DayAssignment each : assignments) {
EffortDuration durationForAssignment = newEffortsPerDay[i++];
result.add(SpecificDayAssignment.create(each.getDay(),
durationForAssignment, resource));
result.add(SpecificDayAssignment.create(each.getDay(), durationForAssignment, resource));
}
return result;
}
@ -367,35 +341,32 @@ public class SpecificResourceAllocation extends
private int[] asSeconds(List<DayAssignment> assignments) {
int[] result = new int[assignments.size()];
int i = 0;
for (DayAssignment each : assignments) {
result[i++] = each.getDuration().getSeconds();
}
return result;
}
public void overrideConsolidatedDayAssignments(
SpecificResourceAllocation origin) {
public void overrideConsolidatedDayAssignments(SpecificResourceAllocation origin) {
if ( origin != null ) {
List<SpecificDayAssignment> originAssignments = origin
.getConsolidatedAssignments();
resetAssignmentsTo(SpecificDayAssignment
.copyToAssignmentsWithoutParent(originAssignments));
List<SpecificDayAssignment> originAssignments = origin.getConsolidatedAssignments();
resetAssignmentsTo(SpecificDayAssignment.copyToAssignmentsWithoutParent(originAssignments));
}
}
@Override
public EffortDuration getAssignedEffort(Criterion criterion,
final IntraDayDate startInclusive, final IntraDayDate endExclusive) {
public EffortDuration getAssignedEffort(Criterion criterion, final IntraDayDate startInclusive,
final IntraDayDate endExclusive) {
return EffortDuration.sum(
getIntervalsRelatedWith(criterion, startInclusive.getDate(),
endExclusive.asExclusiveEnd()),
new IEffortFrom<Interval>() {
return EffortDuration.sum(getIntervalsRelatedWith(criterion, startInclusive.getDate(),
endExclusive.asExclusiveEnd()), new IEffortFrom<Interval>() {
@Override
public EffortDuration from(Interval each) {
FixedPoint intervalStart = (FixedPoint) each.getStart();
FixedPoint intervalEnd = (FixedPoint) each.getEnd();
return getAssignedDuration(
IntraDayDate.convert(intervalStart.getDate(), startInclusive),
IntraDayDate.convert(intervalEnd.getDate(), endExclusive));
@ -403,12 +374,13 @@ public class SpecificResourceAllocation extends
});
}
private List<Interval> getIntervalsRelatedWith(Criterion criterion,
LocalDate startInclusive, LocalDate endExclusive) {
Interval queryInterval = AvailabilityTimeLine.Interval.create(
startInclusive, endExclusive);
private List<Interval> getIntervalsRelatedWith(Criterion criterion, LocalDate startInclusive,
LocalDate endExclusive) {
Interval queryInterval = AvailabilityTimeLine.Interval.create(startInclusive, endExclusive);
List<Interval> result = new ArrayList<Interval>();
for (Interval each : getIntervalsThisAllocationInterferesWith(criterion)) {
if ( queryInterval.overlaps(each) ) {
result.add(queryInterval.intersect(each));
@ -417,20 +389,17 @@ public class SpecificResourceAllocation extends
return result;
}
private List<Interval> getIntervalsThisAllocationInterferesWith(
Criterion criterion) {
AvailabilityTimeLine availability = AvailabilityCalculator
.getCriterionsAvailabilityFor(Collections.singleton(criterion),
resource);
private List<Interval> 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<Interval> intervalsRelatedWith = getIntervalsRelatedWith(
criterion, startInclusive, endExclusive);
public boolean interferesWith(Criterion criterion, LocalDate startInclusive, LocalDate endExclusive) {
List<Interval> intervalsRelatedWith = getIntervalsRelatedWith(criterion, startInclusive, endExclusive);
return !intervalsRelatedWith.isEmpty();
}

View file

@ -155,7 +155,7 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
private Set<ResourceAllocation<?>> resourceAllocations = new HashSet<ResourceAllocation<?>>();
@Valid
private Set<ResourceAllocation<?>> getResourceAlloations() {
private Set<ResourceAllocation<?>> getResourceAllocations() {
return new HashSet<ResourceAllocation<?>>(resourceAllocations);
}
@ -241,8 +241,7 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
if ( isLimiting() ) {
result.addAll(getLimitingResourceAllocations());
} else {
result.addAll(ResourceAllocation
.getSatisfied(resourceAllocations));
result.addAll(ResourceAllocation.getSatisfied(resourceAllocations));
}
return Collections.unmodifiableSet(result);
}
@ -285,25 +284,21 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
if ( !isLimiting() ) {
throw new IllegalStateException("this is not a limiting task");
}
return getAssociatedLimitingResourceAllocation()
.getLimitingResourceQueueElement();
return getAssociatedLimitingResourceAllocation().getLimitingResourceQueueElement();
}
public boolean isLimitingAndHasDayAssignments() {
ResourceAllocation<?> resourceAllocation = getAssociatedLimitingResourceAllocation();
return resourceAllocation != null
&& resourceAllocation.isLimitingAndHasDayAssignments();
return resourceAllocation != null && resourceAllocation.isLimitingAndHasDayAssignments();
}
public void addResourceAllocation(ResourceAllocation<?> resourceAllocation) {
addResourceAllocation(resourceAllocation, true);
}
public void addResourceAllocation(ResourceAllocation<?> resourceAllocation,
boolean generateDayAssignments) {
public void addResourceAllocation(ResourceAllocation<?> resourceAllocation, boolean generateDayAssignments) {
if ( !resourceAllocation.getTask().equals(this) ) {
throw new IllegalArgumentException(
"the resourceAllocation's task must be this task");
throw new IllegalArgumentException("the resourceAllocation's task must be this task");
}
resourceAllocations.add(resourceAllocation);
if ( generateDayAssignments ) {
@ -795,17 +790,14 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
new WithPotentiallyNewResources(searcher));
}
private void reassign(Scenario onScenario, Direction direction,
WithPotentiallyNewResources strategy) {
private void reassign(Scenario onScenario, Direction direction, WithPotentiallyNewResources strategy) {
try {
this.lastAllocationDirection = direction;
if ( isLimiting() ) {
return;
}
List<ModifiedAllocation> copied = ModifiedAllocation.copy(onScenario,
getResourceAlloations());
List<ResourceAllocation<?>> toBeModified = ModifiedAllocation
.modified(copied);
List<ModifiedAllocation> copied = ModifiedAllocation.copy(onScenario, getResourceAllocations());
List<ResourceAllocation<?>> toBeModified = ModifiedAllocation.modified(copied);
if ( toBeModified.isEmpty() ) {
return;
}
@ -814,12 +806,12 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
updateDerived(copied);
List<ResourceAllocation<?>> newAllocations = emptyList(), removedAllocations = emptyList();
mergeAllocation(onScenario, getIntraDayStartDate(),
getIntraDayEndDate(), workableDays, calculatedValue,
mergeAllocation(onScenario, getIntraDayStartDate(), getIntraDayEndDate(), workableDays, calculatedValue,
newAllocations, copied, removedAllocations);
} catch (Exception e) {
LOG.error("reassignment for task: " + this
+ " couldn't be completed", e);
LOG.error("reassignment for task: " + this + " couldn't be completed", e);
}
}
@ -1186,7 +1178,7 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
if (this.currentStatus != null) {
return this.currentStatus == TaskStatusEnum.IN_PROGRESS;
} else {
boolean advanceBetweenZeroAndOne = this.advancePertentageIsGreaterThanZero() &&
boolean advanceBetweenZeroAndOne = this.advancePercentageIsGreaterThanZero() &&
!advancePercentageIsOne();
boolean outcome = advanceBetweenZeroAndOne || this.hasAttachedWorkReports();
if (outcome == true) {
@ -1208,8 +1200,7 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
return false;
}
} else if ( dependencyType.equals(Type.START_START) ) {
if (!dependency.getOrigin().isFinished() &&
!dependency.getOrigin().isInProgress()) {
if ( !dependency.getOrigin().isFinished() && !dependency.getOrigin().isInProgress() ) {
return false;
}
}
@ -1229,8 +1220,7 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
return true;
}
} else if ( dependencyType.equals(Type.START_START) ) {
if (!dependency.getOrigin().isFinished() &&
!dependency.getOrigin().isInProgress()) {
if ( !dependency.getOrigin().isFinished() && !dependency.getOrigin().isInProgress() ) {
return true;
}
}
@ -1238,7 +1228,7 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
return false;
}
private boolean advancePertentageIsGreaterThanZero() {
private boolean advancePercentageIsGreaterThanZero() {
return this.getAdvancePercentage().compareTo(BigDecimal.ZERO) > 0;
}
@ -1270,4 +1260,13 @@ public class Task extends TaskElement implements ITaskPositionConstrained {
return getPositionConstraint().getConstraintType().equals(type);
}
@Override
public void setParent(TaskGroup taskGroup) {
super.setParent(taskGroup);
}
@Override
public void setTaskSource(TaskSource taskSource) {
super.setTaskSource(taskSource);
}
}

View file

@ -135,8 +135,7 @@ public abstract class TaskElement extends BaseEntity {
return this.getEndAsLocalDate();
}
protected static <T extends TaskElement> T create(T taskElement,
TaskSource taskSource) {
protected static <T extends TaskElement> T create(T taskElement, TaskSource taskSource) {
taskElement.setTaskSource(taskSource);
taskElement.updateDeadlineFromOrderElement();
taskElement.setName(taskElement.getOrderElement().getName());
@ -317,8 +316,7 @@ public abstract class TaskElement extends BaseEntity {
}
public void setStartDate(Date startDate) {
setIntraDayStartDate(IntraDayDate.startOfDay(LocalDate
.fromDateFields(startDate)));
setIntraDayStartDate(IntraDayDate.startOfDay(LocalDate.fromDateFields(startDate)));
}
public void setIntraDayStartDate(IntraDayDate startDate) {
@ -328,20 +326,17 @@ public abstract class TaskElement extends BaseEntity {
IntraDayDate previousStart = getIntraDayStartDate();
IntraDayDate previousEnd = getIntraDayEndDate();
this.startDate = startDate;
datesInterceptor.setStartDate(previousStart, previousEnd,
getIntraDayStartDate());
datesInterceptor.setStartDate(previousStart, previousEnd, getIntraDayStartDate());
}
@NotNull
public Date getEndDate() {
return endDate != null ? endDate.toDateTimeAtStartOfDay().toDate()
: null;
return (endDate != null) ? endDate.toDateTimeAtStartOfDay().toDate() : null;
}
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) {
@ -576,20 +571,19 @@ public abstract class TaskElement extends BaseEntity {
return result;
}
private void addToResult(SortedMap<LocalDate, EffortDuration> result,
LocalDate date, EffortDuration duration) {
EffortDuration current = result.get(date) != null ? result.get(date)
: zero();
private void addToResult(SortedMap<LocalDate, EffortDuration> result, LocalDate date, EffortDuration duration) {
EffortDuration current = result.get(date) != null ? result.get(date) : zero();
result.put(date, current.plus(duration));
}
public List<DayAssignment> getDayAssignments(DayAssignment.FilterType filter) {
List<DayAssignment> dayAssignments = new ArrayList<DayAssignment>();
Set<ResourceAllocation<?>> resourceAllocations = getSatisfiedResourceAllocations();
for (ResourceAllocation<?> resourceAllocation : resourceAllocations) {
dayAssignments.addAll(resourceAllocation.getAssignments());
Set<DerivedAllocation> derivedAllocations = resourceAllocation
.getDerivedAllocations();
Set<DerivedAllocation> derivedAllocations = resourceAllocation.getDerivedAllocations();
for (DerivedAllocation each : derivedAllocations) {
dayAssignments.addAll(each.getAssignments());
}

View file

@ -194,16 +194,20 @@ public class TaskGroup extends TaskElement {
public void setTaskChildrenTo(List<TaskElement> children) {
Validate.noNullElements(children);
int positionOnTaskElements = 0;
for (int i = 0; i < children.size(); i++) {
TaskElement element = children.get(i);
element.setParent(this);
if ( positionOnTaskElements >= taskElements.size() ) {
taskElements.add(element);
} else {
while (positionOnTaskElements < taskElements.size()
&& isMilestone(taskElements.get(positionOnTaskElements))) {
while (positionOnTaskElements < taskElements.size() &&
isMilestone(taskElements.get(positionOnTaskElements))) {
positionOnTaskElements++;
}
if ( positionOnTaskElements >= taskElements.size() ) {
taskElements.add(element);
} else {
@ -212,8 +216,7 @@ public class TaskGroup extends TaskElement {
}
positionOnTaskElements++;
}
ListIterator<TaskElement> listIterator = taskElements
.listIterator(positionOnTaskElements);
ListIterator<TaskElement> listIterator = taskElements.listIterator(positionOnTaskElements);
while (listIterator.hasNext()) {
TaskElement current = listIterator.next();
if ( !isMilestone(current) ) {
@ -390,4 +393,8 @@ public class TaskGroup extends TaskElement {
return false;
}
@Override
public void setTaskSource(TaskSource taskSource) {
super.setTaskSource(taskSource);
}
}

View file

@ -55,8 +55,8 @@ import org.libreplan.business.resources.daos.ICriterionDAO;
public class Criterion extends IntegrationEntity implements ICriterion,
Comparable<Criterion> {
public static Criterion createUnvalidated(String code, String name,
CriterionType type, Criterion parent, Boolean active) {
public static Criterion createUnvalidated(String code, String name, CriterionType type, Criterion parent,
Boolean active) {
Criterion criterion = create(new Criterion(), code);

View file

@ -75,8 +75,7 @@ import org.libreplan.business.workingday.IntraDayDate.PartialDay;
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
*/
public abstract class Resource extends IntegrationEntity implements
IHumanIdentifiable, Comparable<Resource> {
public abstract class Resource extends IntegrationEntity implements IHumanIdentifiable, Comparable<Resource> {
public static class AllResourceAssignments implements IAssignmentsOnResourceCalculator {
@ -86,8 +85,7 @@ public abstract class Resource extends IntegrationEntity implements
}
}
public static List<Machine> machines(
Collection<? extends Resource> resources) {
public static List<Machine> machines(Collection<? extends Resource> resources) {
return filter(Machine.class, resources);
}
@ -95,8 +93,7 @@ public abstract class Resource extends IntegrationEntity implements
return filter(Worker.class, resources);
}
public static <T extends Resource> List<T> filter(Class<T> klass,
Collection<? extends Resource> resources) {
public static <T extends Resource> List<T> filter(Class<T> klass, Collection<? extends Resource> resources) {
List<T> result = new ArrayList<T>();
for (Resource each : resources) {
if ( klass.isInstance(each) ) {
@ -185,8 +182,7 @@ public abstract class Resource extends IntegrationEntity implements
List<DayAssignment> result = new ArrayList<DayAssignment>();
Scenario current = Registry.getScenarioManager().getCurrent();
for (DayAssignment each : dayAssignments) {
if (each.getScenario() != null
&& each.getScenario().equals(current)) {
if ( each.getScenario() != null && each.getScenario().equals(current) ) {
result.add(each);
}
}
@ -206,8 +202,7 @@ public abstract class Resource extends IntegrationEntity implements
List<DayAssignment> calculateAssignments() {
List<DayAssignment> result = new ArrayList<DayAssignment>();
for (DayAssignment each : dayAssignments) {
if (isTransient(each)
|| each.getScenario().equals(currentScenario)) {
if ( isTransient(each) || each.getScenario().equals(currentScenario) ) {
result.add(each);
}
}
@ -223,8 +218,7 @@ public abstract class Resource extends IntegrationEntity implements
@Valid
public Set<CriterionSatisfaction> getCriterionSatisfactions() {
Set<CriterionSatisfaction> satisfactionActives =
new HashSet<CriterionSatisfaction>();
Set<CriterionSatisfaction> satisfactionActives = new HashSet<CriterionSatisfaction>();
for(CriterionSatisfaction satisfaction:criterionSatisfactions){
if( !satisfaction.isIsDeleted() ) {
satisfactionActives.add(satisfaction);
@ -233,12 +227,10 @@ public abstract class Resource extends IntegrationEntity implements
return satisfactionActives;
}
public CriterionSatisfaction getCriterionSatisfactionByCode(String code)
throws InstanceNotFoundException {
public CriterionSatisfaction getCriterionSatisfactionByCode(String code) throws InstanceNotFoundException {
if ( StringUtils.isBlank(code) ) {
throw new InstanceNotFoundException(code,
CriterionSatisfaction.class.getName());
throw new InstanceNotFoundException(code, CriterionSatisfaction.class.getName());
}
for (CriterionSatisfaction i : criterionSatisfactions) {
@ -247,8 +239,7 @@ public abstract class Resource extends IntegrationEntity implements
}
}
throw new InstanceNotFoundException(code,
CriterionSatisfaction.class.getName());
throw new InstanceNotFoundException(code, CriterionSatisfaction.class.getName());
}
@ -858,11 +849,11 @@ public abstract class Resource extends IntegrationEntity implements
public EffortDuration getAssignedDurationDiscounting(
Map<Long, Set<BaseEntity>> allocationsFromWhichDiscountHours,
LocalDate day) {
EffortDuration result = zero();
for (DayAssignment dayAssignment : getAssignmentsForDay(day)) {
if (!dayAssignment
.belongsToSomeOf(allocationsFromWhichDiscountHours)) {
if ( !dayAssignment.belongsToSomeOf(allocationsFromWhichDiscountHours) ) {
result = result.plus(dayAssignment.getDuration());
}
}
@ -876,8 +867,7 @@ public abstract class Resource extends IntegrationEntity implements
this.dayAssignments.addAll(assignments);
}
public void removeAssignments(
Collection<? extends DayAssignment> assignments) {
public void removeAssignments(Collection<? extends DayAssignment> assignments) {
Validate.noNullElements(assignments);
clearCachedData();
this.dayAssignments.removeAll(assignments);
@ -961,6 +951,7 @@ public abstract class Resource extends IntegrationEntity implements
newList.add(satisfaction);
}
}
//Create a activeList with not eliminated Satifaction
Set<CriterionSatisfaction> activeList = new HashSet<CriterionSatisfaction>();
for(CriterionSatisfaction satisfaction : addlist){
@ -968,13 +959,13 @@ public abstract class Resource extends IntegrationEntity implements
activeList.add(satisfaction);
}
}
validateSatisfactions(activeList);
criterionSatisfactions.clear();
criterionSatisfactions.addAll(newList);
}
private void validateSatisfactions(Set<CriterionSatisfaction> satisfactions)
throws ValidationException {
private void validateSatisfactions(Set<CriterionSatisfaction> satisfactions) throws ValidationException {
for (CriterionSatisfaction satisfaction : satisfactions) {
final Set<CriterionSatisfaction> remainingSatisfactions = new HashSet<CriterionSatisfaction>();
remainingSatisfactions.addAll(satisfactions);
@ -983,15 +974,12 @@ public abstract class Resource extends IntegrationEntity implements
}
}
private void validateSatisfaction(CriterionSatisfaction satisfaction,
Set<CriterionSatisfaction> satisfactions)
private void validateSatisfaction(CriterionSatisfaction satisfaction, Set<CriterionSatisfaction> satisfactions)
throws ValidationException {
if ( !canAddSatisfaction(satisfaction, satisfactions) ) {
String message = getReasonForNotAddingSatisfaction(satisfaction
.getCriterion().getType());
throw new ValidationException(invalidValue(message, "resource",
this, satisfaction));
String message = getReasonForNotAddingSatisfaction(satisfaction.getCriterion().getType());
throw new ValidationException(invalidValue(message, "resource", this, satisfaction));
}
}
@ -1001,15 +989,12 @@ public abstract class Resource extends IntegrationEntity implements
}
public boolean satisfiesCriterions(Collection<? extends ICriterion> criterions) {
ICriterion compositedCriterion = CriterionCompounder.buildAnd(
criterions).getResult();
ICriterion compositedCriterion = CriterionCompounder.buildAnd(criterions).getResult();
return compositedCriterion.isSatisfiedBy(this);
}
public boolean satisfiesCriterionsAtSomePoint(
Collection<? extends Criterion> criterions) {
AvailabilityTimeLine availability = AvailabilityCalculator
.getCriterionsAvailabilityFor(criterions, this);
public boolean satisfiesCriterionsAtSomePoint(Collection<? extends Criterion> criterions) {
AvailabilityTimeLine availability = AvailabilityCalculator.getCriterionsAvailabilityFor(criterions, this);
return !availability.getValidPeriods().isEmpty();
}
@ -1072,8 +1057,7 @@ public abstract class Resource extends IntegrationEntity implements
*/
for (CriterionSatisfaction i : getCriterionSatisfactions()) {
if (!(i.isStartDateSpecified() && i
.isPositiveTimeInterval())) {
if ( !(i.isStartDateSpecified() && i.isPositiveTimeInterval()) ) {
return true;
}
@ -1100,8 +1084,7 @@ public abstract class Resource extends IntegrationEntity implements
* If not, it does not make sense to check assignment overlapping.
*/
for (ResourcesCostCategoryAssignment each : getResourcesCostCategoryAssignments()) {
if (!(each.isInitDateSpecified() && each
.isPositiveTimeInterval())) {
if ( !(each.isInitDateSpecified() && each.isPositiveTimeInterval()) ) {
return false;
}
}
@ -1190,24 +1173,24 @@ public abstract class Resource extends IntegrationEntity implements
@AssertTrue(message = "You have exceeded the maximum limit of resources")
public boolean isMaxResourcesConstraint() {
return Registry.getTransactionService()
.runOnAnotherReadOnlyTransaction(new IOnTransaction<Boolean>() {
return Registry.getTransactionService().runOnAnotherReadOnlyTransaction(new IOnTransaction<Boolean>() {
@Override
public Boolean execute() {
Configuration configuration = Registry
.getConfigurationDAO().getConfiguration();
Configuration configuration = Registry.getConfigurationDAO().getConfiguration();
if ( configuration == null ) {
return true;
}
Integer maxResources = configuration.getMaxResources();
if ( maxResources != null && maxResources > 0 ) {
List<Resource> resources = Registry
.getResourceDAO().findAll();
List<Resource> resources = Registry.getResourceDAO().findAll();
int resourcesNumber = resources.size();
if ( isNewObject() ) {
resourcesNumber++;
}
if ( resourcesNumber > maxResources ) {
return false;
}

View file

@ -29,8 +29,7 @@ import org.apache.commons.lang.Validate;
* Implementation of {@link ITreeParentNode} that mutates a list <br />
* @author Óscar González Fernández <ogonzalez@igalia.com>
*/
public abstract class TreeNodeOnList<T extends ITreeNode<T>> implements
ITreeParentNode<T> {
public abstract class TreeNodeOnList<T extends ITreeNode<T>> implements ITreeParentNode<T> {
private final List<T> children;

View file

@ -73,11 +73,9 @@ public class EffortDuration implements Comparable<EffortDuration> {
}
}
private static final Pattern lenientEffortDurationSpecification = Pattern
.compile("(\\d+)(\\s*:\\s*\\d+\\s*)*");
private static final Pattern lenientEffortDurationSpecification = Pattern.compile("(\\d+)(\\s*:\\s*\\d+\\s*)*");
private static final Pattern contiguousDigitsPattern = Pattern
.compile("\\d+");
private static final Pattern contiguousDigitsPattern = Pattern.compile("\\d+");
/**
* If an {@link EffortDuration} can't be parsed <code>null</code> is
@ -379,11 +377,9 @@ public class EffortDuration implements Comparable<EffortDuration> {
return EffortDuration.seconds(total.seconds / items);
}
private static int roundHalfUpToHours(
EnumMap<Granularity, Integer> components) {
private static int roundHalfUpToHours(EnumMap<Granularity, Integer> components) {
int seconds = components.get(Granularity.SECONDS);
int minutes = components.get(Granularity.MINUTES)
+ (seconds < 30 ? 0 : 1);
int minutes = components.get(Granularity.MINUTES) + (seconds < 30 ? 0 : 1);
int hours = components.get(Granularity.HOURS) + (minutes < 30 ? 0 : 1);
return hours;
}

View file

@ -377,8 +377,7 @@ public class IntraDayDate implements Comparable<IntraDayDate> {
return result;
}
private static Iterator<PartialDay> createIterator(
final IntraDayDate start, final IterationPredicate predicate) {
private static Iterator<PartialDay> createIterator(final IntraDayDate start, final IterationPredicate predicate) {
return new Iterator<IntraDayDate.PartialDay>() {
private IntraDayDate current = start;
@ -399,8 +398,7 @@ public class IntraDayDate implements Comparable<IntraDayDate> {
}
private IntraDayDate calculateNext(IntraDayDate date) {
IntraDayDate nextDay = IntraDayDate.startOfDay(date.date
.plusDays(1));
IntraDayDate nextDay = IntraDayDate.startOfDay(date.date.plusDays(1));
return predicate.limitNext(nextDay);
}
@ -452,18 +450,13 @@ public class IntraDayDate implements Comparable<IntraDayDate> {
* @return a new {@link IntraDayDate}
*/
public IntraDayDate increaseBy(ResourcesPerDay resourcesPerDay, EffortDuration effort) {
EffortDuration newEnd = this.getEffortDuration().plus(
calculateProportionalDuration(resourcesPerDay,
effort));
EffortDuration newEnd = this.getEffortDuration().plus(calculateProportionalDuration(resourcesPerDay, effort));
return IntraDayDate.create(getDate(), newEnd);
}
private EffortDuration calculateProportionalDuration(
ResourcesPerDay resourcesPerDay, EffortDuration effort) {
private EffortDuration calculateProportionalDuration(ResourcesPerDay resourcesPerDay, EffortDuration effort) {
int seconds = effort.getSeconds();
BigDecimal end = new BigDecimal(seconds).divide(
resourcesPerDay.getAmount(),
RoundingMode.HALF_UP);
BigDecimal end = new BigDecimal(seconds).divide(resourcesPerDay.getAmount(), RoundingMode.HALF_UP);
return seconds(end.intValue());
}
@ -478,20 +471,16 @@ public class IntraDayDate implements Comparable<IntraDayDate> {
* @param effort
* @return a new {@link IntraDayDate}
*/
public IntraDayDate decreaseBy(ResourcesPerDay resourcesPerDay,
EffortDuration effort) {
EffortDuration proportionalDuration = calculateProportionalDuration(
resourcesPerDay, effort);
public IntraDayDate decreaseBy(ResourcesPerDay resourcesPerDay, EffortDuration effort) {
EffortDuration proportionalDuration = calculateProportionalDuration(resourcesPerDay, effort);
if ( getEffortDuration().compareTo(proportionalDuration) > 0 ) {
return IntraDayDate.create(getDate(),
getEffortDuration().minus(proportionalDuration));
return IntraDayDate.create(getDate(), getEffortDuration().minus(proportionalDuration));
} else {
return IntraDayDate.startOfDay(getDate());
}
}
public static IntraDayDate convert(LocalDate date,
IntraDayDate morePreciseAlternative) {
public static IntraDayDate convert(LocalDate date, IntraDayDate morePreciseAlternative) {
LocalDate morePreciseDate = morePreciseAlternative.getDate();
if ( morePreciseDate.equals(date) ) {
return morePreciseAlternative;
@ -514,8 +503,7 @@ public class IntraDayDate implements Comparable<IntraDayDate> {
if ( !getEffortDuration().isZero()) {
result = result.minus(EffortDuration.hours(8));
result = result.plus(EffortDuration.hours(8).minus(
getEffortDuration()));
result = result.plus(EffortDuration.hours(8).minus(getEffortDuration()));
}
if ( !end.getEffortDuration().isZero() ) {

View file

@ -38,37 +38,31 @@ public class ProportionalDistributorTest {
@Test
public void mustGiveTheSameDistributionForSameTotal() {
ProportionalDistributor distributor = ProportionalDistributor.create(
100, 200);
ProportionalDistributor distributor = ProportionalDistributor.create(100, 200);
assertThat(distributor.distribute(300), equalToDistribution(100, 200));
}
@Test
public void exactDivisionsWorkOk() {
ProportionalDistributor distributor = ProportionalDistributor.create(
100, 100, 100);
assertThat(distributor.distribute(600), equalToDistribution(200, 200,
200));
ProportionalDistributor distributor = ProportionalDistributor.create(100, 100, 100);
assertThat(distributor.distribute(600), equalToDistribution(200, 200, 200));
}
@Test
public void distributingZeroGivesZeroShares() {
ProportionalDistributor distributor = ProportionalDistributor.create(
100, 100, 100);
ProportionalDistributor distributor = ProportionalDistributor.create(100, 100, 100);
assertThat(distributor.distribute(0), equalToDistribution(0, 0, 0));
}
@Test
public void ifOneOfTheProportionsIsZeroAlwaysGivesZeros() {
ProportionalDistributor distributor = ProportionalDistributor.create(
100, 100, 0);
ProportionalDistributor distributor = ProportionalDistributor.create(100, 100, 0);
assertThat(distributor.distribute(100), equalToDistribution(50, 50, 0));
}
@Test
public void ifEmptySharesProvidedItDistributesEqually() {
ProportionalDistributor distributor = ProportionalDistributor.create(0,
0, 0, 0);
ProportionalDistributor distributor = ProportionalDistributor.create(0, 0, 0, 0);
assertThat(distributor.distribute(4), equalToDistribution(1, 1, 1, 1));
assertThat(distributor.distribute(5), equalToDistribution(2, 1, 1, 1));
assertThat(distributor.distribute(6), equalToDistribution(2, 2, 1, 1));
@ -84,15 +78,13 @@ public class ProportionalDistributorTest {
@Test
public void disputedPartGoesToFirstIfEqualWeight() {
ProportionalDistributor distributor = ProportionalDistributor.create(
10, 10, 10);
ProportionalDistributor distributor = ProportionalDistributor.create(10, 10, 10);
assertThat(distributor.distribute(10), equalToDistribution(4, 3, 3));
}
@Test
public void distributionIsKept() {
ProportionalDistributor distributor = ProportionalDistributor.create(2,
3, 5);
ProportionalDistributor distributor = ProportionalDistributor.create(2, 3, 5);
assertThat(distributor.distribute(1), equalToDistribution(0, 0, 1));
assertThat(distributor.distribute(2), equalToDistribution(0, 1, 1));
assertThat(distributor.distribute(3), equalToDistribution(1, 1, 1));
@ -105,8 +97,7 @@ public class ProportionalDistributorTest {
@Test
public void addingOneEachTime() {
ProportionalDistributor distributor = ProportionalDistributor.create(
99, 101, 800);
ProportionalDistributor distributor = ProportionalDistributor.create(99, 101, 800);
assertThat(distributor.distribute(1), equalToDistribution(0, 0, 1));
assertThat(distributor.distribute(3), equalToDistribution(0, 0, 3));
assertThat(distributor.distribute(6), equalToDistribution(0, 1, 5));
@ -138,8 +129,7 @@ public class ProportionalDistributorTest {
@Override
public void describeTo(Description description) {
description.appendText("must equal "
+ Arrays.toString(distribution));
description.appendText("must equal " + Arrays.toString(distribution));
}
};
}
@ -151,8 +141,7 @@ public class ProportionalDistributorTest {
@Test
public void notThrowDivisionByZeroExceptionAtDistributeMehtod() {
ProportionalDistributor distributor = ProportionalDistributor
.create(100);
ProportionalDistributor distributor = ProportionalDistributor.create(100);
distributor.distribute(0);
}

View file

@ -50,11 +50,9 @@ import org.springframework.test.context.transaction.TransactionalTestExecutionLi
* @author Bob McCune
* @version 1.0
*/
public class DBUnitTestExecutionListener extends
TransactionalTestExecutionListener {
public class DBUnitTestExecutionListener extends TransactionalTestExecutionListener {
private static final Log logger = LogFactory
.getLog(DBUnitTestExecutionListener.class);
private static final Log logger = LogFactory.getLog(DBUnitTestExecutionListener.class);
private static final String DEFAULT_DATASOURCE_NAME = "dataSource";
private static final String TABLE_TYPES[] = { "TABLE", "ALIAS" };

View file

@ -29,10 +29,9 @@ package org.libreplan.business.test;
*/
public class BusinessGlobalNames {
public final static String BUSINESS_SPRING_CONFIG_TEST_FILE =
"classpath:/libreplan-business-spring-config-test.xml";
public final static String BUSINESS_SPRING_CONFIG_TEST_FILE = "classpath:/libreplan-business-spring-config-test.xml";
public final static String DBUNIT_CONFIG_TEST_FILE = "/dbunit-data.xml";
public final static String DBUNIT_CONFIG_TEST_FILE =
"/dbunit-data.xml";
private BusinessGlobalNames () {}
}

View file

@ -52,10 +52,8 @@ public class DefaultAdvanceTypesBootstrapListenerTest {
private IAdvanceTypeDAO advanceTypeDAO;
private IDataBootstrap getAdvanceTypeBootstrap() {
String simpleName = DefaultAdvanceTypesBootstrapListener.class
.getSimpleName();
return dataBootstraps.get(simpleName.substring(0, 1).toLowerCase()
+ simpleName.substring(1));
String simpleName = DefaultAdvanceTypesBootstrapListener.class.getSimpleName();
return dataBootstraps.get(simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1));
}
@Test

View file

@ -57,8 +57,7 @@ public class AdvanceAssignmentDAOTest {
private AdvanceType givenAdvanceType() {
BigDecimal value = new BigDecimal(100);
BigDecimal precision = BigDecimal.ONE;
AdvanceType advanceType = AdvanceType.create("advance-type", value,
true, precision, true, false);
AdvanceType advanceType = AdvanceType.create("advance-type", value, true, precision, true, false);
advanceTypeDAO.save(advanceType);
return advanceType;
}
@ -66,8 +65,7 @@ public class AdvanceAssignmentDAOTest {
@Test
@Transactional
public void saveValidAdvanceAssignment() {
AdvanceAssignment advance = DirectAdvanceAssignment.create(false,
BigDecimal.TEN);
AdvanceAssignment advance = DirectAdvanceAssignment.create(false, BigDecimal.TEN);
advance.setAdvanceType(givenAdvanceType());
advanceAssignmentDAO.save(advance);
assertTrue(advance.getId() != null);
@ -76,8 +74,7 @@ public class AdvanceAssignmentDAOTest {
@Test(expected = ValidationException.class)
@Transactional
public void saveAdvanceAssignmentWithZeroAsMaxValue() {
AdvanceAssignment advance = DirectAdvanceAssignment.create(false,
BigDecimal.ZERO);
AdvanceAssignment advance = DirectAdvanceAssignment.create(false, BigDecimal.ZERO);
advance.setAdvanceType(givenAdvanceType());
advanceAssignmentDAO.save(advance);
assertTrue(advance.getId() != null);
@ -86,8 +83,7 @@ public class AdvanceAssignmentDAOTest {
@Test(expected = ValidationException.class)
@Transactional
public void saveAdvanceAssignmentWithNegativeNumberAsMaxValue() {
AdvanceAssignment advance = DirectAdvanceAssignment.create(false,
BigDecimal.valueOf(-10));
AdvanceAssignment advance = DirectAdvanceAssignment.create(false, BigDecimal.valueOf(-10));
advance.setAdvanceType(givenAdvanceType());
advanceAssignmentDAO.save(advance);
assertTrue(advance.getId() != null);

View file

@ -111,18 +111,13 @@ public class GenericResourceAllocationTest {
private Task givenTaskWithStartAndEnd(Interval interval) {
Task task = createNiceMock(Task.class);
setupCriterions(task);
IntraDayDate start = IntraDayDate.startOfDay(interval.getStart()
.toLocalDate());
IntraDayDate end = IntraDayDate.startOfDay(interval.getEnd()
.toLocalDate());
expect(task.getStartDate()).andReturn(interval.getStart().toDate())
.anyTimes();
IntraDayDate start = IntraDayDate.startOfDay(interval.getStart().toLocalDate());
IntraDayDate end = IntraDayDate.startOfDay(interval.getEnd().toLocalDate());
expect(task.getStartDate()).andReturn(interval.getStart().toDate()).anyTimes();
expect(task.getIntraDayStartDate()).andReturn(start).anyTimes();
expect(task.getEndDate()).andReturn(interval.getEnd().toDate())
.anyTimes();
expect(task.getEndDate()).andReturn(interval.getEnd().toDate()).anyTimes();
expect(task.getIntraDayEndDate()).andReturn(end).anyTimes();
expect(task.getFirstDayNotConsolidated()).andReturn(start)
.anyTimes();
expect(task.getFirstDayNotConsolidated()).andReturn(start).anyTimes();
expect(task.getCalendar()).andReturn(baseCalendar).anyTimes();
replay(task);
return this.task = task;
@ -137,8 +132,7 @@ public class GenericResourceAllocationTest {
}
private void setupCriterions(Task task) {
expect(task.getCriterions()).andReturn(givenPredefinedCriterions())
.anyTimes();
expect(task.getCriterions()).andReturn(givenPredefinedCriterions()).anyTimes();
}
private void givenGenericResourceAllocationForTask(Task task) {
@ -159,9 +153,7 @@ public class GenericResourceAllocationTest {
}
private void setupIsSatisfiedByAll(Criterion criterion) {
expect(
criterion.isSatisfiedBy(isA(Resource.class),
isA(LocalDate.class))).andReturn(true).anyTimes();
expect(criterion.isSatisfiedBy(isA(Resource.class), isA(LocalDate.class))).andReturn(true).anyTimes();
}
private void givenWorkersWithoutLoadAndWithoutCalendar() {
@ -175,9 +167,8 @@ public class GenericResourceAllocationTest {
public static void mockZeroLoad(Resource... resources) {
for (Resource each : resources) {
expect(
each.getAssignedDurationDiscounting(isA(Map.class),
isA(LocalDate.class))).andReturn(zero()).anyTimes();
expect(each.getAssignedDurationDiscounting(isA(Map.class), isA(LocalDate.class)))
.andReturn(zero()).anyTimes();
}
}
@ -219,37 +210,33 @@ public class GenericResourceAllocationTest {
}
private Worker createWorkerWithLoad(ResourceCalendar resourceCalendar,
int hours) {
return createWorkerWithLoad(resourceCalendar,
new LoadSpec(hours(hours)));
private Worker createWorkerWithLoad(ResourceCalendar resourceCalendar, int hours) {
return createWorkerWithLoad(resourceCalendar, new LoadSpec(hours(hours)));
}
private Worker createWorkerWithLoad(ResourceCalendar resourceCalendar,
final LoadSpec loadSpec) {
private Worker createWorkerWithLoad(ResourceCalendar resourceCalendar, final LoadSpec loadSpec) {
Worker result = createNiceMock(Worker.class);
expect(result.getCalendar()).andReturn(resourceCalendar).anyTimes();
expect(
result.getAssignedDurationDiscounting(isA(Map.class),
isA(LocalDate.class))).andAnswer(
expect(result.getAssignedDurationDiscounting(isA(Map.class), isA(LocalDate.class))).andAnswer(
new IAnswer<EffortDuration>() {
@Override
public EffortDuration answer() throws Throwable {
Object[] currentArguments = EasyMock
.getCurrentArguments();
Object[] currentArguments = EasyMock.getCurrentArguments();
LocalDate date = (LocalDate) currentArguments[1];
return loadSpec.getLoad(date);
}
}).anyTimes();
expect(result.getSatisfactionsFor(isA(Criterion.class))).andReturn(
satisfactionsForPredefinedCriterions(result)).anyTimes();
expect(result.getSatisfactionsFor(isA(Criterion.class)))
.andReturn(satisfactionsForPredefinedCriterions(result)).anyTimes();
replay(result);
return result;
}
private List<CriterionSatisfaction> satisfactionsForPredefinedCriterions(
Resource resource) {
private List<CriterionSatisfaction> satisfactionsForPredefinedCriterions(Resource resource) {
List<CriterionSatisfaction> result = new ArrayList<CriterionSatisfaction>();
for (Criterion each : criterions) {
result.add(CriterionSatisfaction.create(each, resource,
@ -259,22 +246,18 @@ public class GenericResourceAllocationTest {
}
private org.libreplan.business.resources.entities.Interval fromVeryEarlyTime() {
return org.libreplan.business.resources.entities.Interval
.from(new LocalDate(0, 1, 1));
return org.libreplan.business.resources.entities.Interval.from(new LocalDate(0, 1, 1));
}
private void givenCalendarsForResources(int capacity1, int capacity2,
int capacity3) {
givenCalendarsForResources(fromHours(capacity1), fromHours(capacity2),
fromHours(capacity3));
private void givenCalendarsForResources(int capacity1, int capacity2, int capacity3) {
givenCalendarsForResources(fromHours(capacity1), fromHours(capacity2), fromHours(capacity3));
}
private Capacity fromHours(int hours) {
return Capacity.create(hours(hours)).overAssignableWithoutLimit();
}
private void givenCalendarsForResources(Capacity capacity1,
Capacity capacity2, Capacity capacity3) {
private void givenCalendarsForResources(Capacity capacity1, Capacity capacity2, Capacity capacity3) {
workerCalendars = new ArrayList<ResourceCalendar>();
workerCalendars.add(createCalendar(ResourceCalendar.class, capacity1));
workerCalendars.add(createCalendar(ResourceCalendar.class, capacity2));
@ -282,18 +265,16 @@ public class GenericResourceAllocationTest {
}
private void givenWorkersWithLoads(int hours1, int hours2, int hours3) {
givenWorkersWithLoads(LoadSpec.withHours(hours1),
LoadSpec.withHours(hours2), LoadSpec.withHours(hours3));
givenWorkersWithLoads(LoadSpec.withHours(hours1), LoadSpec.withHours(hours2), LoadSpec.withHours(hours3));
}
private void givenWorkersWithLoads(LoadSpec load1, LoadSpec load2,
LoadSpec load3) {
private void givenWorkersWithLoads(LoadSpec load1, LoadSpec load2, LoadSpec load3) {
ResourceCalendar[] calendars;
if ( workerCalendars == null ) {
calendars = new ResourceCalendar[] { null, null, null };
} else {
calendars = new ResourceCalendar[] { workerCalendars.get(0),
workerCalendars.get(1), workerCalendars.get(2) };
calendars =
new ResourceCalendar[] { workerCalendars.get(0), workerCalendars.get(1), workerCalendars.get(2) };
}
worker1 = createWorkerWithLoad(calendars[0], load1);
worker2 = createWorkerWithLoad(calendars[1], load2);
@ -302,50 +283,49 @@ public class GenericResourceAllocationTest {
}
private void givenBaseCalendarWithoutExceptions(int hoursPerDay) {
BaseCalendar baseCalendar = createCalendar(BaseCalendar.class, Capacity
.create(hours(hoursPerDay)).overAssignableWithoutLimit());
BaseCalendar baseCalendar =
createCalendar(BaseCalendar.class, Capacity.create(hours(hoursPerDay)).overAssignableWithoutLimit());
this.baseCalendar = baseCalendar;
}
private <T extends BaseCalendar> T createCalendar(Class<T> klass,
final Capacity capacity) {
private <T extends BaseCalendar> T createCalendar(Class<T> klass, final Capacity capacity) {
return createCalendar(klass, capacity, 1);
}
private <T extends BaseCalendar> T createCalendar(Class<T> klass,
final Capacity capacity, int units) {
private <T extends BaseCalendar> T createCalendar(Class<T> klass, final Capacity capacity, int units) {
final Capacity capacityMultipliedByUnits = capacity.multiplyBy(units);
BaseCalendar baseCalendar = createNiceMock(klass);
expect(baseCalendar.getCapacityOn(isA(PartialDay.class))).andAnswer(
new IAnswer<EffortDuration>() {
@Override
public EffortDuration answer() throws Throwable {
PartialDay day = (PartialDay) getCurrentArguments()[0];
return day.limitWorkingDay(capacityMultipliedByUnits
.getStandardEffort());
return day.limitWorkingDay(capacityMultipliedByUnits.getStandardEffort());
}
}).anyTimes();
expect(baseCalendar.isActive(isA(LocalDate.class))).andReturn(true)
.anyTimes();
expect(baseCalendar.canWorkOn(isA(LocalDate.class))).andReturn(true)
.anyTimes();
expect(baseCalendar.getAvailability()).andReturn(
AvailabilityTimeLine.allValid()).anyTimes();
expect(baseCalendar.isActive(isA(LocalDate.class))).andReturn(true).anyTimes();
expect(baseCalendar.canWorkOn(isA(LocalDate.class))).andReturn(true).anyTimes();
expect(baseCalendar.getAvailability()).andReturn(AvailabilityTimeLine.allValid()).anyTimes();
IAnswer<EffortDuration> durationAnswer = new IAnswer<EffortDuration>() {
@Override
public EffortDuration answer() throws Throwable {
PartialDay day = (PartialDay) getCurrentArguments()[0];
ResourcesPerDay resourcesPerDay = (ResourcesPerDay) getCurrentArguments()[1];
return capacityMultipliedByUnits.limitDuration(resourcesPerDay
.asDurationGivenWorkingDayOf(day.limitWorkingDay(capacity
.getStandardEffort())));
return capacityMultipliedByUnits.limitDuration(
resourcesPerDay.asDurationGivenWorkingDayOf(day.limitWorkingDay(capacity.getStandardEffort())));
}
};
expect(
baseCalendar.asDurationOn(isA(PartialDay.class),
isA(ResourcesPerDay.class))).andAnswer(durationAnswer)
.anyTimes();
expect(baseCalendar.asDurationOn(isA(PartialDay.class), isA(ResourcesPerDay.class)))
.andAnswer(durationAnswer).anyTimes();
expect(baseCalendar.getCapacityWithOvertime(isA(LocalDate.class)))
.andReturn(capacityMultipliedByUnits).anyTimes();
@ -360,24 +340,21 @@ public class GenericResourceAllocationTest {
@Test
public void theCriterionsAreCopied() {
givenGenericResourceAllocation();
GenericResourceAllocation copied = (GenericResourceAllocation) genericResourceAllocation
.copy(mockScenario());
GenericResourceAllocation copied = (GenericResourceAllocation) genericResourceAllocation.copy(mockScenario());
assertThat(copied.getCriterions(), equalTo(criterions));
}
@Test
public void hasTheCriterionsOfTheTask() {
givenGenericResourceAllocation();
assertThat(genericResourceAllocation.getCriterions(),
equalTo(criterions));
assertThat(genericResourceAllocation.getCriterions(), equalTo(criterions));
}
@Test
public void getOrderedAssignmentsReturnsEmptyListIfNotExistsWorker() {
givenWorkersWithoutLoadAndWithoutCalendar();
givenGenericResourceAllocation();
List<GenericDayAssignment> assignments = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignments = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertNotNull(assignments);
assertTrue(assignments.isEmpty());
}
@ -389,13 +366,10 @@ public class GenericResourceAllocationTest {
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
genericResourceAllocation.forResources(Arrays.asList(worker1))
.allocate(ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignments = genericResourceAllocation
.getAssignments();
assertThat(assignments,
haveResourceAllocation(genericResourceAllocation));
List<GenericDayAssignment> assignments = genericResourceAllocation.getAssignments();
assertThat(assignments, haveResourceAllocation(genericResourceAllocation));
}
@Test
@ -403,18 +377,14 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
genericResourceAllocation.forResources(Arrays.asList(worker1))
.allocate(ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
assertThat(orderedAssignmentsFor, from(start).consecutiveDays(
TASK_DURATION_DAYS));
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(orderedAssignmentsFor, from(start).consecutiveDays(TASK_DURATION_DAYS));
}
@Test
@ -422,8 +392,7 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
ResourcesPerDay resourcesPerDay = ResourcesPerDay.amount(1);
@ -432,10 +401,8 @@ public class GenericResourceAllocationTest {
.resourcesPerDayUntil(plusDays(start, 2))
.allocate(resourcesPerDay);
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
int hoursPerDay = resourcesPerDay.asDurationGivenWorkingDayOf(
EffortDuration.hours(8)).getHours();
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
int hoursPerDay = resourcesPerDay.asDurationGivenWorkingDayOf(EffortDuration.hours(8)).getHours();
assertThat(orderedAssignmentsFor, haveHours(hoursPerDay, hoursPerDay));
}
@ -444,22 +411,18 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
ResourcesPerDay resourcesPerDay = ResourcesPerDay.amount(1);
genericResourceAllocation.forResources(Arrays.asList(worker1))
.allocate(resourcesPerDay);
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(resourcesPerDay);
genericResourceAllocation.forResources(Arrays.asList(worker1))
.resourcesPerDayUntil(plusDays(start, 2))
.allocate(resourcesPerDay);
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
int hoursPerDay = resourcesPerDay.asDurationGivenWorkingDayOf(
EffortDuration.hours(8)).getHours();
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
int hoursPerDay = resourcesPerDay.asDurationGivenWorkingDayOf(EffortDuration.hours(8)).getHours();
assertThat(orderedAssignmentsFor, haveHours(hoursPerDay, hoursPerDay));
}
@ -475,8 +438,7 @@ public class GenericResourceAllocationTest {
.resourcesPerDayUntil(minusDays(start, 1))
.allocate(resourcesPerDay);
assertTrue(genericResourceAllocation.getOrderedAssignmentsFor(worker1)
.isEmpty());
assertTrue(genericResourceAllocation.getOrderedAssignmentsFor(worker1).isEmpty());
}
@Test(expected = IllegalArgumentException.class)
@ -503,45 +465,38 @@ public class GenericResourceAllocationTest {
genericResourceAllocation.forResources(Arrays.asList(worker1))
.resourcesPerDayUntil(IntraDayDate.startOfDay(start))
.allocate(resourcesPerDay);
assertThat(genericResourceAllocation.getResourcesPerDay(),
equalTo(ResourcesPerDay.amount(0)));
assertTrue(genericResourceAllocation.getOrderedAssignmentsFor(worker1)
.isEmpty());
assertThat(genericResourceAllocation.getResourcesPerDay(), equalTo(ResourcesPerDay.amount(0)));
assertTrue(genericResourceAllocation.getOrderedAssignmentsFor(worker1).isEmpty());
}
@Test
public void theResourcesPerDayAreChangedWhenTheAllocationIsDone() {
givenTaskWithStartAndEnd(toInterval(new LocalDate(2006, 10, 5), Period
.days(2)));
givenTaskWithStartAndEnd(toInterval(new LocalDate(2006, 10, 5), Period.days(2)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
ResourcesPerDay assignedResourcesPerDay = ResourcesPerDay.amount(5);
genericResourceAllocation.forResources(workers).allocate(
assignedResourcesPerDay);
assertThat(genericResourceAllocation.getResourcesPerDay(),
equalTo(assignedResourcesPerDay));
genericResourceAllocation.forResources(workers).allocate(assignedResourcesPerDay);
assertThat(genericResourceAllocation.getResourcesPerDay(), equalTo(assignedResourcesPerDay));
}
@Test
public void allocatingSeveralResourcesPerDayHavingJustOneResourceProducesOvertime() {
LocalDate start = new LocalDate(2006, 10, 5);
final Integer standardHoursPerDay = SameWorkHoursEveryDay
.getDefaultWorkingDay()
.getCapacityOn(PartialDay.wholeDay(start)).getHours();
final Integer standardHoursPerDay =
SameWorkHoursEveryDay.getDefaultWorkingDay().getCapacityOn(PartialDay.wholeDay(start)).getHours();
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(standardHoursPerDay);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
genericResourceAllocation.forResources(Arrays.asList(worker1))
.allocate(ResourcesPerDay.amount(2));
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(2));
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
assertThat(orderedAssignmentsFor.get(0).getHours(),
equalTo(standardHoursPerDay * 2));
List<GenericDayAssignment> orderedAssignmentsFor = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(orderedAssignmentsFor.get(0).getHours(), equalTo(standardHoursPerDay * 2));
}
@Test
@ -550,16 +505,13 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 1;
final int halfWorkingDay = 4;
givenBaseCalendarWithoutExceptions(halfWorkingDay);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
genericResourceAllocation.forResources(Arrays.asList(worker1))
.allocate(ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assigmments = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assigmments = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assigmments, haveHours(halfWorkingDay));
}
@ -567,20 +519,18 @@ public class GenericResourceAllocationTest {
public void ifThereisNoTaskCalendarTheWorkingHoursAreSpecifiedbyTheDefaultWorkingDay() {
LocalDate start = new LocalDate(2006, 10, 5);
final int TASK_DURATION_DAYS = 1;
final Integer defaultWorkableHours = SameWorkHoursEveryDay
.getDefaultWorkingDay()
.getCapacityOn(PartialDay.wholeDay(start)).getHours();
final Integer defaultWorkableHours =
SameWorkHoursEveryDay.getDefaultWorkingDay().getCapacityOn(PartialDay.wholeDay(start)).getHours();
givenBaseCalendarWithoutExceptions(defaultWorkableHours);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
genericResourceAllocation.forResources(Arrays.asList(worker1))
.allocate(ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(Arrays.asList(worker1)).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assigmments = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assigmments = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assigmments.get(0).getHours(), equalTo(defaultWorkableHours));
}
@ -589,22 +539,19 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(3, 12, 1);
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(1, 1, 1, 1));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours());
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation
.getOrderedAssignmentsFor(worker3);
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation.getOrderedAssignmentsFor(worker3);
assertThat(assignmentsWorker3, haveHours(7, 7, 7, 7));
}
@ -613,29 +560,28 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start,
Period.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(
LoadSpec.withHours(3)
.withException(start.plusDays(1), hours(1))
.withException(start.plusDays(3), hours(8)),
LoadSpec.withHours(12).withException(start.plusDays(3), zero()),
LoadSpec.withHours(1)
.withException(start.plusDays(1), hours(3))
.withException(start.plusDays(3), hours(8)));
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(1, 7, 1));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours(8));
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation
.getOrderedAssignmentsFor(worker3);
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation.getOrderedAssignmentsFor(worker3);
assertThat(assignmentsWorker3, haveHours(7, 1, 7));
}
@ -644,27 +590,22 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start,
Period.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(
LoadSpec.withHours(0)
.withException(start.plusDays(3), hours(4)),
LoadSpec.withHours(0).withException(start.plusDays(3), hours(4)),
LoadSpec.withHours(12),
LoadSpec.withHours(1)
.withException(start.plusDays(3), hours(0)));
LoadSpec.withHours(1).withException(start.plusDays(3), hours(0)));
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation
.getOrderedAssignmentsFor(worker3);
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation.getOrderedAssignmentsFor(worker3);
assertThat(assignmentsWorker3, haveHours(4));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(8, 8, 8, 4));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours());
}
@ -673,28 +614,23 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start,
Period.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
Capacity workingDay = Capacity.create(hours(8));
Capacity with2ExtraHours = workingDay
.withAllowedExtraEffort(hours(2));
givenCalendarsForResources(with2ExtraHours, with2ExtraHours,
workingDay.overAssignableWithoutLimit());
Capacity with2ExtraHours = workingDay.withAllowedExtraEffort(hours(2));
givenCalendarsForResources(with2ExtraHours, with2ExtraHours, workingDay.overAssignableWithoutLimit());
givenWorkersWithLoads(0, 0, 0);
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(4));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(4));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(10, 10, 10, 10));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours(10, 10, 10, 10));
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation
.getOrderedAssignmentsFor(worker3);
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation.getOrderedAssignmentsFor(worker3);
assertThat(assignmentsWorker3, haveHours(12, 12, 12, 12));
}
@ -704,50 +640,52 @@ public class GenericResourceAllocationTest {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start,
Period.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(0, 0, 0);
genericResourceAllocation.forResources(asList(worker1, worker2))
.allocate(ResourcesPerDay.amount(2));
genericResourceAllocation.forResources(asList(worker1, worker2)).allocate(ResourcesPerDay.amount(2));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(8, 8, 8, 8));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours(8, 8, 8, 8));
}
@Test
public void virtualWorkersAreGivenMoreLoad() {
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(8, 8, 8);
givenVirtualWorkerWithCapacityAndLoad(Capacity.create(hours(8))
.overAssignableWithoutLimit(), 5, hours(40));
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation
.getOrderedAssignmentsFor(worker3);
final int TASK_DURATION_DAYS = 4;
givenBaseCalendarWithoutExceptions(8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(8, 8, 8);
givenVirtualWorkerWithCapacityAndLoad(Capacity.create(hours(8)).overAssignableWithoutLimit(), 5, hours(40));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation.getOrderedAssignmentsFor(worker3);
assertThat(assignmentsWorker3, haveHours(1, 1, 1, 1));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(1, 1, 1, 1));
List<GenericDayAssignment> virtualWorkerAssignments = genericResourceAllocation
.getOrderedAssignmentsFor(workers.get(workers.size() - 1));
List<GenericDayAssignment> virtualWorkerAssignments =
genericResourceAllocation.getOrderedAssignmentsFor(workers.get(workers.size() - 1));
assertThat(virtualWorkerAssignments, haveHours(5, 5, 5, 5));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours(1, 1, 1, 1));
}
@ -757,22 +695,19 @@ public class GenericResourceAllocationTest {
givenBaseCalendarWithoutExceptions(8);
givenCalendarsForResources(4, 4, 0);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start, Period
.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(4, 4, 4);
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation
.getOrderedAssignmentsFor(worker1);
List<GenericDayAssignment> assignmentsWorker1 = genericResourceAllocation.getOrderedAssignmentsFor(worker1);
assertThat(assignmentsWorker1, haveHours(4, 4, 4, 4));
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation
.getOrderedAssignmentsFor(worker2);
List<GenericDayAssignment> assignmentsWorker2 = genericResourceAllocation.getOrderedAssignmentsFor(worker2);
assertThat(assignmentsWorker2, haveHours(4, 4, 4, 4));
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation
.getOrderedAssignmentsFor(worker3);
List<GenericDayAssignment> assignmentsWorker3 = genericResourceAllocation.getOrderedAssignmentsFor(worker3);
assertThat(assignmentsWorker3, haveHours());
}
@ -782,16 +717,16 @@ public class GenericResourceAllocationTest {
givenBaseCalendarWithoutExceptions(8);
givenCalendarsForResources(8, 8, 8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start,
Period.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(8, 6, 2);
IntraDayDate end = ResourceAllocation.allocating(
Arrays.asList(ResourcesPerDayModification.create(
IntraDayDate end = ResourceAllocation.allocating(Arrays.asList(ResourcesPerDayModification.create(
genericResourceAllocation,
ResourcesPerDay.amount(new BigDecimal(1)), workers)))
.untilAllocating(hours(12));
ResourcesPerDay.amount(new BigDecimal(1)), workers))).untilAllocating(hours(12));
assertThat(end.getDate(), equalTo(start.plusDays(1)));
EffortDuration biggestLastAssignment = hours(4);
assertThat(end.getEffortDuration(), equalTo(biggestLastAssignment));
}
@ -802,36 +737,33 @@ public class GenericResourceAllocationTest {
givenBaseCalendarWithoutExceptions(8);
givenCalendarsForResources(8, 8, 8);
LocalDate start = new LocalDate(2006, 10, 5);
givenTaskWithStartAndEnd(toInterval(start,
Period.days(TASK_DURATION_DAYS)));
givenTaskWithStartAndEnd(toInterval(start, Period.days(TASK_DURATION_DAYS)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(8, 2, 6);
IntraDayDate end = ResourceAllocation.allocating(
Arrays.asList(ResourcesPerDayModification.create(
genericResourceAllocation, ResourcesPerDay.amount(1),
IntraDayDate end = ResourceAllocation.allocating(Arrays.asList(ResourcesPerDayModification.create(
genericResourceAllocation,
ResourcesPerDay.amount(1),
workers))).untilAllocating(hours(16));
assertThat(end.getDate(), equalTo(start.plusDays(2)));
}
private void givenVirtualWorkerWithCapacityAndLoad(
Capacity capacityPerDayAndUnit,
int capacityUnits,
private void givenVirtualWorkerWithCapacityAndLoad(Capacity capacityPerDayAndUnit, int capacityUnits,
EffortDuration load) {
VirtualWorker worker = createNiceMock(VirtualWorker.class);
expect(
worker.getAssignedDurationDiscounting(isA(Map.class),
isA(LocalDate.class))).andReturn(load)
.anyTimes();
expect(worker.getCalendar()).andReturn(
createCalendar(ResourceCalendar.class, capacityPerDayAndUnit,
capacityUnits)).anyTimes();
expect(worker.getAssignedDurationDiscounting(isA(Map.class), isA(LocalDate.class))).andReturn(load).anyTimes();
expect(worker.getCalendar())
.andReturn(createCalendar(ResourceCalendar.class, capacityPerDayAndUnit, capacityUnits)).anyTimes();
replay(worker);
workers.add(worker);
}
private static Interval toInterval(LocalDate start, Period period) {
return new Interval(start.toDateTimeAtStartOfDay(), start.plus(period)
.toDateTimeAtStartOfDay());
return new Interval(start.toDateTimeAtStartOfDay(), start.plus(period).toDateTimeAtStartOfDay());
}
@Test
@ -844,36 +776,32 @@ public class GenericResourceAllocationTest {
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(3, 12, 1);
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
assertThat(genericResourceAllocation.getAssignedHours(),
equalTo(workableHoursDay * days));
assertThat(genericResourceAllocation.getAssignedHours(), equalTo(workableHoursDay * days));
final int hoursOnSubinterval = 3;
int daysSubinterval = 2;
genericResourceAllocation.forResources(workers)
.onIntervalWithinTask(start, start.plusDays(daysSubinterval))
.allocateHours(hoursOnSubinterval);
assertThat(genericResourceAllocation.getAssignedHours(),
equalTo(hoursOnSubinterval + (days - daysSubinterval)
* workableHoursDay));
equalTo(hoursOnSubinterval + (days - daysSubinterval) * workableHoursDay));
}
@Test
public void theRelatedResourcesCanBeRetrieved() {
givenTaskWithStartAndEnd(toInterval(new LocalDate(2006, 10, 5), Period
.days(4)));
givenTaskWithStartAndEnd(toInterval(new LocalDate(2006, 10, 5), Period.days(4)));
givenGenericResourceAllocationForTask(task);
givenWorkersWithoutLoadAndWithoutCalendar();
List<Resource> resourcesGiven = Arrays.<Resource> asList(worker1,
worker2);
genericResourceAllocation.forResources(resourcesGiven)
.allocate(ResourcesPerDay.amount(1));
List<Resource> resourcesGiven = Arrays.<Resource> asList(worker1, worker2);
genericResourceAllocation.forResources(resourcesGiven).allocate(ResourcesPerDay.amount(1));
assertThat(asSet(genericResourceAllocation.getAssociatedResources()),
equalTo(asSet(genericResourceAllocation
.getAssociatedResources())));
equalTo(asSet(genericResourceAllocation.getAssociatedResources())));
}
private Set<Resource> asSet(Collection<Resource> associatedResources) {
@ -890,18 +818,18 @@ public class GenericResourceAllocationTest {
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(3, 12, 1);
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(1));
final int hoursOnSubinterval = 3;
int daysSubinterval = 2;
genericResourceAllocation.withPreviousAssociatedResources().onIntervalWithinTask(
start,
start.plusDays(daysSubinterval)).allocateHours(
hoursOnSubinterval);
assertThat(genericResourceAllocation.getAssignedHours(),
equalTo(hoursOnSubinterval + (days - daysSubinterval)
* workableHoursDay));
equalTo(hoursOnSubinterval + (days - daysSubinterval) * workableHoursDay));
}
@Test
@ -913,8 +841,7 @@ public class GenericResourceAllocationTest {
givenTaskWithStartAndEnd(toInterval(start, Period.days(days)));
givenGenericResourceAllocationForTask(task);
genericResourceAllocation.withPreviousAssociatedResources().allocate(
ResourcesPerDay.amount(1));
genericResourceAllocation.withPreviousAssociatedResources().allocate(ResourcesPerDay.amount(1));
assertThat(genericResourceAllocation.getAssignedHours(), equalTo(0));
}
@ -929,16 +856,11 @@ public class GenericResourceAllocationTest {
givenGenericResourceAllocationForTask(task);
givenWorkersWithLoads(8, 8, 8);
genericResourceAllocation.forResources(workers).allocate(
ResourcesPerDay.amount(3));
ResourcesPerDay original = genericResourceAllocation
.getResourcesPerDay();
genericResourceAllocation.forResources(workers).onIntervalWithinTask(start,
start.plusDays(2)).allocateHours(60);
ResourcesPerDay current = genericResourceAllocation
.getResourcesPerDay();
assertTrue(current.getAmount()
.compareTo(original.getAmount()) > 0);
genericResourceAllocation.forResources(workers).allocate(ResourcesPerDay.amount(3));
ResourcesPerDay original = genericResourceAllocation.getResourcesPerDay();
genericResourceAllocation.forResources(workers).onIntervalWithinTask(start, start.plusDays(2)).allocateHours(60);
ResourcesPerDay current = genericResourceAllocation.getResourcesPerDay();
assertTrue(current.getAmount().compareTo(original.getAmount()) > 0);
}
}

View file

@ -69,24 +69,19 @@ import org.libreplan.business.workingday.ResourcesPerDay;
public class SpecificResourceAllocationTest {
public static IntraDayDate date(int year, int monthOfYear, int dayOfMonth) {
return IntraDayDate.startOfDay(new LocalDate(year, monthOfYear,
dayOfMonth));
return IntraDayDate.startOfDay(new LocalDate(year, monthOfYear, dayOfMonth));
}
public static IntraDayDate plusDays(IntraDayDate date, int days) {
return IntraDayDate.create(date.getDate().plusDays(days),
date.getEffortDuration());
return IntraDayDate.create(date.getDate().plusDays(days), date.getEffortDuration());
}
public static IntraDayDate minusDays(IntraDayDate date, int days) {
return IntraDayDate.create(date.getDate().minusDays(days),
date.getEffortDuration());
return IntraDayDate.create(date.getDate().minusDays(days), date.getEffortDuration());
}
public static IntraDayDate plusDaysAndEffort(IntraDayDate date, int days,
EffortDuration effort) {
return IntraDayDate.create(date.getDate().plusDays(days), date
.getEffortDuration().plus(effort));
public static IntraDayDate plusDaysAndEffort(IntraDayDate date, int days, EffortDuration effort) {
return IntraDayDate.create(date.getDate().plusDays(days), date.getEffortDuration().plus(effort));
}
private BaseCalendar baseCalendar;
@ -109,92 +104,79 @@ public class SpecificResourceAllocationTest {
expect(workerCalendar.getCapacityOn(isA(PartialDay.class)))
.andReturn(EffortDuration.hours(hours)).anyTimes();
IAnswer<? extends EffortDuration> asDurationAnswer = asDurationOnAnswer(hours(hours));
expect(
workerCalendar.asDurationOn(isA(PartialDay.class),
isA(ResourcesPerDay.class)))
expect(workerCalendar.asDurationOn(isA(PartialDay.class), isA(ResourcesPerDay.class)))
.andAnswer(asDurationAnswer).anyTimes();
expect(workerCalendar.getCapacityWithOvertime(isA(LocalDate.class)))
.andReturn(
Capacity.create(hours(hours))
.overAssignableWithoutLimit()).anyTimes();
expect(workerCalendar.getAvailability()).andReturn(
AvailabilityTimeLine.allValid()).anyTimes();
.andReturn(Capacity.create(hours(hours)).overAssignableWithoutLimit()).anyTimes();
expect(workerCalendar.getAvailability()).andReturn(AvailabilityTimeLine.allValid()).anyTimes();
replay(workerCalendar);
return workerCalendar;
}
private static IAnswer<? extends EffortDuration> asDurationOnAnswer(
final EffortDuration duration) {
private static IAnswer<? extends EffortDuration> asDurationOnAnswer(final EffortDuration duration) {
return new IAnswer<EffortDuration>() {
@Override
public EffortDuration answer() throws Throwable {
ResourcesPerDay perDay = (ResourcesPerDay) EasyMock
.getCurrentArguments()[1];
ResourcesPerDay perDay = (ResourcesPerDay) EasyMock.getCurrentArguments()[1];
return perDay.asDurationGivenWorkingDayOf(duration);
}
};
}
private void givenResourceCalendar(final Capacity defaultAnswer,
final Map<LocalDate, Capacity> answersForDates) {
private void givenResourceCalendar(final Capacity defaultAnswer, final Map<LocalDate, Capacity> answersForDates) {
this.calendar = createNiceMock(ResourceCalendar.class);
expect(this.calendar.getCapacityOn(isA(PartialDay.class)))
.andAnswer(new IAnswer<EffortDuration>() {
expect(this.calendar.getCapacityOn(isA(PartialDay.class))).andAnswer(new IAnswer<EffortDuration>() {
@Override
public EffortDuration answer() throws Throwable {
PartialDay day = (PartialDay) EasyMock
.getCurrentArguments()[0];
PartialDay day = (PartialDay) EasyMock.getCurrentArguments()[0];
LocalDate date = day.getDate();
if ( answersForDates.containsKey(date) ) {
return day.limitWorkingDay(answersForDates
.get(date).getStandardEffort());
return day.limitWorkingDay(answersForDates.get(date).getStandardEffort());
}
return day.limitWorkingDay(defaultAnswer
.getStandardEffort());
return day.limitWorkingDay(defaultAnswer.getStandardEffort());
}
}).anyTimes();
expect(this.calendar.getCapacityWithOvertime(isA(LocalDate.class)))
.andAnswer(new IAnswer<Capacity>() {
expect(this.calendar.getCapacityWithOvertime(isA(LocalDate.class))).andAnswer(new IAnswer<Capacity>() {
@Override
public Capacity answer() throws Throwable {
LocalDate date = (LocalDate) EasyMock
.getCurrentArguments()[0];
LocalDate date = (LocalDate) EasyMock.getCurrentArguments()[0];
if ( answersForDates.containsKey(date) ) {
return answersForDates.get(date);
}
return defaultAnswer;
}
}).anyTimes();
final IAnswer<EffortDuration> effortAnswer = new IAnswer<EffortDuration>() {
@Override
public EffortDuration answer() throws Throwable {
PartialDay day = (PartialDay) EasyMock
.getCurrentArguments()[0];
ResourcesPerDay resourcesPerDay = (ResourcesPerDay) EasyMock
.getCurrentArguments()[1];
PartialDay day = (PartialDay) EasyMock.getCurrentArguments()[0];
ResourcesPerDay resourcesPerDay = (ResourcesPerDay) EasyMock.getCurrentArguments()[1];
LocalDate date = day.getDate();
Capacity capacity = answersForDates.containsKey(date) ? answersForDates
.get(date) : defaultAnswer;
Capacity capacity = answersForDates.containsKey(date) ? answersForDates.get(date) : defaultAnswer;
EffortDuration oneResourcePerDayWorkingDuration = day.limitWorkingDay(capacity.getStandardEffort());
EffortDuration amountRequestedDuration =
resourcesPerDay.asDurationGivenWorkingDayOf(oneResourcePerDayWorkingDuration);
EffortDuration oneResourcePerDayWorkingDuration = day
.limitWorkingDay(capacity.getStandardEffort());
EffortDuration amountRequestedDuration = resourcesPerDay
.asDurationGivenWorkingDayOf(oneResourcePerDayWorkingDuration);
return capacity.limitDuration(amountRequestedDuration);
}
};
expect(
this.calendar.asDurationOn(isA(PartialDay.class),
isA(ResourcesPerDay.class))).andAnswer(effortAnswer)
.anyTimes();
expect(this.calendar.getAvailability()).andReturn(
AvailabilityTimeLine.allValid()).anyTimes();
expect(this.calendar.asDurationOn(isA(PartialDay.class), isA(ResourcesPerDay.class)))
.andAnswer(effortAnswer).anyTimes();
expect(this.calendar.getAvailability()).andReturn(AvailabilityTimeLine.allValid()).anyTimes();
replay(this.calendar);
}
@ -207,18 +189,15 @@ public class SpecificResourceAllocationTest {
private void givenTask(IntraDayDate start, IntraDayDate end) {
task = createNiceMock(Task.class);
expect(task.getCalendar()).andReturn(baseCalendar).anyTimes();
expect(task.getStartDate()).andReturn(
start.toDateTimeAtStartOfDay().toDate()).anyTimes();
expect(task.getStartDate()).andReturn(start.toDateTimeAtStartOfDay().toDate()).anyTimes();
expect(task.getIntraDayStartDate()).andReturn(start).anyTimes();
expect(task.getEndDate()).andReturn(
end.toDateTimeAtStartOfDay().toDate()).anyTimes();
expect(task.getEndDate()).andReturn(end.toDateTimeAtStartOfDay().toDate()).anyTimes();
expect(task.getIntraDayEndDate()).andReturn(end).anyTimes();
expect(task.getFirstDayNotConsolidated()).andReturn(start).anyTimes();
replay(task);
}
private void givenSpecificResourceAllocation(IntraDayDate start,
IntraDayDate end) {
private void givenSpecificResourceAllocation(IntraDayDate start, IntraDayDate end) {
givenWorker();
givenTask(start, end);
specificResourceAllocation = SpecificResourceAllocation.create(task);

View file

@ -86,8 +86,7 @@ public class TaskElementTest {
private Dependency exampleDependency;
public TaskElementTest() {
this.exampleDependency = Dependency.create(new Task(), new Task(),
Type.END_START);
this.exampleDependency = Dependency.create(new Task(), new Task(), Type.END_START);
}
@Test
@ -120,8 +119,7 @@ public class TaskElementTest {
}
private static Date toStartOfDay(Date date) {
return LocalDate.fromDateFields(date)
.toDateTimeAtStartOfDay().toDate();
return LocalDate.fromDateFields(date).toDateTimeAtStartOfDay().toDate();
}
@Test
@ -132,45 +130,38 @@ public class TaskElementTest {
Type type = Type.START_END;
Dependency.create(origin, destination, type);
assertThat(origin.getDependenciesWithThisOrigin().size(), equalTo(1));
assertThat(destination.getDependenciesWithThisDestination().size(),
equalTo(1));
assertThat(destination.getDependenciesWithThisDestination().size(), equalTo(1));
origin.removeDependencyWithDestination(destination, type);
assertThat(origin.getDependenciesWithThisOrigin().size(), equalTo(0));
assertThat(destination.getDependenciesWithThisDestination().size(),
equalTo(0));
assertThat(destination.getDependenciesWithThisDestination().size(), equalTo(0));
}
private void addDependenciesForChecking(TaskElement taskBeingTransformed,
TaskElement sourceDependencyTask,
private void addDependenciesForChecking(TaskElement taskBeingTransformed, TaskElement sourceDependencyTask,
TaskElement destinationDependencyTask) {
Dependency.create(sourceDependencyTask, taskBeingTransformed,
Type.END_START);
Dependency.create(taskBeingTransformed, destinationDependencyTask,
Type.END_START);
Dependency.create(sourceDependencyTask, taskBeingTransformed, Type.END_START);
Dependency.create(taskBeingTransformed, destinationDependencyTask, Type.END_START);
}
public void detachRemovesDependenciesFromRelatedTasks() {
Task taskToDetach = (Task) TaskTest.createValidTask();
Task sourceDependencyTask = (Task) TaskTest.createValidTask();
Task destinationDependencyTask = (Task) TaskTest.createValidTask();
Task taskToDetach = TaskTest.createValidTask();
Task sourceDependencyTask = TaskTest.createValidTask();
Task destinationDependencyTask = TaskTest.createValidTask();
taskToDetach.setName("prueba");
taskToDetach.setNotes("blabla");
taskToDetach.setStartDate(new Date());
addDependenciesForChecking(taskToDetach, sourceDependencyTask,
destinationDependencyTask);
addDependenciesForChecking(taskToDetach, sourceDependencyTask, destinationDependencyTask);
taskToDetach.detach();
assertThat(sourceDependencyTask.getDependenciesWithThisOrigin().size(),
equalTo(0));
assertThat(destinationDependencyTask
.getDependenciesWithThisDestination().size(), equalTo(0));
assertThat(sourceDependencyTask.getDependenciesWithThisOrigin().size(), equalTo(0));
assertThat(destinationDependencyTask.getDependenciesWithThisDestination().size(), equalTo(0));
}
@Test
@Transactional
public void detachRemovesTaskFromParent() {
TaskGroup parent = TaskGroupTest.createValidTaskGroup();
Task child = (Task) TaskTest.createValidTask();
Task anotherChild = (Task) TaskTest.createValidTask();
Task child = TaskTest.createValidTask();
Task anotherChild = TaskTest.createValidTask();
parent.addTaskElement(child);
parent.addTaskElement(anotherChild);
child.detach();
@ -201,12 +192,10 @@ public class TaskElementTest {
if ( hoursGroups.isEmpty() ) {
hoursGroups = Collections.singletonList(createHoursGroup(100));
}
return TaskSource.create(mockSchedulingDataForVersion(orderLine),
hoursGroups);
return TaskSource.create(mockSchedulingDataForVersion(orderLine), hoursGroups);
}
public static SchedulingDataForVersion mockSchedulingDataForVersion(
OrderElement orderElement) {
public static SchedulingDataForVersion mockSchedulingDataForVersion(OrderElement orderElement) {
SchedulingDataForVersion result = createNiceMock(SchedulingDataForVersion.class);
TaskSource taskSource = createNiceMock(TaskSource.class);
expect(result.getOrderElement()).andReturn(orderElement).anyTimes();
@ -233,8 +222,7 @@ public class TaskElementTest {
addOrderTo(orderLine);
TaskSource taskSource = asTaskSource(orderLine);
Task task = Task.createTask(taskSource);
assertThat(task.getPositionConstraint(),
isOfType(PositionConstraintType.AS_SOON_AS_POSSIBLE));
assertThat(task.getPositionConstraint(), isOfType(PositionConstraintType.AS_SOON_AS_POSSIBLE));
}
private void addOrderTo(OrderElement orderElement) {
@ -271,12 +259,10 @@ public class TaskElementTest {
order.setInitDate(initDate);
TaskSource taskSource = asTaskSource(orderLine);
Task task = Task.createTask(taskSource);
assertThat(task.getPositionConstraint(),
isOfType(PositionConstraintType.AS_SOON_AS_POSSIBLE));
assertThat(task.getPositionConstraint(), isOfType(PositionConstraintType.AS_SOON_AS_POSSIBLE));
}
private static Matcher<TaskPositionConstraint> isOfType(
final PositionConstraintType type) {
private static Matcher<TaskPositionConstraint> isOfType(final PositionConstraintType type) {
return new BaseMatcher<TaskPositionConstraint>() {
@Override
@ -290,14 +276,12 @@ public class TaskElementTest {
@Override
public void describeTo(Description description) {
description.appendText("the start constraint must be of type "
+ type);
description.appendText("the start constraint must be of type " + type);
}
};
}
private static Matcher<TaskPositionConstraint> hasValue(
final LocalDate value) {
private static Matcher<TaskPositionConstraint> hasValue(final LocalDate value) {
return new BaseMatcher<TaskPositionConstraint>() {
@Override
@ -307,18 +291,15 @@ public class TaskElementTest {
LocalDate constraintDate = startConstraint
.getConstraintDate().toDateTimeAtStartOfDay()
.toLocalDate();
boolean bothNotNull = value != null
&& constraintDate != null;
return value == constraintDate || bothNotNull
&& constraintDate.equals(value);
boolean bothNotNull = value != null && constraintDate != null;
return value == constraintDate || bothNotNull && constraintDate.equals(value);
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("the start constraint must have date "
+ value);
description.appendText("the start constraint must have date " + value);
}
};
}

View file

@ -18,13 +18,10 @@ public class DistributorTest {
@Test
public void theEffortIsDistributedEvenly() {
Distributor distributor = Distributor.among(Capacity.create(hours(8)),
Capacity.create(hours(8)));
Distributor distributor = Distributor.among(Capacity.create(hours(8)), Capacity.create(hours(8)));
assertThat(distributor.distribute(hours(16)),
hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(8)),
hasEfforts(hours(4), hours(4)));
assertThat(distributor.distribute(hours(16)), hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(8)), hasEfforts(hours(4), hours(4)));
}
@Test
@ -33,8 +30,7 @@ public class DistributorTest {
.notOverAssignableWithoutLimit(), Capacity.create(hours(8))
.notOverAssignableWithoutLimit());
assertThat(distributor.distribute(hours(18)),
hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(18)), hasEfforts(hours(8), hours(8)));
}
@Test
@ -43,13 +39,10 @@ public class DistributorTest {
.notOverAssignableWithoutLimit(), Capacity.create(hours(8))
.overAssignableWithoutLimit());
assertThat(distributor.distribute(hours(14)),
hasEfforts(hours(7), hours(7)));
assertThat(distributor.distribute(hours(16)),
hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(14)), hasEfforts(hours(7), hours(7)));
assertThat(distributor.distribute(hours(16)), hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(18)),
hasEfforts(hours(8), hours(10)));
assertThat(distributor.distribute(hours(18)), hasEfforts(hours(8), hours(10)));
}
@Test
@ -58,25 +51,19 @@ public class DistributorTest {
.withAllowedExtraEffort(hours(2)), Capacity.create(hours(8))
.notOverAssignableWithoutLimit());
assertThat(distributor.distribute(hours(16)),
hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(17)),
hasEfforts(hours(9), hours(8)));
assertThat(distributor.distribute(hours(18)),
hasEfforts(hours(10), hours(8)));
assertThat(distributor.distribute(hours(19)),
hasEfforts(hours(10), hours(8)));
assertThat(distributor.distribute(hours(16)), hasEfforts(hours(8), hours(8)));
assertThat(distributor.distribute(hours(17)), hasEfforts(hours(9), hours(8)));
assertThat(distributor.distribute(hours(18)), hasEfforts(hours(10), hours(8)));
assertThat(distributor.distribute(hours(19)), hasEfforts(hours(10), hours(8)));
}
@Test
public void ifNoCapacityItReturnsZeroHours() {
Distributor distributor = Distributor.among(Capacity.create(hours(0))
.notOverAssignableWithoutLimit());
Distributor distributor = Distributor.among(Capacity.create(hours(0)).notOverAssignableWithoutLimit());
assertThat(distributor.distribute(hours(4)), hasEfforts(hours(0)));
}
private Matcher<List<EffortDuration>> hasEfforts(
final EffortDuration... efforts) {
private Matcher<List<EffortDuration>> hasEfforts(final EffortDuration... efforts) {
return new BaseMatcher<List<EffortDuration>>() {
@Override

View file

@ -29,11 +29,11 @@ package org.libreplan.web;
*/
public class WebappGlobalNames {
private WebappGlobalNames() {
}
private WebappGlobalNames() {}
public final static String WEBAPP_SPRING_CONFIG_FILE = "classpath:/libreplan-webapp-spring-config.xml";
public final static String WEBAPP_SPRING_SECURITY_CONFIG_FILE = "classpath:/libreplan-webapp-spring-security-config.xml";
public final static String WEBAPP_SPRING_SECURITY_CONFIG_FILE =
"classpath:/libreplan-webapp-spring-security-config.xml";
}

View file

@ -67,8 +67,7 @@ import org.springframework.transaction.annotation.Transactional;
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Qualifier("main")
@OnConcurrentModification(goToPage = "/calendars/calendars.zul")
public class BaseCalendarModel extends IntegrationEntityModel implements
IBaseCalendarModel {
public class BaseCalendarModel extends IntegrationEntityModel implements IBaseCalendarModel {
/**
* Conversation state

View file

@ -159,8 +159,7 @@ public interface IBaseCalendarModel extends IIntegrationEntityModel {
CalendarExceptionType getCalendarExceptionType(LocalDate date);
void updateException(CalendarExceptionType type, LocalDate startDate,
LocalDate endDate, Capacity capacity);
void updateException(CalendarExceptionType type, LocalDate startDate, LocalDate endDate, Capacity capacity);
void removeCalendarData(CalendarData calendarData);
@ -176,11 +175,9 @@ public interface IBaseCalendarModel extends IIntegrationEntityModel {
void createCalendarAvailability();
void setStartDate(CalendarAvailability calendarAvailability,
LocalDate startDate) throws IllegalArgumentException;
void setStartDate(CalendarAvailability calendarAvailability, LocalDate startDate) throws IllegalArgumentException;
void setEndDate(CalendarAvailability calendarAvailability, LocalDate endDate)
throws IllegalArgumentException;
void setEndDate(CalendarAvailability calendarAvailability, LocalDate endDate) throws IllegalArgumentException;
/*
* Final conversation steps
@ -212,11 +209,9 @@ public interface IBaseCalendarModel extends IIntegrationEntityModel {
Date getCurrentExpiringDate();
void checkChangeExpiringDate(CalendarData version, Date date)
throws ValidationException;
void checkChangeExpiringDate(CalendarData version, Date date) throws ValidationException;
void checkAndChangeStartDate(CalendarData version, Date date)
throws ValidationException;
void checkAndChangeStartDate(CalendarData version, Date date) throws ValidationException;
boolean isOwnExceptionDay();

View file

@ -41,8 +41,7 @@ import org.springframework.transaction.annotation.Transactional;
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Qualifier("subclass")
public class ResourceCalendarModel extends BaseCalendarModel implements
IBaseCalendarModel {
public class ResourceCalendarModel extends BaseCalendarModel implements IBaseCalendarModel {
@Override
public void initCreate() {

View file

@ -255,14 +255,12 @@ public class ConfigurationModel implements IConfigurationModel {
public void removeEntitySequences(final List<EntitySequence> sequences) {
// first one is necessary to remove the deleted sequences.
List<EntitySequence> toRemove = entitySequenceDAO
.findEntitySquencesNotIn(sequences);
List<EntitySequence> toRemove = entitySequenceDAO.findEntitySquencesNotIn(sequences);
for (final EntitySequence entitySequence : toRemove) {
try {
entitySequenceDAO.remove(entitySequence);
} catch (InstanceNotFoundException e) {
throw new ValidationException(
_("Some sequences to be removed do not exist"));
throw new ValidationException(_("Some sequences to be removed do not exist"));
} catch (IllegalArgumentException e) {
throw new ValidationException(e.getMessage());
}

View file

@ -42,29 +42,30 @@ import org.springframework.dao.OptimisticLockingFailureException;
@Order(0)
public class ConcurrentModificationHandling {
public static <T> T addHandling(final String goToPage,
Class<T> interfaceKlass, T toBeWraped) {
public static <T> T addHandling(final String goToPage, Class<T> interfaceKlass, T toBeWraped) {
Class<?>[] classesToProxy = { interfaceKlass };
Object result = Proxy.newProxyInstance(interfaceKlass.getClassLoader(),
classesToProxy, handler(toBeWraped, goToPage));
Object result =
Proxy.newProxyInstance(interfaceKlass.getClassLoader(), classesToProxy, handler(toBeWraped, goToPage));
return interfaceKlass.cast(result);
}
private static InvocationHandler handler(final Object toBeWraped,
final String goToPage) {
private static InvocationHandler handler(final Object toBeWraped, final String goToPage) {
return new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(toBeWraped, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if ( cause instanceof OptimisticLockingFailureException ) {
OptimisticLockingFailureException optimisticLockingFailureException = (OptimisticLockingFailureException) cause;
ConcurrentModificationController.showException(
optimisticLockingFailureException, goToPage);
OptimisticLockingFailureException optimisticLockingFailureException =
(OptimisticLockingFailureException) cause;
ConcurrentModificationController.showException(optimisticLockingFailureException, goToPage);
}
throw cause;
}
@ -77,8 +78,7 @@ public class ConcurrentModificationHandling {
@SuppressWarnings("unused")
@Pointcut("@within(onConcurrentModification))")
private void methodWithinConcurrentModificationMarkedType(
OnConcurrentModification onConcurrentModification) {
private void methodWithinConcurrentModificationMarkedType(OnConcurrentModification onConcurrentModification) {
}
/**
@ -92,15 +92,14 @@ public class ConcurrentModificationHandling {
* the annotation applied to object's type
* @return the object that would be originally returned
*/
@Around("methodWithinConcurrentModificationMarkedType(onConcurrentModification)"
+ " && execution(public * * (..))")
@Around("methodWithinConcurrentModificationMarkedType(onConcurrentModification)" + " && execution(public * * (..))")
public Object whenConcurrentModification(ProceedingJoinPoint jointPoint,
OnConcurrentModification onConcurrentModification) throws Throwable {
try {
return jointPoint.proceed(jointPoint.getArgs());
} catch (OptimisticLockingFailureException e) {
ConcurrentModificationController.showException(e,
onConcurrentModification.goToPage());
ConcurrentModificationController.showException(e, onConcurrentModification.goToPage());
throw e;
}
}

View file

@ -63,28 +63,24 @@ public class CostStatusModel implements ICostStatusModel {
}
@Override
public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost,
BigDecimal actualCost) {
public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost, BigDecimal actualCost) {
return earnedValueCalculator.getCostPerformanceIndex(budgetedCost,
actualCost);
}
@Override
public BigDecimal getCostVariance(BigDecimal budgetedCost,
BigDecimal actualCost) {
public BigDecimal getCostVariance(BigDecimal budgetedCost, BigDecimal actualCost) {
return earnedValueCalculator.getCostVariance(budgetedCost, actualCost);
}
@Override
public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion,
BigDecimal costPerformanceIndex) {
public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion, BigDecimal costPerformanceIndex) {
return earnedValueCalculator.getEstimateAtCompletion(
budgetAtCompletion, costPerformanceIndex);
}
@Override
public BigDecimal getVarianceAtCompletion(BigDecimal budgetAtCompletion,
BigDecimal estimateAtCompletion) {
public BigDecimal getVarianceAtCompletion(BigDecimal budgetAtCompletion, BigDecimal estimateAtCompletion) {
return budgetAtCompletion.subtract(estimateAtCompletion);
}
@ -100,15 +96,12 @@ public class CostStatusModel implements ICostStatusModel {
@Override
public BigDecimal getBudgetedCostWorkPerformedAt(LocalDate date) {
return earnedValueCalculator
.getBudgetedCostWorkPerformedAt(order, date);
return earnedValueCalculator.getBudgetedCostWorkPerformedAt(order, date);
}
@Override
public BigDecimal getEstimateToComplete(BigDecimal estimateAtCompletion,
BigDecimal actualCost) {
return earnedValueCalculator.getEstimateToComplete(
estimateAtCompletion, actualCost);
public BigDecimal getEstimateToComplete(BigDecimal estimateAtCompletion, BigDecimal actualCost) {
return earnedValueCalculator.getEstimateToComplete(estimateAtCompletion, actualCost);
}
}

View file

@ -278,14 +278,15 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
public void initEdit(Order orderToEdit, Desktop desktop) {
Validate.notNull(orderToEdit);
loadNeededDataForConversation();
this.planningState = planningStateCreator.retrieveOrCreate(desktop,
orderToEdit, new IActionsOnRetrieval() {
this.planningState = planningStateCreator.retrieveOrCreate(desktop, orderToEdit, new IActionsOnRetrieval() {
@Override
public void onRetrieval(PlanningState planningState) {
planningState.reattach();
}
});
Order order = this.planningState.getOrder();
this.orderElementTreeModel = new OrderElementTreeModel(order);
forceLoadAdvanceAssignmentsAndMeasurements(order);
@ -413,8 +414,7 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
}
private void initializeOrder() {
this.orderElementTreeModel = new OrderElementTreeModel(
planningState.getOrder());
this.orderElementTreeModel = new OrderElementTreeModel(planningState.getOrder());
}
private void initializeCode() {
@ -430,14 +430,13 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
@Transactional(readOnly = true)
public void prepareCreationFrom(OrderTemplate template, Desktop desktop) {
loadNeededDataForConversation();
Order newOrder = createOrderFrom((OrderTemplate) templateDAO
.findExistingEntity(template.getId()));
Order newOrder = createOrderFrom((OrderTemplate) templateDAO.findExistingEntity(template.getId()));
newOrder.setCode(getOrder().getCode());
newOrder.setCodeAutogenerated(true);
newOrder.setName(getOrder().getName());
newOrder.setCustomer(((Order) getOrder()).getCustomer());
newOrder.setCustomer(getOrder().getCustomer());
newOrder.setCalendar(getCalendar());
newOrder.setInitDate(getOrder().getInitDate());
@ -454,19 +453,16 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
return template.createOrder(scenarioManager.getCurrent());
}
private OrderElement createOrderElementFrom(OrderLineGroup parent,
OrderElementTemplate template) {
private OrderElement createOrderElementFrom(OrderLineGroup parent, OrderElementTemplate template) {
Validate.notNull(parent);
return template.createElement(parent);
}
@Override
@Transactional(readOnly = true)
public OrderElement createFrom(OrderLineGroup parent,
OrderElementTemplate template) {
public OrderElement createFrom(OrderLineGroup parent, OrderElementTemplate template) {
reattachNeededDataForConversation();
OrderElement result = createOrderElementFrom(parent, templateDAO
.findExistingEntity(template.getId()));
OrderElement result = createOrderElementFrom(parent, templateDAO.findExistingEntity(template.getId()));
if ( isCodeAutogenerated() ) {
setAllCodeToNull(result);
}
@ -537,6 +533,7 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
private void removeVersions(Order order) {
Map<Long, OrderVersion> versionsRemovedById = new HashMap<Long, OrderVersion>();
List<Scenario> currentAndDerived = currentAndDerivedScenarios();
for (Scenario each : currentAndDerived) {
OrderVersion versionRemoved = order.disassociateFrom(each);
if ( versionRemoved != null ) {
@ -551,8 +548,7 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
}
}
private void removeOrderVersionAt(OrderVersion orderVersion,
Collection<? extends Scenario> currentAndDerived) {
private void removeOrderVersionAt(OrderVersion orderVersion, Collection<? extends Scenario> currentAndDerived) {
for (Scenario each : currentAndDerived) {
each.removeVersion(orderVersion);
}
@ -562,8 +558,7 @@ public class OrderModel extends IntegrationEntityModel implements IOrderModel {
List<Scenario> scenariosToBeDisassociatedFrom = new ArrayList<Scenario>();
Scenario currentScenario = scenarioManager.getCurrent();
scenariosToBeDisassociatedFrom.add(currentScenario);
scenariosToBeDisassociatedFrom.addAll(scenarioDAO
.getDerivedScenarios(currentScenario));
scenariosToBeDisassociatedFrom.addAll(scenarioDAO.getDerivedScenarios(currentScenario));
return scenariosToBeDisassociatedFrom;
}

View file

@ -65,8 +65,7 @@ import org.zkoss.zul.Window;
public class ProjectDetailsController extends GenericForwardComposer {
private static final Log LOG = LogFactory
.getLog(AdvanceConsolidationController.class);
private static final Log LOG = LogFactory.getLog(AdvanceConsolidationController.class);
private OrderCRUDController orderController;
@ -96,8 +95,8 @@ public class ProjectDetailsController extends GenericForwardComposer {
private OrderTemplate template;
public ProjectDetailsController() {
Window window = (Window) Executions.createComponents(
"/orders/_projectDetails.zul", null,
Window window = (Window) Executions.createComponents("/orders/_projectDetails.zul", null,
new HashMap<String, String>());
try {
doAfterCompose(window);
@ -113,13 +112,11 @@ public class ProjectDetailsController extends GenericForwardComposer {
window.setVariable("projectController", this, true);
}
public void showWindow(OrderCRUDController orderController,
MultipleTabsPlannerController tabs) {
public void showWindow(OrderCRUDController orderController, MultipleTabsPlannerController tabs) {
this.tabs = tabs;
this.orderController = orderController;
this.defaultCalendar = orderController.getOrder().getCalendar();
this.isCodeAutogeneratedInit = orderController.getOrder()
.isCodeAutogenerated();
this.isCodeAutogeneratedInit = orderController.getOrder().isCodeAutogenerated();
try {
Util.reloadBindings(window);
Util.createBindingsFor(gridProjectDetails);
@ -142,8 +139,7 @@ public class ProjectDetailsController extends GenericForwardComposer {
Desktop desktop = window.getDesktop();
IOrderModel orderModel = orderController.getOrderModel();
if ( bdProjectTemplate.getSelectedElement() != null ) {
OrderTemplate template = (OrderTemplate) bdProjectTemplate
.getSelectedElement();
OrderTemplate template = (OrderTemplate) bdProjectTemplate.getSelectedElement();
orderModel.prepareCreationFrom(template, desktop);
} else {
orderModel.initEdit(orderController.getOrder(), desktop);

View file

@ -53,8 +53,9 @@ import org.libreplan.business.workingday.EffortDuration.IEffortFrom;
public class AllocationRowsHandler {
public static AllocationRowsHandler create(Task task,
List<AllocationRow> initialAllocations, IWorkerFinder workerFinder) {
public static AllocationRowsHandler create(Task task, List<AllocationRow> initialAllocations,
IWorkerFinder workerFinder) {
return new AllocationRowsHandler(task, initialAllocations, workerFinder);
}
@ -256,20 +257,20 @@ public class AllocationRowsHandler {
createDerived();
AllocationResult result = createResult();
if ( AllocationModification.allFullfiled(AllocationModification
.ofType(EffortModification.class, modificationsDone)) ) {
return Flagged.justValue(result);
} else {
return Flagged.withFlags(result,
Warnings.SOME_GOALS_NOT_FULFILLED);
return Flagged.withFlags(result, Warnings.SOME_GOALS_NOT_FULFILLED);
}
}
return Flagged.justValue(createResult());
}
private AllocationResult createResult() {
return AllocationResult.create(task,
calculatedValue, currentRows, getWorkableDaysIfApplyable());
return AllocationResult.create(task, calculatedValue, currentRows, getWorkableDaysIfApplyable());
}
private List<? extends AllocationModification> doSuitableAllocation() {
@ -278,30 +279,34 @@ public class AllocationRowsHandler {
case NUMBER_OF_HOURS:
allocationModifications = calculateNumberOfHoursAllocation();
break;
case END_DATE:
allocationModifications = calculateEndDateOrStartDateAllocation();
break;
case RESOURCES_PER_DAY:
allocationModifications = calculateResourcesPerDayAllocation();
break;
default:
throw new RuntimeException("cant handle: " + calculatedValue);
}
AssignmentFunction.applyAssignmentFunctionsIfAny(AllocationModification
.getBeingModified(allocationModifications));
AssignmentFunction
.applyAssignmentFunctionsIfAny(AllocationModification.getBeingModified(allocationModifications));
return allocationModifications;
}
private List<ResourcesPerDayModification> calculateNumberOfHoursAllocation() {
List<ResourcesPerDayModification> allocations = AllocationRow
.createAndAssociate(task, currentRows, requestedToRemove);
List<ResourcesPerDayModification> allocations =
AllocationRow.createAndAssociate(task, currentRows, requestedToRemove);
if ( isForwardsAllocation() ) {
ResourceAllocation.allocating(allocations).allocateUntil(
formBinder.getAllocationEnd());
ResourceAllocation.allocating(allocations).allocateUntil(formBinder.getAllocationEnd());
} else {
ResourceAllocation.allocating(allocations).allocateFromEndUntil(
formBinder.getAllocationStart());
ResourceAllocation.allocating(allocations).allocateFromEndUntil(formBinder.getAllocationStart());
}
return allocations;
}
@ -337,48 +342,45 @@ public class AllocationRowsHandler {
}
private List<EffortModification> calculateResourcesPerDayAllocation() {
List<EffortModification> hours = AllocationRow
.createHoursModificationsAndAssociate(task, currentRows,
requestedToRemove);
List<EffortModification> hours =
AllocationRow.createHoursModificationsAndAssociate(task, currentRows, requestedToRemove);
if ( isForwardsAllocation() ) {
ResourceAllocation.allocatingHours(hours).allocateUntil(
formBinder.getAllocationEnd());
ResourceAllocation.allocatingHours(hours).allocateUntil(formBinder.getAllocationEnd());
} else {
ResourceAllocation.allocatingHours(hours).allocateFromEndUntil(
formBinder.getAllocationStart());
ResourceAllocation.allocatingHours(hours).allocateFromEndUntil(formBinder.getAllocationStart());
}
return hours;
}
private Integer getWorkableDaysIfApplyable() {
switch (calculatedValue) {
case NUMBER_OF_HOURS:
case RESOURCES_PER_DAY:
return formBinder.getWorkableDays();
case END_DATE:
return null;
default:
throw new RuntimeException("unexpected calculatedValue: "
+ calculatedValue);
throw new RuntimeException("unexpected calculatedValue: " + calculatedValue);
}
}
private void createDerived() {
List<ResourceAllocation<?>> lastFrom = AllocationRow
.getBeingModified(currentRows);
List<ResourceAllocation<?>> lastFrom = AllocationRow.getBeingModified(currentRows);
for (ResourceAllocation<?> each : lastFrom) {
each.createDerived(workersFinder);
}
}
public FormBinder createFormBinder(Scenario currentScenario,
IResourceAllocationModel resourceAllocationModel) {
public FormBinder createFormBinder(Scenario currentScenario, IResourceAllocationModel resourceAllocationModel) {
if ( formBinder != null ) {
throw new IllegalStateException(
"there is already a binder associated with this object");
throw new IllegalStateException("there is already a binder associated with this object");
}
formBinder = new FormBinder(currentScenario, this,
resourceAllocationModel);
formBinder = new FormBinder(currentScenario, this, resourceAllocationModel);
return formBinder;
}

View file

@ -187,18 +187,16 @@ public class FormBinder {
private Button advancedSearchButton;
public FormBinder(Scenario currentScenario,
AllocationRowsHandler allocationRowsHandler,
public FormBinder(Scenario currentScenario, AllocationRowsHandler allocationRowsHandler,
IResourceAllocationModel resourceAllocationModel) {
this.allocationRowsHandler = allocationRowsHandler;
this.resourceAllocationModel = resourceAllocationModel;
this.lastAllocation = this.allocationRowsHandler
.getInitialAllocation(currentScenario);
this.lastAllocation = this.allocationRowsHandler.getInitialAllocation(currentScenario);
this.aggregate = this.lastAllocation.getAggregate();
}
public void setAssignedEffortComponent(
EffortDurationBox assignedEffortComponent) {
public void setAssignedEffortComponent(EffortDurationBox assignedEffortComponent) {
this.effortInput = assignedEffortComponent;
this.effortInput.setConstraint(positiveValueRequired());
allHoursInputComponentDisabilityRule();
@ -268,16 +266,14 @@ public class FormBinder {
}
private void onChangeEnableApply(InputElement inputElement) {
Util.ensureUniqueListener(inputElement, Events.ON_CHANGE,
onChangeEnableApply);
Util.ensureUniqueListener(inputElement, Events.ON_CHANGE, onChangeEnableApply);
}
public void setWorkableDays(Intbox duration,
final TaskPropertiesController taskPropertiesController,
public void setWorkableDays(Intbox duration, final TaskPropertiesController taskPropertiesController,
final Label labelTaskStart, final Label labelTaskEnd) {
this.workableDaysAndDatesBinder = new WorkableDaysAndDatesBinder(
duration, labelTaskStart, labelTaskEnd,
taskPropertiesController);
this.workableDaysAndDatesBinder =
new WorkableDaysAndDatesBinder(duration, labelTaskStart, labelTaskEnd, taskPropertiesController);
}
class WorkableDaysAndDatesBinder {
@ -290,17 +286,15 @@ public class FormBinder {
private final TaskPropertiesController taskPropertiesController;
WorkableDaysAndDatesBinder(final Intbox taskWorkableDays,
final Label labelTaskStart, final Label labelTaskEnd,
WorkableDaysAndDatesBinder(final Intbox taskWorkableDays, final Label labelTaskStart, final Label labelTaskEnd,
final TaskPropertiesController taskPropertiesController) {
this.taskWorkableDays = taskWorkableDays;
this.labelTaskStart = labelTaskStart;
this.labelTaskEnd = labelTaskEnd;
this.taskPropertiesController = taskPropertiesController;
initializeDateAndDurationFieldsFromTaskOriginalValues();
final LocalDate firstPossibleDay = getTask()
.getFirstDayNotConsolidated().nextDayAtStart()
.asExclusiveEnd();
final LocalDate firstPossibleDay = getTask().getFirstDayNotConsolidated().nextDayAtStart().asExclusiveEnd();
Util.ensureUniqueListeners(taskWorkableDays, Events.ON_CHANGE,
new EventListener() {
@ -309,50 +303,46 @@ public class FormBinder {
Task task = getTask();
Integer workableDays = taskWorkableDays.getValue();
if ( allocationRowsHandler.isForwardsAllocation() ) {
IntraDayDate newEnd = ensureItIsAfterConsolidation(task
.calculateEndGivenWorkableDays(workableDays));
updateWorkableDaysIfNecessary(workableDays,
getTask().getIntraDayStartDate(),
newEnd);
taskPropertiesController
.updateTaskEndDate(newEnd.getDate());
showValueOfDateOn(labelTaskEnd,
newEnd.getDate());
IntraDayDate newEnd =
ensureItIsAfterConsolidation(task.calculateEndGivenWorkableDays(workableDays));
updateWorkableDaysIfNecessary(workableDays, getTask().getIntraDayStartDate(), newEnd);
taskPropertiesController.updateTaskEndDate(newEnd.getDate());
showValueOfDateOn(labelTaskEnd, newEnd.getDate());
} else {
IntraDayDate newStart = ensureItIsAfterConsolidation(task
.calculateStartGivenWorkableDays(workableDays));
updateWorkableDaysIfNecessary(workableDays,
newStart, task.getIntraDayEndDate());
taskPropertiesController
.updateTaskStartDate(newStart.getDate());
showValueOfDateOn(labelTaskStart,
newStart.getDate());
IntraDayDate newStart =
ensureItIsAfterConsolidation(task.calculateStartGivenWorkableDays(workableDays));
updateWorkableDaysIfNecessary(workableDays, newStart, task.getIntraDayEndDate());
taskPropertiesController.updateTaskStartDate(newStart.getDate());
showValueOfDateOn(labelTaskStart, newStart.getDate());
}
}
private void updateWorkableDaysIfNecessary(
int specifiedWorkableDays,
private void updateWorkableDaysIfNecessary(int specifiedWorkableDays,
IntraDayDate allocationStart,
IntraDayDate allocationEnd) {
Integer effectiveWorkableDays = getTask()
.getWorkableDaysFrom(
Integer effectiveWorkableDays = getTask().getWorkableDaysFrom(
allocationStart.getDate(),
allocationEnd.asExclusiveEnd());
if ( effectiveWorkableDays < specifiedWorkableDays ) {
Clients.response(new AuWrongValue(
taskWorkableDays,
_("The original workable days value {0} cannot be modified as it has consolidations",
specifiedWorkableDays)) );
taskWorkableDays
.setValue(effectiveWorkableDays);
taskWorkableDays.setValue(effectiveWorkableDays);
}
}
@SuppressWarnings("unchecked")
private IntraDayDate ensureItIsAfterConsolidation(
IntraDayDate newDate) {
private IntraDayDate ensureItIsAfterConsolidation(IntraDayDate newDate) {
if ( getTask().hasConsolidations() ) {
return Collections.max(Arrays.asList(newDate,
return Collections.max(
Arrays.asList(newDate,
IntraDayDate.startOfDay(firstPossibleDay)));
}
return newDate;
@ -363,9 +353,9 @@ public class FormBinder {
}
void applyDisabledRules() {
this.taskWorkableDays.setDisabled(allocationRowsHandler
.getCalculatedValue() == CalculatedValue.END_DATE
|| isAnyManual() || isTaskUpdatedFromTimesheets());
this.taskWorkableDays.setDisabled(allocationRowsHandler.getCalculatedValue() == CalculatedValue.END_DATE ||
isAnyManual() ||
isTaskUpdatedFromTimesheets());
}
private void initializeDateAndDurationFieldsFromTaskOriginalValues() {
@ -514,14 +504,15 @@ public class FormBinder {
}
public void doApply() {
AllocationResult allocationResult = resourceAllocationModel
.onAllocationContext(new IResourceAllocationContext<AllocationResult>() {
AllocationResult allocationResult =
resourceAllocationModel.onAllocationContext(new IResourceAllocationContext<AllocationResult>() {
@Override
public AllocationResult doInsideTransaction() {
return allocationRowsHandler.doAllocation().getValue();
}
});
allocationProduced(allocationResult);
TaskPropertiesController.allocationResult = allocationResult;
@ -537,8 +528,7 @@ public class FormBinder {
return true;
}
Flagged<AllocationResult, Warnings> result = resourceAllocationModel
.accept();
Flagged<AllocationResult, Warnings> result = resourceAllocationModel.accept();
// result can be null when editing milestones
if ( result != null && result.isFlagged() ) {
@ -565,8 +555,7 @@ public class FormBinder {
@SuppressWarnings("unchecked")
private void loadSclassRowSatisfied() {
try {
List<org.zkoss.zul.Row> rows = (List<org.zkoss.zul.Row>) allocationsGrid
.getRows().getChildren();
List<org.zkoss.zul.Row> rows = (List<org.zkoss.zul.Row>) allocationsGrid.getRows().getChildren();
for (org.zkoss.zul.Row row : rows) {
if ( row.getValue() instanceof AllocationRow ) {
if ( !((AllocationRow) row.getValue()).isSatisfied() ) {
@ -616,8 +605,7 @@ public class FormBinder {
FormBinder.this.applyButton.setDisabled(true);
}
};
Util.ensureUniqueListener(this.applyButton, Events.ON_CLICK,
applyButtonListener);
Util.ensureUniqueListener(this.applyButton, Events.ON_CLICK, applyButtonListener);
}
public EffortDuration getAssignedEffort() {
@ -669,20 +657,15 @@ public class FormBinder {
public void markNoResourcesMatchedByCriterions(ResourceEnum resourceType,
Collection<? extends Criterion> criterions) {
messagesForUser
.showMessage(
Level.ERROR,
messagesForUser.showMessage(Level.ERROR,
_("there are no resources for required criteria: {0}. So the generic allocation can't be added",
Criterion.getCaptionFor(resourceType,
criterions)));
Criterion.getCaptionFor(resourceType, criterions)));
}
public void markThereisAlreadyAssignmentWith(ResourceEnum resourceType,
Collection<? extends Criterion> criterions) {
messagesForUser.showMessage(
Level.ERROR,
_("already exists an allocation for criteria {0}",
Criterion.getCaptionFor(resourceType, criterions)));
messagesForUser.showMessage(Level.ERROR,
_("already exists an allocation for criteria {0}", Criterion.getCaptionFor(resourceType, criterions)));
}
public void markNoEmptyResourcesPerDay(List<AllocationRow> rows) {
@ -690,8 +673,7 @@ public class FormBinder {
final String message = _("resources per day cannot be empty or less than zero");
if ( !recommendedAllocation ) {
AllocationRow first = rows.get(0);
throw new WrongValueException(
first.getIntendedResourcesPerDayInput(), message);
throw new WrongValueException(first.getIntendedResourcesPerDayInput(), message);
} else {
throw new WrongValueException(allResourcesPerDay, message);
}
@ -707,19 +689,16 @@ public class FormBinder {
public void detach() {
if ( this.applyButton != null ) {
this.applyButton.removeEventListener(Events.ON_CLICK,
applyButtonListener);
this.applyButton.removeEventListener(Events.ON_CLICK, applyButtonListener);
}
for (InputElement inputElement : inputsAssociatedWithOnChangeEnableApply) {
inputElement.removeEventListener(Events.ON_CHANGE,
onChangeEnableApply);
inputElement.removeEventListener(Events.ON_CHANGE, onChangeEnableApply);
}
}
public void setRecommendedAllocation(Button recommendedAllocation) {
this.btnRecommendedAllocation = recommendedAllocation;
this.btnRecommendedAllocation.setDisabled(isAnyManual()
|| isTaskUpdatedFromTimesheets());
this.btnRecommendedAllocation.setDisabled(isAnyManual() || isTaskUpdatedFromTimesheets());
Util.ensureUniqueListener(recommendedAllocation, Events.ON_CLICK,
new EventListener() {
@Override
@ -740,19 +719,20 @@ public class FormBinder {
private void activatingRecommendedAllocation() {
allocationRowsHandler.removeAll();
ProportionalDistributor distributor = resourceAllocationModel
.addDefaultAllocations();
ProportionalDistributor distributor = resourceAllocationModel.addDefaultAllocations();
boolean recommendAllocationSuccessful = distributor != null;
if ( recommendAllocationSuccessful ) {
hoursDistributorForRecommendedAllocation = distributor;
resourcesPerDayDistributorForRecommendedAllocation = ResourcesPerDay
.distributor(hoursDistributorForRecommendedAllocation);
resourcesPerDayDistributorForRecommendedAllocation =
ResourcesPerDay.distributor(hoursDistributorForRecommendedAllocation);
this.recommendedAllocation = true;
disableIfNeededWorkerSearch();
applyDisabledRules();
effortInput.addEventListener(Events.ON_CHANGE, allHoursInputChange);
allResourcesPerDay.addEventListener(Events.ON_CHANGE,
allResourcesPerDayChange);
allResourcesPerDay.addEventListener(Events.ON_CHANGE, allResourcesPerDayChange);
resetStateForResourcesPerDayInputsWhenDoingRecommendedAllocation();
}
Util.reloadBindings(allocationsGrid);
@ -800,8 +780,7 @@ public class FormBinder {
private void deactivatingRecommendedAllocation() {
this.recommendedAllocation = false;
effortInput.removeEventListener(Events.ON_CHANGE, allHoursInputChange);
allResourcesPerDay.removeEventListener(Events.ON_CHANGE,
allResourcesPerDayChange);
allResourcesPerDay.removeEventListener(Events.ON_CHANGE, allResourcesPerDayChange);
applyDisabledRules();
disableIfNeededWorkerSearch();
}
@ -822,8 +801,7 @@ public class FormBinder {
this.advancedSearchButton.setDisabled(recommendedAllocation);
}
public void setNewAllocationSelectorCombo(
NewAllocationSelectorCombo newAllocationSelectorCombo) {
public void setNewAllocationSelectorCombo(NewAllocationSelectorCombo newAllocationSelectorCombo) {
this.newAllocationSelectorCombo = newAllocationSelectorCombo;
this.newAllocationSelectorCombo.setDisabled(recommendedAllocation);
}
@ -892,8 +870,7 @@ public class FormBinder {
return allTotalResourcesPerDay;
}
public void setAllConsolidatedResourcesPerDay(
Label allConsolidatedResourcesPerDay) {
public void setAllConsolidatedResourcesPerDay(Label allConsolidatedResourcesPerDay) {
this.allConsolidatedResourcesPerDay = allConsolidatedResourcesPerDay;
}
@ -904,16 +881,11 @@ public class FormBinder {
public void loadAggregatedCalculations() {
// Calculate aggregated values
if ( behaviour.allowMultipleSelection() ) {
allOriginalEffort.setValue(sumAllOriginalEffort(this.rows)
.toFormattedString());
allTotalEffort.setValue(sumAllTotalEffort(this.rows)
.toFormattedString());
allConsolidatedEffort.setValue(AllocationRow
.sumAllConsolidatedEffort(this.rows).toFormattedString());
allTotalResourcesPerDay.setValue(sumAllTotalResourcesPerDay()
.toString());
allConsolidatedResourcesPerDay
.setValue(sumAllConsolidatedResourcesPerDay().toString());
allOriginalEffort.setValue(sumAllOriginalEffort(this.rows).toFormattedString());
allTotalEffort.setValue(sumAllTotalEffort(this.rows).toFormattedString());
allConsolidatedEffort.setValue(AllocationRow.sumAllConsolidatedEffort(this.rows).toFormattedString());
allTotalResourcesPerDay.setValue(sumAllTotalResourcesPerDay().toString());
allConsolidatedResourcesPerDay.setValue(sumAllConsolidatedResourcesPerDay().toString());
}
}
@ -922,10 +894,8 @@ public class FormBinder {
}
public void cannotAllocateMoreThanOneResource(List<Resource> resources) {
messagesForUser.showMessage(
Level.ERROR,
_("{0} could not be allocated. "
+ "Cannot allocate more than one resource",
messagesForUser.showMessage(Level.ERROR,
_("{0} could not be allocated. " + "Cannot allocate more than one resource",
Resource.getCaptionFor(resources)));
}
@ -934,8 +904,7 @@ public class FormBinder {
}
public boolean isAnyNotFlat() {
for (AllocationRow allocationRow : allocationRowsHandler
.getCurrentRows()) {
for (AllocationRow allocationRow : allocationRowsHandler.getCurrentRows()) {
if ( allocationRow.isAssignmentFunctionNotFlat() ) {
return true;
}
@ -944,8 +913,7 @@ public class FormBinder {
}
public boolean isAnyManual() {
for (AllocationRow allocationRow : allocationRowsHandler
.getCurrentRows()) {
for (AllocationRow allocationRow : allocationRowsHandler.getCurrentRows()) {
if ( allocationRow.isAssignmentFunctionManual() ) {
return true;
}

View file

@ -53,18 +53,15 @@ public class ResourceAllocationCommand implements IResourceAllocationCommand {
}
@Override
public void doAction(IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement) {
public void doAction(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement) {
editTaskUtilities.reattach(taskElement);
if ( isApplicableTo(taskElement) ) {
Task task = (Task) taskElement;
if ( task.isSubcontracted() ) {
editTaskController.showEditFormSubcontract(context, task,
planningState);
editTaskController.showEditFormSubcontract(context, task, planningState);
} else {
editTaskController.showEditFormResourceAllocation(context,
task, planningState);
editTaskController.showEditFormResourceAllocation(context, task, planningState);
}
}
}
@ -75,8 +72,7 @@ public class ResourceAllocationCommand implements IResourceAllocationCommand {
}
@Override
public void initialize(EditTaskController editTaskController,
PlanningState planningState) {
public void initialize(EditTaskController editTaskController, PlanningState planningState) {
this.editTaskController = editTaskController;
this.planningState = planningState;
}

View file

@ -38,6 +38,7 @@ import org.libreplan.business.planner.entities.DerivedAllocation;
import org.libreplan.business.planner.entities.ResourceAllocation;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.business.resources.entities.ResourceEnum;
import org.libreplan.business.planner.entities.Task;
import org.libreplan.web.I18nHelper;
import org.libreplan.web.common.EffortDurationBox;
import org.libreplan.web.common.IMessagesForUser;
@ -93,8 +94,7 @@ import org.zkoss.zul.Window;
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ResourceAllocationController extends GenericForwardComposer {
private static final Log LOG = LogFactory
.getLog(ResourceAllocationController.class);
private static final Log LOG = LogFactory.getLog(ResourceAllocationController.class);
private IResourceAllocationModel resourceAllocationModel;
@ -177,18 +177,15 @@ public class ResourceAllocationController extends GenericForwardComposer {
* @param ganttTask
* @param planningState
*/
public void init(IContextWithPlannerTask<TaskElement> context,
org.libreplan.business.planner.entities.Task task,
PlanningState planningState, IMessagesForUser messagesForUser) {
public void init(IContextWithPlannerTask<TaskElement> context, Task task, PlanningState planningState,
IMessagesForUser messagesForUser) {
try {
if ( formBinder != null ) {
formBinder.detach();
}
allocationRows = resourceAllocationModel.initAllocationsFor(task,
context, planningState);
allocationRows = resourceAllocationModel.initAllocationsFor(task, context, planningState);
formBinder = allocationRows.createFormBinder(planningState
.getCurrentScenario(), resourceAllocationModel);
formBinder = allocationRows.createFormBinder(planningState.getCurrentScenario(), resourceAllocationModel);
formBinder.setBehaviour(ResourceAllocationBehaviour.NON_LIMITING);
formBinder.setAllOriginalEffort(allOriginalEffort);
formBinder.setAllTotalEffort(allTotalEffort);
@ -196,21 +193,17 @@ public class ResourceAllocationController extends GenericForwardComposer {
formBinder.setAssignedEffortComponent(assignedEffortComponent);
formBinder.setAllTotalResourcesPerDay(allTotalResourcesPerDay);
formBinder
.setAllConsolidatedResourcesPerDay(allConsolidatedResourcesPerDay);
formBinder.setAllConsolidatedResourcesPerDay(allConsolidatedResourcesPerDay);
formBinder.setAllResourcesPerDay(allResourcesPerDay);
TaskPropertiesController taskPropertiesController = editTaskController
.getTaskPropertiesController();
formBinder.setWorkableDays(getTaskWorkableDays(),
taskPropertiesController, getTaskStart(), getTaskEnd());
TaskPropertiesController taskPropertiesController = editTaskController.getTaskPropertiesController();
formBinder.setWorkableDays(getTaskWorkableDays(), taskPropertiesController, getTaskStart(), getTaskEnd());
formBinder.setApplyButton(applyButton);
formBinder.setAllocationsGrid(allocationsGrid);
formBinder.setMessagesForUser(messagesForUser);
formBinder.setWorkerSearchTab(workerSearchTab);
formBinder
.setNewAllocationSelectorCombo(newAllocationSelectorCombo);
formBinder.setNewAllocationSelectorCombo(newAllocationSelectorCombo);
initializeTaskInformationComponent();
initializeAllocationConfigurationComponent();
@ -219,8 +212,7 @@ public class ResourceAllocationController extends GenericForwardComposer {
tbResourceAllocation.setSelected(true);
newAllocationSelector.setAllocationsAdder(resourceAllocationModel);
newAllocationSelectorCombo
.setAllocationsAdder(resourceAllocationModel);
newAllocationSelectorCombo.setAllocationsAdder(resourceAllocationModel);
Util.reloadBindings(allocationsGrid);
} catch (WrongValueException e) {
@ -234,13 +226,11 @@ public class ResourceAllocationController extends GenericForwardComposer {
}
public Label getTaskStart() {
return (allocationConfiguration != null) ? allocationConfiguration
.getTaskStart() : null;
return (allocationConfiguration != null) ? allocationConfiguration.getTaskStart() : null;
}
public Label getTaskEnd() {
return (allocationConfiguration != null) ? allocationConfiguration
.getTaskEnd() : null;
return (allocationConfiguration != null) ? allocationConfiguration.getTaskEnd() : null;
}
private Radiogroup getCalculationTypeSelector() {
@ -248,10 +238,8 @@ public class ResourceAllocationController extends GenericForwardComposer {
}
private void initializeTaskInformationComponent() {
taskInformation.initializeGridTaskRows(resourceAllocationModel
.getHoursAggregatedByCriterions());
formBinder.setRecommendedAllocation(taskInformation
.getBtnRecommendedAllocation());
taskInformation.initializeGridTaskRows(resourceAllocationModel.getHoursAggregatedByCriterions());
formBinder.setRecommendedAllocation(taskInformation.getBtnRecommendedAllocation());
taskInformation.onCalculateTotalHours(new ITotalHoursCalculationListener() {
@Override
@ -269,23 +257,20 @@ public class ResourceAllocationController extends GenericForwardComposer {
CRITERIONS {
@Override
public Component cell(HoursRendererColumn column,
AggregatedHoursGroup data) {
public Component cell(HoursRendererColumn column, AggregatedHoursGroup data) {
return new Label(data.getCriterionsJoinedByComma());
}
},
RESOURCE_TYPE{
@Override
public Component cell(HoursRendererColumn column,
AggregatedHoursGroup data) {
public Component cell(HoursRendererColumn column, AggregatedHoursGroup data) {
return new Label(asString(data.getResourceType()));
}
},
HOURS {
@Override
public Component cell(HoursRendererColumn column,
AggregatedHoursGroup data) {
public Component cell(HoursRendererColumn column, AggregatedHoursGroup data) {
Label result = new Label(Integer.toString(data.getHours()));
return result;
}
@ -293,17 +278,19 @@ public class ResourceAllocationController extends GenericForwardComposer {
private static String asString(ResourceEnum resourceType) {
switch (resourceType) {
case MACHINE:
case WORKER:
return _(resourceType.getDisplayName());
default:
LOG.warn("no i18n for " + resourceType.name());
return resourceType.name();
}
}
public abstract Component cell(HoursRendererColumn column,
AggregatedHoursGroup data);
public abstract Component cell(HoursRendererColumn column, AggregatedHoursGroup data);
}
/**

View file

@ -70,8 +70,7 @@ import org.zkoss.zk.ui.Executions;
public abstract class ChartFiller implements IChartFiller {
protected abstract class EffortByDayCalculator<T> {
public SortedMap<LocalDate, EffortDuration> calculate(
Collection<? extends T> elements) {
public SortedMap<LocalDate, EffortDuration> calculate(Collection<? extends T> elements) {
SortedMap<LocalDate, EffortDuration> result = new TreeMap<LocalDate, EffortDuration>();
if ( elements.isEmpty() ) {
return result;

View file

@ -182,8 +182,7 @@ public abstract class EarnedValueChartFiller extends ChartFiller {
indicators.put(type, calculatedValueForEveryDay(values, interval));
}
protected void addZeroBeforeTheFirstValue(
SortedMap<LocalDate, BigDecimal> map) {
protected void addZeroBeforeTheFirstValue(SortedMap<LocalDate, BigDecimal> map) {
if ( !map.isEmpty() ) {
map.put(map.firstKey().minusDays(1), BigDecimal.ZERO);
}
@ -233,8 +232,7 @@ public abstract class EarnedValueChartFiller extends ChartFiller {
public LocalDate initialDateForIndicatorValues() {
Interval chartInterval = getIndicatorsDefinitionInterval();
LocalDate today = new LocalDate();
return includes(chartInterval, today) ? today : chartInterval
.getFinish().minusDays(1);
return includes(chartInterval, today) ? today : chartInterval.getFinish().minusDays(1);
}
/**

View file

@ -63,8 +63,7 @@ import org.zkoss.zul.Tab;
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class LimitingResourceAllocationController extends GenericForwardComposer {
private static final Log LOG = LogFactory
.getLog(LimitingResourceAllocationController.class);
private static final Log LOG = LogFactory.getLog(LimitingResourceAllocationController.class);
@Autowired
private ILimitingResourceAllocationModel resourceAllocationModel;

View file

@ -267,8 +267,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
private String tabSelected = "load_tab";
private static class NullSeparatorCommandOnTask<T> implements
ICommandOnTask<T> {
private static class NullSeparatorCommandOnTask<T> implements ICommandOnTask<T> {
@Override
public String getName() {
@ -294,7 +293,8 @@ public class OrderPlanningModel implements IOrderPlanningModel {
@Override
@Transactional(readOnly = true)
public void setConfigurationToPlanner(final Planner planner, Order order,
public void setConfigurationToPlanner(final Planner planner,
Order order,
ViewSwitcher switcher,
EditTaskController editTaskController,
AdvancedAllocationTaskController advancedAllocationTaskController,
@ -302,29 +302,27 @@ public class OrderPlanningModel implements IOrderPlanningModel {
AdvanceConsolidationController advanceConsolidationController,
CalendarAllocationController calendarAllocationController,
List<ICommand<TaskElement>> additional) {
long time = System.currentTimeMillis();
this.planner = planner;
planningState = createPlanningStateFor(order);
PlannerConfiguration<TaskElement> configuration = planningState
.getConfiguration();
PROFILING_LOG.debug("load data and create configuration took: "
+ (System.currentTimeMillis() - time) + " ms");
PlannerConfiguration<TaskElement> configuration = planningState.getConfiguration();
PROFILING_LOG.debug("load data and create configuration took: " + (System.currentTimeMillis() - time) + " ms");
User user;
try {
user = this.userDAO.findByLoginName(SecurityUtils
.getSessionUserLoginName());
user = this.userDAO.findByLoginName(SecurityUtils.getSessionUserLoginName());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
configuration.setExpandPlanningViewCharts(user
.isExpandOrderPlanningViewCharts());
configuration.setExpandPlanningViewCharts(user.isExpandOrderPlanningViewCharts());
addAdditional(additional, configuration);
planner.setInitialZoomLevel(getZoomLevel(configuration, order));
final boolean writingAllowed = isWritingAllowedOnOrder();
ISaveCommand saveCommand = setupSaveCommand(configuration,
writingAllowed);
ISaveCommand saveCommand = setupSaveCommand(configuration, writingAllowed);
setupEditingCapabilities(configuration, writingAllowed);
configuration.addGlobalCommand(buildReassigningCommand());
@ -335,25 +333,21 @@ public class OrderPlanningModel implements IOrderPlanningModel {
final IResourceAllocationCommand resourceAllocationCommand = buildResourceAllocationCommand(editTaskController);
final IAdvanceAssignmentPlanningCommand advanceAssignmentPlanningCommand = buildAdvanceAssignmentPlanningCommand(advanceAssignmentPlanningController);
final IAdvanceAssignmentPlanningCommand advanceAssignmentPlanningCommand =
buildAdvanceAssignmentPlanningCommand(advanceAssignmentPlanningController);
// Build context menu
configuration.addCommandOnTask(buildMilestoneCommand());
configuration.addCommandOnTask(buildDeleteMilestoneCommand());
configuration.addCommandOnTask(separator);
configuration
.addCommandOnTask(buildTaskPropertiesCommand(editTaskController));
configuration.addCommandOnTask(buildTaskPropertiesCommand(editTaskController));
configuration.addCommandOnTask(resourceAllocationCommand);
configuration
.addCommandOnTask(buildAdvancedAllocationCommand(advancedAllocationTaskController));
configuration
.addCommandOnTask(buildSubcontractCommand(editTaskController));
configuration
.addCommandOnTask(buildCalendarAllocationCommand(calendarAllocationController));
configuration.addCommandOnTask(buildAdvancedAllocationCommand(advancedAllocationTaskController));
configuration.addCommandOnTask(buildSubcontractCommand(editTaskController));
configuration.addCommandOnTask(buildCalendarAllocationCommand(calendarAllocationController));
configuration.addCommandOnTask(separator);
configuration.addCommandOnTask(advanceAssignmentPlanningCommand);
configuration
.addCommandOnTask(buildAdvanceConsolidationCommand(advanceConsolidationController));
configuration.addCommandOnTask(buildAdvanceConsolidationCommand(advanceConsolidationController));
configuration.setDoubleClickCommand(resourceAllocationCommand);
addPrintSupport(configuration, order);
@ -366,8 +360,10 @@ public class OrderPlanningModel implements IOrderPlanningModel {
configureModificators(planningState.getOrder(), configuration);
long setConfigurationTime = System.currentTimeMillis();
planner.setConfiguration(configuration);
PROFILING_LOG.debug("setConfiguration on planner took: "
+ (System.currentTimeMillis() - setConfigurationTime) + " ms");
PROFILING_LOG.debug("setConfiguration on planner took: " +
(System.currentTimeMillis() - setConfigurationTime) + " ms");
long preparingChartsAndMisc = System.currentTimeMillis();
setupZoomLevelListener(planner, order);
@ -389,23 +385,19 @@ public class OrderPlanningModel implements IOrderPlanningModel {
ChangeHooker changeHooker = new ChangeHooker(configuration, saveCommand);
setupLoadChart(chartLoadTimeplot, planner, changeHooker);
setupEarnedValueChart(chartEarnedValueTimeplot, earnedValueChartFiller,
planner, changeHooker);
setupEarnedValueChart(chartEarnedValueTimeplot, earnedValueChartFiller, planner, changeHooker);
setupAdvanceAssignmentPlanningController(planner, advanceAssignmentPlanningController);
PROFILING_LOG
.debug("preparing charts and miscellaneous took: "
+ (System.currentTimeMillis() - preparingChartsAndMisc)
+ " ms");
PROFILING_LOG.debug("preparing charts and miscellaneous took: " +
(System.currentTimeMillis() - preparingChartsAndMisc) + " ms");
// Calculate critical path progress, needed for 'Project global progress' chart in Dashboard view
planner.addGraphChangeListenersFromConfiguration(configuration);
long overalProgressContentTime = System.currentTimeMillis();
PROFILING_LOG.debug("overalProgressContent took: "
+ (System.currentTimeMillis() - overalProgressContentTime));
PROFILING_LOG.debug("overalProgressContent took: " + (System.currentTimeMillis() - overalProgressContentTime));
}
private ZoomLevel getZoomLevel(
PlannerConfiguration<TaskElement> configuration, Order order) {
private ZoomLevel getZoomLevel(PlannerConfiguration<TaskElement> configuration, Order order) {
ZoomLevel sessionZoom = FilterUtils.readZoomLevel(order);
if ( sessionZoom != null ) {
return sessionZoom;
@ -414,12 +406,10 @@ public class OrderPlanningModel implements IOrderPlanningModel {
}
private void setupZoomLevelListener(Planner planner, Order order) {
planner.getTimeTracker().addZoomListener(
getSessionZoomLevelListener(order));
planner.getTimeTracker().addZoomListener(getSessionZoomLevelListener(order));
}
private IZoomLevelChangedListener getSessionZoomLevelListener(
final Order order) {
private IZoomLevelChangedListener getSessionZoomLevelListener(final Order order) {
IZoomLevelChangedListener zoomListener = new IZoomLevelChangedListener() {
@Override
@ -434,7 +424,8 @@ public class OrderPlanningModel implements IOrderPlanningModel {
private OrderEarnedValueChartFiller earnedValueChartFiller;
private void setupAdvanceAssignmentPlanningController(final Planner planner,
private void setupAdvanceAssignmentPlanningController(
final Planner planner,
AdvanceAssignmentPlanningController advanceAssignmentPlanningController) {
advanceAssignmentPlanningController.setReloadEarnedValueListener(new IReloadChartListener() {
@ -451,6 +442,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
if ( planner.isVisibleChart() ) {
//update earned value chart
earnedValueChart.fillChart();
//update earned value legend
updateEarnedValueChartLegend();
}
@ -591,25 +583,20 @@ public class OrderPlanningModel implements IOrderPlanningModel {
return result;
}
void hookInto(EnumSet<ChangeTypes> reloadOn,
IReloadChartListener reloadChart) {
void hookInto(EnumSet<ChangeTypes> reloadOn, IReloadChartListener reloadChart) {
Validate.notNull(reloadChart);
hookIntoImpl(wrapIfNeeded(reloadChart), reloadOn);
}
private IReloadChartListener wrapIfNeeded(
IReloadChartListener reloadChart) {
private IReloadChartListener wrapIfNeeded(IReloadChartListener reloadChart) {
if ( !wrapOnReadOnlyTransaction ) {
return reloadChart;
}
return AdHocTransactionService.readOnlyProxy(transactionService,
IReloadChartListener.class, reloadChart);
return AdHocTransactionService.readOnlyProxy(transactionService, IReloadChartListener.class, reloadChart);
}
private void hookIntoImpl(IReloadChartListener reloadChart,
EnumSet<ChangeTypes> reloadOn) {
if (saveCommand != null
&& reloadOn.contains(ChangeTypes.ON_GRAPH_CHANGED)) {
private void hookIntoImpl(IReloadChartListener reloadChart, EnumSet<ChangeTypes> reloadOn) {
if ( saveCommand != null && reloadOn.contains(ChangeTypes.ON_GRAPH_CHANGED) ) {
hookIntoSaveCommand(reloadChart);
}
if ( reloadOn.contains(ChangeTypes.ON_RELOAD_CHART_REQUESTED) ) {
@ -630,14 +617,12 @@ public class OrderPlanningModel implements IOrderPlanningModel {
saveCommand.addListener(afterSaveListener);
}
private void hookIntoReloadChartRequested(
IReloadChartListener reloadChart) {
private void hookIntoReloadChartRequested(IReloadChartListener reloadChart) {
configuration.addReloadChartListener(reloadChart);
}
private void hookIntoGraphChanged(final IReloadChartListener reloadChart) {
configuration
.addPostGraphChangeListener(new IGraphChangeListener() {
configuration.addPostGraphChangeListener(new IGraphChangeListener() {
@Override
public void execute() {
@ -648,8 +633,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
}
private void addPrintSupport(
PlannerConfiguration<TaskElement> configuration, final Order order) {
private void addPrintSupport(PlannerConfiguration<TaskElement> configuration, final Order order) {
configuration.setPrintAction(new IPrintAction() {
@Override
public void doPrint() {
@ -662,8 +646,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
}
@Override
public void doPrint(HashMap<String, String> parameters,
Planner planner) {
public void doPrint(HashMap<String, String> parameters, Planner planner) {
CutyPrint.print(order, parameters, planner);
}
@ -676,8 +659,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
return deleteMilestoneCommand;
}
private void configureModificators(Order orderReloaded,
PlannerConfiguration<TaskElement> configuration) {
private void configureModificators(Order orderReloaded, PlannerConfiguration<TaskElement> configuration) {
// Either InitDate or DeadLine must be set, depending on forwards or
// backwards planning
configuration.setSecondLevelModificators(SeveralModificators.create(
@ -761,13 +743,11 @@ public class OrderPlanningModel implements IOrderPlanningModel {
hbox.setClass("legend-container");
hbox.setAlign("center");
hbox.setPack("center");
Executions.createComponents("/planner/_legendLoadChartOrder.zul", hbox,
null);
Executions.createComponents("/planner/_legendLoadChartOrder.zul", hbox, null);
return hbox;
}
private Constraint dateMustBeInsideVisualizationArea(
final OrderEarnedValueChartFiller earnedValueChartFiller) {
private Constraint dateMustBeInsideVisualizationArea(final OrderEarnedValueChartFiller earnedValueChartFiller) {
return new Constraint() {
@Override
@ -775,13 +755,12 @@ public class OrderPlanningModel implements IOrderPlanningModel {
Object valueObject)
throws WrongValueException {
Date value = (Date) valueObject;
if (value != null
&& !EarnedValueChartFiller.includes(
earnedValueChartFiller
.getIndicatorsDefinitionInterval(), LocalDate
.fromDateFields(value))) {
throw new WrongValueException(comp,
_("Date must be inside visualization area"));
if ( value != null && !EarnedValueChartFiller.includes(
earnedValueChartFiller.getIndicatorsDefinitionInterval(),
LocalDate.fromDateFields(value)) ) {
throw new WrongValueException(comp, _("Date must be inside visualization area"));
}
}
@ -790,16 +769,15 @@ public class OrderPlanningModel implements IOrderPlanningModel {
private void dateInfutureMessage(Datebox datebox) {
Date value = datebox.getValue();
Date today = LocalDate.fromDateFields(new Date())
.toDateTimeAtStartOfDay().toDate();
Date today = LocalDate.fromDateFields(new Date()).toDateTimeAtStartOfDay().toDate();
if ( value != null && (value.compareTo(today) > 0) ) {
throw new WrongValueException(datebox, _("date in the future"));
}
}
private void appendEventListenerToDateboxIndicators(
final OrderEarnedValueChartFiller earnedValueChartFiller,
private void appendEventListenerToDateboxIndicators(final OrderEarnedValueChartFiller earnedValueChartFiller,
final Vbox vbox) {
earnedValueChartLegendDatebox.addEventListener(Events.ON_CHANGE,
new EventListener() {
@ -816,33 +794,29 @@ public class OrderPlanningModel implements IOrderPlanningModel {
try {
//force the validation again (getValue alone doesn't work because
//the result of the validation is cached)
earnedValueChartLegendDatebox.setValue(
earnedValueChartLegendDatebox.getValue());
earnedValueChartLegendDatebox.setValue(earnedValueChartLegendDatebox.getValue());
}
catch (WrongValueException e) {
//the user moved the gantt and the legend became out of the
//visualization area, reset to a correct date
earnedValueChartLegendDatebox.setValue(earnedValueChartFiller.
initialDateForIndicatorValues().toDateTimeAtStartOfDay()
.toDate());
earnedValueChartLegendDatebox.setValue(earnedValueChartFiller.initialDateForIndicatorValues().
toDateTimeAtStartOfDay().toDate());
}
LocalDate date = new LocalDate(earnedValueChartLegendDatebox.getRawValue());
org.zkoss.zk.ui.Component child = earnedValueChartLegendContainer
.getFellow("indicatorsTable");
org.zkoss.zk.ui.Component child = earnedValueChartLegendContainer.getFellow("indicatorsTable");
updateEarnedValueChartLegend(date);
}
private void updateEarnedValueChartLegend(LocalDate date) {
for (EarnedValueType type : EarnedValueType.values()) {
Label valueLabel = (Label) earnedValueChartLegendContainer
.getFellow(type.toString());
valueLabel.setValue(getLabelTextEarnedValueType(
earnedValueChartFiller, type, date));
Label valueLabel = (Label) earnedValueChartLegendContainer.getFellow(type.toString());
valueLabel.setValue(getLabelTextEarnedValueType(earnedValueChartFiller, type, date));
}
}
private org.zkoss.zk.ui.Component getEarnedValueChartConfigurableLegend(
OrderEarnedValueChartFiller earnedValueChartFiller, LocalDate date) {
Hbox mainhbox = new Hbox();
mainhbox.setId("indicatorsTable");
@ -864,8 +838,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
checkbox.setAttribute("indicator", type);
checkbox.setStyle("color: " + type.getColor());
Label valueLabel = new Label(getLabelTextEarnedValueType(
earnedValueChartFiller, type, date));
Label valueLabel = new Label(getLabelTextEarnedValueType(earnedValueChartFiller, type, date));
valueLabel.setId(type.toString());
Hbox hbox = new Hbox();
@ -874,9 +847,11 @@ public class OrderPlanningModel implements IOrderPlanningModel {
columnNumber = columnNumber + 1;
switch (columnNumber) {
case 1:
column1.appendChild(hbox);
break;
case 2:
column2.appendChild(hbox);
columnNumber = 0;
@ -897,13 +872,12 @@ public class OrderPlanningModel implements IOrderPlanningModel {
return mainhbox;
}
private String getLabelTextEarnedValueType(
OrderEarnedValueChartFiller earnedValueChartFiller,
private String getLabelTextEarnedValueType(OrderEarnedValueChartFiller earnedValueChartFiller,
EarnedValueType type, LocalDate date) {
BigDecimal value = earnedValueChartFiller.getIndicator(type, date);
String units = _("h");
if (type.equals(EarnedValueType.CPI)
|| type.equals(EarnedValueType.SPI)) {
if ( type.equals(EarnedValueType.CPI) || type.equals(EarnedValueType.SPI) ) {
value = value.multiply(new BigDecimal(100));
units = "%";
}
@ -912,11 +886,12 @@ public class OrderPlanningModel implements IOrderPlanningModel {
private void markAsSelectedDefaultIndicators() {
for (Checkbox checkbox : earnedValueChartConfigurationCheckboxes) {
EarnedValueType type = (EarnedValueType) checkbox
.getAttribute("indicator");
EarnedValueType type = (EarnedValueType) checkbox.getAttribute("indicator");
switch (type) {
case BCWS:
case ACWP:
case BCWP:
checkbox.setChecked(true);
break;
@ -932,16 +907,14 @@ public class OrderPlanningModel implements IOrderPlanningModel {
Set<EarnedValueType> result = new HashSet<EarnedValueType>();
for (Checkbox checkbox : earnedValueChartConfigurationCheckboxes) {
if ( checkbox.isChecked() ) {
EarnedValueType type = (EarnedValueType) checkbox
.getAttribute("indicator");
EarnedValueType type = (EarnedValueType) checkbox.getAttribute("indicator");
result.add(type);
}
}
return result;
}
private void setEventListenerConfigurationCheckboxes(
final Chart earnedValueChart) {
private void setEventListenerConfigurationCheckboxes(final Chart earnedValueChart) {
for (Checkbox checkbox : earnedValueChartConfigurationCheckboxes) {
checkbox.addEventListener(Events.ON_CHECK, new EventListener() {
@ -962,16 +935,13 @@ public class OrderPlanningModel implements IOrderPlanningModel {
}
}
private void refillLoadChartWhenNeeded(ChangeHooker changeHooker,
final Planner planner, final Chart loadChart,
private void refillLoadChartWhenNeeded(ChangeHooker changeHooker, final Planner planner, final Chart loadChart,
final boolean updateEarnedValueChartLegend) {
planner.getTimeTracker().addZoomListener(
fillOnZoomChange(loadChart, planner, updateEarnedValueChartLegend));
planner
.addChartVisibilityListener(fillOnChartVisibilityChange(loadChart));
changeHooker.withReadOnlyTransactionWraping().hookInto(
EnumSet.allOf(ChangeTypes.class), new IReloadChartListener() {
planner.getTimeTracker().addZoomListener(fillOnZoomChange(loadChart, planner, updateEarnedValueChartLegend));
planner.addChartVisibilityListener(fillOnChartVisibilityChange(loadChart));
changeHooker.withReadOnlyTransactionWraping().hookInto(EnumSet.allOf(ChangeTypes.class), new IReloadChartListener() {
@Override
public void reloadChart() {
@ -994,19 +964,20 @@ public class OrderPlanningModel implements IOrderPlanningModel {
private void addAdditional(List<ICommand<TaskElement>> additional,
PlannerConfiguration<TaskElement> configuration) {
for (ICommand<TaskElement> c : additional) {
configuration.addGlobalCommand(c);
}
}
private boolean isWritingAllowedOnOrder() {
if (planningState.getSavedOrderState() == OrderStatusEnum.STORED
&& planningState.getOrder().getState() == OrderStatusEnum.STORED) {
if ( planningState.getSavedOrderState() == OrderStatusEnum.STORED &&
planningState.getOrder().getState() == OrderStatusEnum.STORED ) {
// STORED orders can't be saved, independently of user permissions
return false;
}
if (SecurityUtils
.isSuperuserOrUserInRoles(UserRole.ROLE_EDIT_ALL_PROJECTS)) {
if ( SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_EDIT_ALL_PROJECTS) ) {
return true;
}
return thereIsWriteAuthorizationFor(planningState.getOrder());
@ -1016,8 +987,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
String loginName = SecurityUtils.getSessionUserLoginName();
try {
User user = userDAO.findByLoginName(loginName);
for (OrderAuthorization authorization : orderAuthorizationDAO
.listByOrderUserAndItsProfiles(order, user)) {
for (OrderAuthorization authorization : orderAuthorizationDAO.listByOrderUserAndItsProfiles(order, user)) {
if ( authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION ) {
return true;
}
@ -1364,8 +1334,7 @@ public class OrderPlanningModel implements IOrderPlanningModel {
}
private ISubcontractCommand buildSubcontractCommand(
EditTaskController editTaskController) {
private ISubcontractCommand buildSubcontractCommand(EditTaskController editTaskController) {
subcontractCommand.initialize(editTaskController, planningState);
return subcontractCommand;
}

View file

@ -130,32 +130,33 @@ public class SaveCommandBuilder {
private static final Log LOG = LogFactory.getLog(SaveCommandBuilder.class);
public ISaveCommand build(PlanningState planningState,
PlannerConfiguration<TaskElement> plannerConfiguration) {
SaveCommand result = new SaveCommand(planningState,
plannerConfiguration);
public ISaveCommand build(PlanningState planningState, PlannerConfiguration<TaskElement> plannerConfiguration) {
SaveCommand result = new SaveCommand(planningState, plannerConfiguration);
return ConcurrentModificationHandling.addHandling(
"/planner/index.zul;company_scheduling", ISaveCommand.class,
result);
"/planner/index.zul;company_scheduling", ISaveCommand.class, result);
}
public static void dontPoseAsTransientAndChildrenObjects(
Collection<? extends ResourceAllocation<?>> resourceAllocations) {
for (ResourceAllocation<?> each : resourceAllocations) {
each.dontPoseAsTransientObjectAnymore();
each.makeAssignmentsContainersDontPoseAsTransientAnyMore();
for (DayAssignment eachAssignment : each.getAssignments()) {
eachAssignment.dontPoseAsTransientObjectAnymore();
}
for (DerivedAllocation eachDerived : each.getDerivedAllocations()) {
eachDerived.dontPoseAsTransientObjectAnymore();
Collection<DerivedDayAssignmentsContainer> containers = eachDerived
.getContainers();
Collection<DerivedDayAssignmentsContainer> containers = eachDerived.getContainers();
for (DerivedDayAssignmentsContainer eachContainer : containers) {
eachContainer.dontPoseAsTransientObjectAnymore();
}
for (DerivedDayAssignment eachAssignment : eachDerived
.getAssignments()) {
for (DerivedDayAssignment eachAssignment : eachDerived.getAssignments()) {
eachAssignment.dontPoseAsTransientObjectAnymore();
}
}
@ -165,12 +166,10 @@ public class SaveCommandBuilder {
private static void dontPoseAsTransient(LimitingResourceQueueElement element) {
if ( element != null ) {
for (LimitingResourceQueueDependency d : element
.getDependenciesAsOrigin()) {
for (LimitingResourceQueueDependency d : element.getDependenciesAsOrigin()) {
d.dontPoseAsTransientObjectAnymore();
}
for (LimitingResourceQueueDependency d : element
.getDependenciesAsDestiny()) {
for (LimitingResourceQueueDependency d : element.getDependenciesAsDestiny()) {
d.dontPoseAsTransientObjectAnymore();
}
element.dontPoseAsTransientObjectAnymore();
@ -236,24 +235,20 @@ public class SaveCommandBuilder {
private boolean disabled = false;
public SaveCommand(PlanningState planningState,
PlannerConfiguration<TaskElement> configuration) {
public SaveCommand(PlanningState planningState, PlannerConfiguration<TaskElement> configuration) {
this.state = planningState;
this.configuration = configuration;
this.adapter = configuration.getAdapter();
this.constraintCalculator = new ConstraintCalculator<TaskElement>(
configuration.isScheduleBackwards()) {
this.constraintCalculator = new ConstraintCalculator<TaskElement>(configuration.isScheduleBackwards()) {
@Override
protected GanttDate getStartDate(TaskElement vertex) {
return TaskElementAdapter.toGantt(vertex
.getIntraDayStartDate());
return TaskElementAdapter.toGantt(vertex.getIntraDayStartDate());
}
@Override
protected GanttDate getEndDate(TaskElement vertex) {
return TaskElementAdapter.toGantt(vertex
.getIntraDayEndDate());
return TaskElementAdapter.toGantt(vertex.getIntraDayEndDate());
}
};
}
@ -289,13 +284,10 @@ public class SaveCommandBuilder {
}
@Override
public void save(final IBeforeSaveActions beforeSaveActions,
IAfterSaveActions afterSaveActions) {
public void save(final IBeforeSaveActions beforeSaveActions, IAfterSaveActions afterSaveActions) {
try {
if (state.getScenarioInfo().isUsingTheOwnerScenario()
|| userAcceptsCreateANewOrderVersion()) {
transactionService
.runOnTransaction(new IOnTransaction<Void>() {
if ( state.getScenarioInfo().isUsingTheOwnerScenario() || userAcceptsCreateANewOrderVersion() ) {
transactionService.runOnTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
if (beforeSaveActions != null) {
@ -305,15 +297,13 @@ public class SaveCommandBuilder {
return null;
}
});
dontPoseAsTransientObjectAnymore(state.getOrder());
dontPoseAsTransientObjectAnymore(state.getOrder()
.getEndDateCommunicationToCustomer());
dontPoseAsTransientObjectAnymore(state.getOrder().getEndDateCommunicationToCustomer());
state.getScenarioInfo().afterCommit();
if (state.getOrder()
.isNeededToRecalculateSumChargedEfforts()) {
sumChargedEffortRecalculator.recalculate(state
.getOrder().getId());
if ( state.getOrder().isNeededToRecalculateSumChargedEfforts() ) {
sumChargedEffortRecalculator.recalculate(state.getOrder().getId());
}
if ( state.getOrder().isNeededToRecalculateSumExpenses() ) {
@ -334,12 +324,9 @@ public class SaveCommandBuilder {
String message = "";
LabelCreatorForInvalidValues labelCreator = new LabelCreatorForInvalidValues();
for (InvalidValue invalidValue : validationException
.getInvalidValues()) {
message += "* "
+ ((Label) labelCreator
.createLabelFor(invalidValue))
.getValue() + "\n";
for (InvalidValue invalidValue : validationException.getInvalidValues()) {
message += "* " + ((Label) labelCreator.createLabelFor(invalidValue)).getValue() + "\n";
}
if ( validationException.getInvalidValues().isEmpty() ) {
@ -347,9 +334,11 @@ public class SaveCommandBuilder {
}
LOG.warn("Error saving the project", validationException);
Messagebox.show(
_("Error saving the project\n{0}", message),
_("Error"), Messagebox.OK, Messagebox.ERROR);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@ -369,8 +358,7 @@ public class SaveCommandBuilder {
return;
}
try {
Messagebox.show(_("Project saved"), _("Information"),
Messagebox.OK, Messagebox.INFORMATION);
Messagebox.show(_("Project saved"), _("Information"), Messagebox.OK, Messagebox.INFORMATION);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
@ -378,9 +366,7 @@ public class SaveCommandBuilder {
// Reset timer of warning on leaving page
ConfirmCloseUtil.resetConfirmClose();
if ( SecurityUtils.loggedUserCanWrite(state.getOrder()) ) {
ConfirmCloseUtil
.setConfirmClose(
Executions.getCurrent().getDesktop(),
ConfirmCloseUtil.setConfirmClose(Executions.getCurrent().getDesktop(),
_("You are about to leave the planning editing. Unsaved changes will be lost!"));
}
}
@ -1072,8 +1058,7 @@ public class SaveCommandBuilder {
orderElementName = _("Project");
} else {
orderElementName = _("Task {0}",
((OrderElement) invalidValue.getRootBean())
.getName());
((OrderElement) invalidValue.getRootBean()).getName());
}
result.setValue(orderElementName + ": "

View file

@ -133,14 +133,15 @@ public class EditTaskController extends GenericForwardComposer {
return subcontractController;
}
private void showEditForm(IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement, PlanningState planningState) {
private void showEditForm(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement,
PlanningState planningState) {
showEditForm(context, taskElement, planningState, false);
}
private void showEditForm(IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement, PlanningState planningState,
boolean fromLimitingResourcesView) {
private void showEditForm(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement,
PlanningState planningState, boolean fromLimitingResourcesView) {
this.taskElement = taskElement;
this.context = context;
this.planningState = planningState;
@ -163,30 +164,22 @@ public class EditTaskController extends GenericForwardComposer {
}
private void showSelectedTabPanel() {
showTabPanel(taskPropertiesController
.getResourceAllocationType(taskElement));
showTabPanel(taskPropertiesController.getResourceAllocationType(taskElement));
}
public void showTabPanel(
ResourceAllocationTypeEnum resourceAllocationType) {
public void showTabPanel(ResourceAllocationTypeEnum resourceAllocationType) {
subcontractTab.setVisible(false);
resourceAllocationTab.setVisible(false);
limitingResourceAllocationTab.setVisible(false);
if (ResourceAllocationTypeEnum.SUBCONTRACT
.equals(resourceAllocationType)) {
subcontractController.init(asTask(taskElement), context,
taskPropertiesController.getTaskEditFormComposer());
if ( ResourceAllocationTypeEnum.SUBCONTRACT.equals(resourceAllocationType) ) {
subcontractController.init(asTask(taskElement), context, taskPropertiesController.getTaskEditFormComposer());
showSubcontractTab();
} else if (ResourceAllocationTypeEnum.NON_LIMITING_RESOURCES
.equals(resourceAllocationType)) {
} else if ( ResourceAllocationTypeEnum.NON_LIMITING_RESOURCES.equals(resourceAllocationType) ) {
resourceAllocationController.init(context, asTask(taskElement), planningState, messagesForUser);
showNonLimitingResourcesTab();
} else if (ResourceAllocationTypeEnum.LIMITING_RESOURCES
.equals(resourceAllocationType)) {
limitingResourceAllocationController.init(context, asTask(taskElement),
planningState, messagesForUser);
} else if ( ResourceAllocationTypeEnum.LIMITING_RESOURCES.equals(resourceAllocationType) ) {
limitingResourceAllocationController.init(context, asTask(taskElement), planningState, messagesForUser);
showLimitingResourcesTab();
}
}
@ -205,9 +198,9 @@ public class EditTaskController extends GenericForwardComposer {
limitingResourceAllocationTab.setVisible(true);
}
public void showEditFormTaskProperties(
IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement, PlanningState planningState) {
public void showEditFormTaskProperties(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement,
PlanningState planningState) {
editTaskTabbox.setSelectedPanelApi(taskPropertiesTabpanel);
showEditForm(context, taskElement, planningState);
}
@ -218,17 +211,13 @@ public class EditTaskController extends GenericForwardComposer {
showEditFormResourceAllocation(null, taskElement, null, true);
}
public void showEditFormResourceAllocation(
IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement, PlanningState planningState) {
showEditFormResourceAllocation(context, taskElement, planningState,
false);
public void showEditFormResourceAllocation(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement,
PlanningState planningState) {
showEditFormResourceAllocation(context, taskElement, planningState, false);
}
public void showEditFormResourceAllocation(
IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement, PlanningState planningState,
boolean fromLimitingResourcesView) {
public void showEditFormResourceAllocation(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement,
PlanningState planningState, boolean fromLimitingResourcesView) {
if ( isTask(taskElement) ) {
Task task = asTask(taskElement);
@ -240,17 +229,16 @@ public class EditTaskController extends GenericForwardComposer {
} else {
editTaskTabbox.setSelectedPanelApi(taskPropertiesTabpanel);
}
showEditForm(context, taskElement, planningState,
fromLimitingResourcesView);
showEditForm(context, taskElement, planningState, fromLimitingResourcesView);
}
public void selectAssignmentTab(int index) {
editTaskTabbox.setSelectedIndex(index);
}
public void showEditFormSubcontract(
IContextWithPlannerTask<TaskElement> context,
TaskElement taskElement, PlanningState planningState) {
public void showEditFormSubcontract(IContextWithPlannerTask<TaskElement> context, TaskElement taskElement,
PlanningState planningState) {
if ( isSubcontractedAndIsTask(taskElement) ) {
editTaskTabbox.setSelectedPanelApi(subcontractTabpanel);
} else {

View file

@ -100,11 +100,9 @@ public class AssignedCriterionsModel extends IntegrationEntityModel implements
private void initDTOs() {
criterionSatisfactionDTOs = new HashSet<CriterionSatisfactionDTO>();
for (CriterionSatisfaction criterionSatisfaction : worker
.getCriterionSatisfactions()) {
for (CriterionSatisfaction criterionSatisfaction : worker.getCriterionSatisfactions()) {
if ( !criterionSatisfaction.isIsDeleted() ) {
CriterionSatisfactionDTO dto = new CriterionSatisfactionDTO(
criterionSatisfaction);
CriterionSatisfactionDTO dto = new CriterionSatisfactionDTO(criterionSatisfaction);
criterionSatisfactionDTOs.add(dto);
}
}
@ -344,21 +342,20 @@ public class AssignedCriterionsModel extends IntegrationEntityModel implements
}
private List<CriterionSatisfactionDTO> getWithCriterionAssignedDTOs() {
return CriterionSatisfactionDTO
.keepHavingCriterion(criterionSatisfactionDTOs);
return CriterionSatisfactionDTO.keepHavingCriterion(criterionSatisfactionDTOs);
}
private void updateDTOs() throws ValidationException, IllegalStateException {
// Create a new list of Criterion satisfaction
Set<CriterionSatisfaction> newList = new HashSet<CriterionSatisfaction>();
for (CriterionSatisfactionDTO satisfactionDTO : getWithCriterionAssignedDTOs()) {
CriterionSatisfaction satisfaction;
if ( satisfactionDTO.isNewObject() ) {
Criterion criterion = satisfactionDTO.getCriterionWithItsType()
.getCriterion();
Criterion criterion = satisfactionDTO.getCriterionWithItsType().getCriterion();
Interval interval = satisfactionDTO.getInterval();
satisfaction = CriterionSatisfaction.create(criterion, worker,
interval);
satisfaction = CriterionSatisfaction.create(criterion, worker, interval);
// set the autogenerated code
currentCriterionSatisfaction = satisfaction;
@ -369,6 +366,7 @@ public class AssignedCriterionsModel extends IntegrationEntityModel implements
satisfaction.setIsDeleted(true);
} else {
satisfaction.setStartDate(satisfactionDTO.getStart());
if ( satisfactionDTO.getEndDate() != null ) {
satisfaction.finish(satisfactionDTO.getEnd());
} else {

View file

@ -74,19 +74,19 @@ public class WorkRelationshipsController extends GenericForwardComposer {
public WorkRelationshipsController(IWorkerModel workerModel,
WorkerCRUDController workerCRUDController,
IMessagesForUser messagesForUser) {
this.workerModel = workerModel;
this.workerCRUDController = workerCRUDController;
this.messagesForUser = messagesForUser;
this.workCriterions = new ArrayList<Criterion>();
Map<ICriterionType<?>, Collection<Criterion>> map = workerModel
.getLaboralRelatedCriterions();
Map<ICriterionType<?>, Collection<Criterion>> map = workerModel.getLaboralRelatedCriterions();
this.fromCriterionToType = new HashMap<Criterion, CriterionWithItsType>();
for (Entry<ICriterionType<?>, Collection<Criterion>> entry : map
.entrySet()) {
for (Entry<ICriterionType<?>, Collection<Criterion>> entry : map.entrySet()) {
this.workCriterions.addAll(entry.getValue());
for (Criterion criterion : entry.getValue()) {
this.fromCriterionToType.put(criterion,
new CriterionWithItsType(entry.getKey(), criterion));
this.fromCriterionToType.put(criterion, new CriterionWithItsType(entry.getKey(), criterion));
}
}
}

View file

@ -103,8 +103,7 @@ import org.zkoss.zul.api.Window;
* @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
*/
public class WorkerCRUDController extends GenericForwardComposer implements
IWorkerCRUDControllerEntryPoints {
public class WorkerCRUDController extends GenericForwardComposer implements IWorkerCRUDControllerEntryPoints {
@Autowired
private IDBPasswordEncoderService dbPasswordEncoderService;
@ -304,8 +303,7 @@ public class WorkerCRUDController extends GenericForwardComposer implements
if ( UserBindingOption.EXISTING_USER.ordinal() == option ) {
if ( getWorker().getUser() == null ) {
throw new WrongValueException(userBandbox,
_("please select a user to bound"));
throw new WrongValueException(userBandbox, _("please select a user to bound"));
}
getWorker().updateUserData();
}
@ -318,8 +316,7 @@ public class WorkerCRUDController extends GenericForwardComposer implements
private User createNewUserForBinding() {
String loginName = loginNameTextbox.getValue();
if ( StringUtils.isBlank(loginName) ) {
throw new WrongValueException(loginNameTextbox,
_("cannot be empty"));
throw new WrongValueException(loginNameTextbox, _("cannot be empty"));
}
String password = passwordTextbox.getValue();
@ -394,8 +391,7 @@ public class WorkerCRUDController extends GenericForwardComposer implements
state = CRUDControllerState.EDIT;
getBookmarker().goToEditForm(worker);
workerModel.prepareEditFor(worker);
resourcesCostCategoryAssignmentController.setResource(workerModel
.getWorker());
resourcesCostCategoryAssignmentController.setResource(workerModel.getWorker());
if ( isCalendarNotNull() ) {
editCalendar();
}
@ -403,8 +399,7 @@ public class WorkerCRUDController extends GenericForwardComposer implements
updateUserBindingComponents();
showEditWindow(_("Edit Worker: {0}", worker.getHumanId()));
Textbox workerFirstname = (Textbox) editWindow
.getFellow("workerFirstname");
Textbox workerFirstname = (Textbox) editWindow.getFellow("workerFirstname");
workerFirstname.focus();
}
@ -453,13 +448,11 @@ public class WorkerCRUDController extends GenericForwardComposer implements
getBookmarker().goToCreateForm();
workerModel.prepareForCreate();
createAsignedCriterions();
resourcesCostCategoryAssignmentController.setResource(workerModel
.getWorker());
resourcesCostCategoryAssignmentController.setResource(workerModel.getWorker());
updateUserBindingComponents();
showEditWindow(_("Create Worker"));
resourceCalendarModel.cancel();
Textbox workerFirstname = (Textbox) editWindow
.getFellow("workerFirstname");
Textbox workerFirstname = (Textbox) editWindow.getFellow("workerFirstname");
workerFirstname.focus();
}
@ -473,10 +466,8 @@ public class WorkerCRUDController extends GenericForwardComposer implements
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
localizationsForEditionController = createLocalizationsController(comp,
"editWindow");
localizationsForCreationController = createLocalizationsController(
comp, "editWindow");
localizationsForEditionController = createLocalizationsController(comp, "editWindow");
localizationsForCreationController = createLocalizationsController(comp, "editWindow");
comp.setVariable("controller", this, true);
if ( messagesContainer == null ) {
throw new RuntimeException(_("MessagesContainer is needed"));
@ -490,22 +481,20 @@ public class WorkerCRUDController extends GenericForwardComposer implements
initializeTabs();
initUserBindingComponents();
final EntryPointsHandler<IWorkerCRUDControllerEntryPoints> handler = URLHandlerRegistry
.getRedirectorFor(IWorkerCRUDControllerEntryPoints.class);
final EntryPointsHandler<IWorkerCRUDControllerEntryPoints> handler =
URLHandlerRegistry.getRedirectorFor(IWorkerCRUDControllerEntryPoints.class);
handler.register(this, page);
}
private void initUserBindingComponents() {
userBindingGroupbox = (Groupbox) editWindow
.getFellowIfAny("userBindingGroupbox");
userBindingRadiogroup = (Radiogroup) editWindow
.getFellowIfAny("userBindingRadiogroup");
userBindingGroupbox = (Groupbox) editWindow.getFellowIfAny("userBindingGroupbox");
userBindingRadiogroup = (Radiogroup) editWindow.getFellowIfAny("userBindingRadiogroup");
initUserBindingOptions();
userBandbox = (BandboxSearch) editWindow.getFellowIfAny("userBandbox");
loginNameTextbox = (Textbox) editWindow.getFellowIfAny("loginName");
passwordTextbox = (Textbox) editWindow.getFellowIfAny("password");
passwordConfirmationTextbox = (Textbox) editWindow
.getFellowIfAny("passwordConfirmation");
passwordConfirmationTextbox = (Textbox) editWindow.getFellowIfAny("passwordConfirmation");
emailTextbox = (Textbox) editWindow.getFellowIfAny("email");
}
@ -513,9 +502,10 @@ public class WorkerCRUDController extends GenericForwardComposer implements
UserBindingOption[] values = UserBindingOption.values();
for (UserBindingOption option : values) {
Radio radio = new Radio(_(option.label));
if (option.equals(UserBindingOption.CREATE_NEW_USER)
&& !SecurityUtils
.isSuperuserOrUserInRoles(UserRole.ROLE_USER_ACCOUNTS)) {
if ( option.equals(UserBindingOption.CREATE_NEW_USER) &&
!SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_USER_ACCOUNTS)) {
radio.setDisabled(true);
radio.setTooltiptext(_("You do not have permissions to create new users"));
}
@ -530,14 +520,10 @@ public class WorkerCRUDController extends GenericForwardComposer implements
}
private void initFilterComponent() {
this.filterFinishDate = (Datebox) listWindow
.getFellowIfAny("filterFinishDate");
this.filterStartDate = (Datebox) listWindow
.getFellowIfAny("filterStartDate");
this.filterLimitingResource = (Listbox) listWindow
.getFellowIfAny("filterLimitingResource");
this.bdFilters = (BandboxMultipleSearch) listWindow
.getFellowIfAny("bdFilters");
this.filterFinishDate = (Datebox) listWindow.getFellowIfAny("filterFinishDate");
this.filterStartDate = (Datebox) listWindow.getFellowIfAny("filterStartDate");
this.filterLimitingResource = (Listbox) listWindow.getFellowIfAny("filterLimitingResource");
this.bdFilters = (BandboxMultipleSearch) listWindow.getFellowIfAny("bdFilters");
this.txtfilter = (Textbox) listWindow.getFellowIfAny("txtfilter");
this.listing = (Grid) listWindow.getFellowIfAny("listing");
clearFilterDates();

View file

@ -49,7 +49,6 @@ import org.libreplan.business.planner.daos.IDayAssignmentDAO;
import org.libreplan.business.planner.daos.IResourceAllocationDAO;
import org.libreplan.business.resources.daos.ICriterionDAO;
import org.libreplan.business.resources.daos.IResourceDAO;
import org.libreplan.business.resources.daos.IWorkerDAO;
import org.libreplan.business.resources.entities.Criterion;
import org.libreplan.business.resources.entities.CriterionSatisfaction;
import org.libreplan.business.resources.entities.CriterionWithItsType;
@ -165,8 +164,7 @@ public class WorkerModel extends IntegrationEntityModel implements IWorkerModel
private void resetRoleInOriginalBoundUser() {
if ( boundUser != null ) {
User user = worker.getUser();
if (user == null || user.getId() == null
|| !user.getId().equals(boundUser.getId())) {
if ( user == null || user.getId() == null || !user.getId().equals(boundUser.getId()) ) {
boundUser.removeRole(UserRole.ROLE_BOUND_USER);
userDAO.save(boundUser);
}
@ -230,13 +228,13 @@ public class WorkerModel extends IntegrationEntityModel implements IWorkerModel
worker = Worker.create("");
}
worker.setCodeAutogenerated(configurationDAO.getConfiguration()
.getGenerateCodeForResources());
worker.setCodeAutogenerated(configurationDAO.getConfiguration().getGenerateCodeForResources());
if ( worker.isCodeAutogenerated() ) {
setDefaultCode();
}
localizationsAssigner = new MultipleCriterionActiveAssigner(
criterionDAO, worker, PredefinedCriterionTypes.LOCATION);
localizationsAssigner =
new MultipleCriterionActiveAssigner(criterionDAO, worker, PredefinedCriterionTypes.LOCATION);
boundUser = null;
}
@ -250,9 +248,10 @@ public class WorkerModel extends IntegrationEntityModel implements IWorkerModel
forceLoadCalendar(this.worker);
forceLoadUser(this.worker);
this.boundUser = this.worker.getUser();
localizationsAssigner = new MultipleCriterionActiveAssigner(
criterionDAO, this.worker,
PredefinedCriterionTypes.LOCATION);
localizationsAssigner =
new MultipleCriterionActiveAssigner(criterionDAO, this.worker, PredefinedCriterionTypes.LOCATION);
initOldCodes();
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
@ -624,8 +623,7 @@ public class WorkerModel extends IntegrationEntityModel implements IWorkerModel
@Override
@Transactional
public void confirmRemove(Worker worker, boolean removeBoundUser)
throws InstanceNotFoundException {
public void confirmRemove(Worker worker, boolean removeBoundUser) throws InstanceNotFoundException {
resourceDAO.remove(worker.getId());
User user = getBoundUserFromDB(worker);

View file

@ -88,8 +88,7 @@ import org.zkoss.zul.impl.api.InputElement;
* @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Diego Pino García <dpino@igalia.com>
*/
public abstract class TreeController<T extends ITreeNode<T>> extends
GenericForwardComposer {
public abstract class TreeController<T extends ITreeNode<T>> extends GenericForwardComposer {
private static final ValidatorFactory validatorFactory = Validation
.buildDefaultValidatorFactory();
@ -253,8 +252,7 @@ public abstract class TreeController<T extends ITreeNode<T>> extends
if ( tree.getSelectedCount() == 1 ) {
T node = getSelectedNode();
T newNode = getModel().addElementAt(node, name.getValue(),
hours.getValue());
T newNode = getModel().addElementAt(node, name.getValue(), hours.getValue());
getRenderer().refreshHoursValueForThisNodeAndParents(newNode);
getRenderer().refreshBudgetValueForThisNodeAndParents(newNode);
@ -267,8 +265,7 @@ public abstract class TreeController<T extends ITreeNode<T>> extends
nameTextbox = getRenderer().getNameTextbox(node);
} else {
// select the parent row to add new children ASAP
tree.setSelectedItem(getRenderer().getTreeitemForNode(
newNode.getParent().getThis()));
tree.setSelectedItem(getRenderer().getTreeitemForNode(newNode.getParent().getThis()));
}
} else {
getModel().addElement(name.getValue(), hours.getValue());

View file

@ -75,8 +75,7 @@ public class ExportTimesheetsToTimTest {
@Before
public void loadProperties() throws FileNotFoundException, IOException {
String filename = System.getProperty("user.dir")
+ "/../scripts/tim-connector/tim-conn.properties";
String filename = System.getProperty("user.dir") + "/../scripts/tim-connector/tim-conn.properties";
properties = new Properties();
properties.load(new FileInputStream(filename));
}
@ -159,12 +158,10 @@ public class ExportTimesheetsToTimTest {
@Test
@Transactional
@Ignore("Only working if you have a Tim server configured")
public void testExportTimesheetsToTimWithValidCodeAndOrder()
throws ConnectorException {
public void testExportTimesheetsToTimWithValidCodeAndOrder() throws ConnectorException {
Order order = givenOrder();
exportTimesheetsToTim.exportTimesheets("5160", order);
boolean result = exportTimesheetsToTim.getSynchronizationInfo()
.isSuccessful();
boolean result = exportTimesheetsToTim.getSynchronizationInfo().isSuccessful();
if ( !result ) {
fail("Export timesheets to tim failed");
}
@ -172,17 +169,13 @@ public class ExportTimesheetsToTimTest {
}
@Test(expected = ConnectorException.class)
@Transactional
public void testExportTimesheetsToTimWithInvalidCode()
throws ConnectorException {
public void testExportTimesheetsToTimWithInvalidCode() throws ConnectorException {
Order order = givenOrder();
exportTimesheetsToTim.exportTimesheets("", order);
}
@Test(expected = ConnectorException.class)
@Transactional
public void testExportTimesheetsToTimWithOrderNull()
throws ConnectorException {
public void testExportTimesheetsToTimWithOrderNull() throws ConnectorException {
exportTimesheetsToTim.exportTimesheets("5160", null);
}
}

View file

@ -162,8 +162,7 @@ public class OrderElementTreeModelTest {
workReportDAO.remove(each.getId());
}
List<org.libreplan.business.resources.entities.Resource> resources = resourceDAO
.findAll();
List<org.libreplan.business.resources.entities.Resource> resources = resourceDAO.findAll();
for (org.libreplan.business.resources.entities.Resource each : resources) {
resourceDAO.remove(each.getId());
}
@ -192,63 +191,50 @@ public class OrderElementTreeModelTest {
}
private void addCriterionRequirement(OrderElement orderElement) {
criterion = criterionDAO.findByNameAndType("Europe", "LOCATION")
.get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion);
criterion = criterionDAO.findByNameAndType("Europe", "LOCATION").get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement.create(criterion);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addAnotherCriterionRequirement(OrderElement orderElement) {
criterion2 = criterionDAO.findByNameAndType("Manager", "CATEGORY").get(
0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion2);
criterion2 = criterionDAO.findByNameAndType("Manager", "CATEGORY").get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement.create(criterion2);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addAnotherDifferentCriterionRequirement(
OrderElement orderElement) {
criterion3 = criterionDAO.findByNameAndType("Asia", "LOCATION")
.get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement
.create(criterion3);
private void addAnotherDifferentCriterionRequirement(OrderElement orderElement) {
criterion3 = criterionDAO.findByNameAndType("Asia", "LOCATION").get(0);
DirectCriterionRequirement directCriterionRequirement = DirectCriterionRequirement.create(criterion3);
orderElement.addCriterionRequirement(directCriterionRequirement);
}
private void addDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
addDirectAdvanceAssignment(orderElement, false);
}
private void addDirectAdvanceAssignment(OrderElement orderElement,
boolean spread)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(spread, HUNDRED);
private void addDirectAdvanceAssignment(OrderElement orderElement, boolean spread)
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment.create(spread, HUNDRED);
advanceType = PredefinedAdvancedTypes.PERCENTAGE.getType();
directAdvanceAssignment.setAdvanceType(advanceType);
orderElement.addAdvanceAssignment(directAdvanceAssignment);
}
private void addAnotherDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(false, HUNDRED);
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment.create(false, HUNDRED);
advanceType2 = PredefinedAdvancedTypes.UNITS.getType();
directAdvanceAssignment.setAdvanceType(advanceType2);
orderElement.addAdvanceAssignment(directAdvanceAssignment);
}
private void addAnotherDifferentDirectAdvanceAssignment(
OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(false, HUNDRED);
private void addAnotherDifferentDirectAdvanceAssignment(OrderElement orderElement)
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment.create(false, HUNDRED);
advanceType3 = PredefinedAdvancedTypes.SUBCONTRACTOR.getType();
directAdvanceAssignment.setAdvanceType(advanceType3);
orderElement.addAdvanceAssignment(directAdvanceAssignment);
@ -271,22 +257,20 @@ public class OrderElementTreeModelTest {
}
private void addMaterialAssignment(OrderElement orderElement) {
materialAssignment = MaterialAssignment.create(Material
.createUnvalidated("material-code", "material-description",
HUNDRED, false));
materialAssignment = MaterialAssignment.create(
Material.createUnvalidated("material-code", "material-description", HUNDRED, false));
orderElement.addMaterialAssignment(materialAssignment);
}
private void addQualityForm(OrderElement element) {
qualityForm = QualityForm.create("quality-form-name",
"quality-form-description");
qualityForm = QualityForm.create("quality-form-name", "quality-form-description");
element.addTaskQualityForm(qualityForm);
}
private void addTemplate(OrderElement element) {
template = createNiceMock(OrderElementTemplate.class);
expect(template.getName()).andReturn("order-element-template-name")
.anyTimes();
expect(template.getName()).andReturn("order-element-template-name").anyTimes();
replay(template);
element.initializeTemplate(template);
}
@ -294,8 +278,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkAddElementWithCriteriaAndAdvancesOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
addDirectAdvanceAssignment(order);
@ -308,28 +292,22 @@ public class OrderElementTreeModelTest {
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertIndirectCriterion(element.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(), criterion);
}
private static void assertDirectCriterion(
CriterionRequirement criterionRequirement, Criterion criterion) {
private static void assertDirectCriterion(CriterionRequirement criterionRequirement, Criterion criterion) {
assertCriterion(criterionRequirement, criterion, true);
}
private static void assertIndirectCriterion(
CriterionRequirement criterionRequirement, Criterion criterion) {
private static void assertIndirectCriterion(CriterionRequirement criterionRequirement, Criterion criterion) {
assertCriterion(criterionRequirement, criterion, false);
}
private static void assertCriterion(
CriterionRequirement criterionRequirement, Criterion criterion,
boolean direct) {
private static void assertCriterion(CriterionRequirement criterionRequirement,
Criterion criterion, boolean direct) {
if ( direct ) {
assertTrue(criterionRequirement instanceof DirectCriterionRequirement);
} else {
@ -342,8 +320,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkRemoveElementWithCriteriaAndAdvancesOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
addCriterionRequirement(order);
@ -361,8 +339,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkRemoveElementWithCriteriaAndAdvancesOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
@ -381,8 +359,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkAddCriterionOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
@ -391,43 +369,36 @@ public class OrderElementTreeModelTest {
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertDirectCriterion(element.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(), criterion);
}
@Test
@Transactional
public void checkAddCriterionOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
addCriterionRequirement(order);
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion);
assertDirectCriterion(order.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertIndirectCriterion(element.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(), criterion);
}
@Test
@Transactional
public void checkAddAssignmentOnChild()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
@ -441,8 +412,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkAddAdvanceOnParent()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) model.getRoot().getChildren().get(0);
@ -456,8 +427,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkAddElementOnOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
@ -470,38 +441,34 @@ public class OrderElementTreeModelTest {
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion);
assertDirectCriterion(order.getCriterionRequirements().iterator().next(), criterion);
assertThat(order.getWorkHours(), equalTo(150));
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertIndirectCriterion(container.getCriterionRequirements().iterator().next(), criterion);
assertNotNull(container.getIndirectAdvanceAssignment(advanceType));
assertThat(container.getWorkHours(), equalTo(150));
assertThat(container.getChildren().size(), equalTo(2));
for (OrderElement each : container.getChildren()) {
if ( each.getName().equals("") ) {
assertThat(each.getCriterionRequirements().size(), equalTo(2));
assertThat(each.getDirectAdvanceAssignments().size(),
equalTo(1));
assertNotNull(each
.getDirectAdvanceAssignmentByType(advanceType));
assertThat(each.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(each.getDirectAdvanceAssignmentByType(advanceType));
assertThat(each.getWorkHours(), equalTo(100));
assertThat(element.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(2));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
} else if ( each.getName().equals("element2") ) {
assertThat(each.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(each.getCriterionRequirements()
.iterator().next(), criterion);
assertIndirectCriterion(each.getCriterionRequirements().iterator().next(), criterion);
assertTrue(each.getDirectAdvanceAssignments().isEmpty());
assertThat(each.getWorkHours(), equalTo(50));
assertThat(each.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(each.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(),
assertThat(each.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(
each.getHoursGroups().get(0).getCriterionRequirements().iterator().next(),
criterion);
} else {
fail("Unexpected OrderElment name: " + each.getName());
@ -512,8 +479,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkAddElementOnOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
@ -531,17 +498,17 @@ public class OrderElementTreeModelTest {
assertThat(order.getWorkHours(), equalTo(300));
assertThat(container.getChildren().size(), equalTo(3));
for (OrderElement each : container.getChildren()) {
if ( each.getName().equals("element3") ) {
assertThat(each.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement criterionRequirement : each
.getCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : each.getCriterionRequirements()) {
assertTrue(criterionRequirement instanceof IndirectCriterionRequirement);
}
assertTrue(each.getDirectAdvanceAssignments().isEmpty());
assertThat(each.getWorkHours(), equalTo(150));
assertThat(element.getHoursGroups().get(0)
.getCriterionRequirements().size(), equalTo(2));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
}
}
}
@ -549,8 +516,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkRemoveElementOnOnlyOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
model.addElementAt(element, "element2", 50);
@ -623,39 +590,41 @@ public class OrderElementTreeModelTest {
// * directAdvanceAssignments
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element.getDirectAdvanceAssignmentByType(advanceType2));
assertThat(element.getDirectAdvanceAssignmentByType(advanceType2)
.getOrderElement(), equalTo((OrderElement) element));
assertThat(element.getDirectAdvanceAssignmentByType(advanceType2).getOrderElement(),
equalTo((OrderElement) element));
// * materialAssignments
assertThat(element.getMaterialAssignments().size(), equalTo(1));
assertThat(element.getMaterialAssignments().iterator().next()
.getMaterial(), equalTo(materialAssignment.getMaterial()));
assertThat(element.getMaterialAssignments().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
assertThat(element.getMaterialAssignments().iterator().next().getMaterial(),
equalTo(materialAssignment.getMaterial()));
assertThat(element.getMaterialAssignments().iterator().next().getOrderElement(),
equalTo((OrderElement) element));
// * labels
assertThat(element.getLabels().size(), equalTo(1));
assertThat(element.getLabels().iterator().next(), equalTo(label));
assertThat(element.getLabels().iterator().next().getType(),
equalTo(label.getType()));
assertThat(element.getLabels().iterator().next().getType(), equalTo(label.getType()));
// * taskQualityForms
assertThat(element.getQualityForms().size(), equalTo(1));
assertThat(element.getQualityForms().iterator().next(),
equalTo(qualityForm));
assertThat(element.getTaskQualityForms().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
assertThat(element.getQualityForms().iterator().next(), equalTo(qualityForm));
assertThat(element.getTaskQualityForms().iterator().next().getOrderElement(), equalTo((OrderElement) element));
// * criterionRequirements
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion2);
assertThat(element.getCriterionRequirements().iterator().next()
.getOrderElement(), equalTo((OrderElement) element));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion2);
assertDirectCriterion(element.getCriterionRequirements().iterator().next(), criterion2);
assertThat(element.getCriterionRequirements().iterator().next().getOrderElement(),
equalTo((OrderElement) element));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(
element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(),
criterion2);
// * template
assertNotNull(element.getTemplate());
@ -668,8 +637,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkPreservationOfInvalidatedIndirectCriterionRequirementInToLeaf()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
addCriterionRequirement(order);
model.addElement("element", 100);
@ -679,10 +648,10 @@ public class OrderElementTreeModelTest {
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
model.removeNode(container.getChildren().iterator().next());
IndirectCriterionRequirement indirectCriterionRequirement = (IndirectCriterionRequirement) container
.getCriterionRequirements().iterator().next();
assertTrue(indirectCriterionRequirement.getCriterion().isEquivalent(
criterion));
IndirectCriterionRequirement indirectCriterionRequirement =
(IndirectCriterionRequirement) container.getCriterionRequirements().iterator().next();
assertTrue(indirectCriterionRequirement.getCriterion().isEquivalent(criterion));
indirectCriterionRequirement.setValid(false);
addAnotherCriterionRequirement(container);
@ -693,6 +662,7 @@ public class OrderElementTreeModelTest {
element = (OrderLine) order.getChildren().get(0);
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
@ -704,10 +674,9 @@ public class OrderElementTreeModelTest {
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
assertFalse(each.isValid());
@ -723,13 +692,14 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkIndentOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if ( each.getName().equals("element") ) {
element = (OrderLine) each;
@ -756,29 +726,29 @@ public class OrderElementTreeModelTest {
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertTrue(element.getCriterionRequirements().isEmpty());
assertTrue(element.getHoursGroups().get(0).getCriterionRequirements()
.isEmpty());
assertTrue(element.getHoursGroups().get(0).getCriterionRequirements().isEmpty());
assertNotNull(element2.getAdvanceAssignmentByType(advanceType));
assertThat(element2.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element2.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element2.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertDirectCriterion(element2.getCriterionRequirements().iterator().next(), criterion);
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(
element2.getHoursGroups().get(0).getCriterionRequirements().iterator().next(),
criterion);
}
@Test
@Transactional
public void checkIndentOnOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if ( each.getName().equals("element") ) {
element = (OrderLine) each;
@ -803,30 +773,30 @@ public class OrderElementTreeModelTest {
assertNotNull(element.getAdvanceAssignmentByType(advanceType));
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertDirectCriterion(element.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(
element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(),
criterion);
assertTrue(element2.getDirectAdvanceAssignments().isEmpty());
assertTrue(element2.getCriterionRequirements().isEmpty());
assertTrue(element2.getHoursGroups().get(0).getCriterionRequirements()
.isEmpty());
assertTrue(element2.getHoursGroups().get(0).getCriterionRequirements().isEmpty());
}
@Test
@Transactional
public void checkIndentOnOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElementAt(order.getChildren().get(0), "element2", 50);
model.addElement("element3", 30);
OrderLineGroup container = null;
OrderLine element3 = null;
for (OrderElement each : order.getChildren()) {
if ( each.getName().equals("element") ) {
container = (OrderLineGroup) each;
@ -846,29 +816,29 @@ public class OrderElementTreeModelTest {
assertNotNull(container.getAdvanceAssignmentByType(advanceType));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertDirectCriterion(container.getCriterionRequirements().iterator().next(), criterion);
assertTrue(element3.getDirectAdvanceAssignments().isEmpty());
assertThat(element3.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element3.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(container.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertDirectCriterion(container.getCriterionRequirements().iterator().next(), criterion);
assertThat(element3.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(
container.getHoursGroups().get(0).getCriterionRequirements().iterator().next(),
criterion);
}
@Test
@Transactional
public void checkUnindentOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if ( each.getName().equals("element") ) {
element = (OrderLine) each;
@ -903,12 +873,12 @@ public class OrderElementTreeModelTest {
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element.getAdvanceAssignmentByType(advanceType2));
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertNotNull(element2.getAdvanceAssignmentByType(advanceType));
assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) ) {
assertTrue(each instanceof DirectCriterionRequirement);
@ -919,10 +889,8 @@ public class OrderElementTreeModelTest {
}
}
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if ((each.getCriterion().isEquivalent(criterion) || each
.getCriterion().isEquivalent(criterion2))) {
for (CriterionRequirement each : element2.getHoursGroups().get(0).getCriterionRequirements()) {
if ( (each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion2)) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -933,13 +901,14 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineWithCriteriaAndAdvancesToOrderLineWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElement("element2", 50);
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : order.getChildren()) {
if ( each.getName().equals("element") ) {
element = (OrderLine) each;
@ -964,8 +933,7 @@ public class OrderElementTreeModelTest {
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion3);
assertDirectCriterion(order.getCriterionRequirements().iterator().next(), criterion3);
OrderLineGroup container = (OrderLineGroup) order.getChildren().get(0);
assertTrue(container.getDirectAdvanceAssignments().isEmpty());
@ -973,11 +941,11 @@ public class OrderElementTreeModelTest {
assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
assertNull(container.getIndirectAdvanceAssignment(advanceType3));
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion3);
assertIndirectCriterion(container.getCriterionRequirements().iterator().next(), criterion3);
assertNotNull(element.getAdvanceAssignmentByType(advanceType));
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) ) {
assertTrue(each instanceof DirectCriterionRequirement);
@ -987,12 +955,10 @@ public class OrderElementTreeModelTest {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -1001,6 +967,7 @@ public class OrderElementTreeModelTest {
assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion2) ) {
assertTrue(each instanceof DirectCriterionRequirement);
@ -1010,12 +977,10 @@ public class OrderElementTreeModelTest {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion2)
|| each.getCriterion().isEquivalent(criterion3)) {
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion2) || each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -1026,8 +991,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineWithCriteriaAndAdvancesToOrderLineGroupWithCriteriaAndAdvances()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
model.addElementAt(order.getChildren().get(0), "element2", 50);
@ -1035,6 +1000,7 @@ public class OrderElementTreeModelTest {
OrderLine element = null;
OrderLine element2 = null;
for (OrderElement each : container.getChildren()) {
if ( each.getName().equals("") ) {
element = (OrderLine) each;
@ -1061,14 +1027,14 @@ public class OrderElementTreeModelTest {
assertNotNull(order.getIndirectAdvanceAssignment(advanceType));
assertNotNull(order.getIndirectAdvanceAssignment(advanceType2));
assertThat(order.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(order.getCriterionRequirements().iterator()
.next(), criterion3);
assertDirectCriterion(order.getCriterionRequirements().iterator().next(), criterion3);
assertThat(container.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(container.getDirectAdvanceAssignmentByType(advanceType));
assertNotNull(container.getIndirectAdvanceAssignment(advanceType2));
assertNull(container.getIndirectAdvanceAssignment(advanceType3));
assertThat(container.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : container.getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
@ -1081,20 +1047,18 @@ public class OrderElementTreeModelTest {
assertTrue(element.getDirectAdvanceAssignments().isEmpty());
assertThat(element.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
if ( each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -1103,23 +1067,23 @@ public class OrderElementTreeModelTest {
assertNotNull(element2.getAdvanceAssignmentByType(advanceType2));
assertThat(element2.getCriterionRequirements().size(), equalTo(3));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion2) ) {
assertTrue(each instanceof DirectCriterionRequirement);
} else if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion3)) {
} else if ( each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(3));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion2)
|| each.getCriterion().isEquivalent(criterion3)) {
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(3));
for (CriterionRequirement each : element2.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) ||
each.getCriterion().isEquivalent(criterion2) ||
each.getCriterion().isEquivalent(criterion3) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -1357,8 +1321,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineWithAdvanceToOrderLineGroupWithSameAdvanceType()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWithContainerAndTask();
addDirectAdvanceAssignment(container);
@ -1391,8 +1355,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineWithAdvanceToOrderLineInGroupWithSameAdvanceType()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWithContainerAndTask();
addDirectAdvanceAssignment(container);
@ -1425,8 +1389,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineGroupWithAdvanceToOrderLineGroupWithSameAdvance()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWithContainerAndContainer();
addDirectAdvanceAssignment(container);
@ -1469,8 +1433,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineGroupWithAdvanceToOrderLineInGroupWithSameAdvance()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWithContainerAndContainer();
addDirectAdvanceAssignment(container);
@ -1513,8 +1477,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineGroupWithAdvanceOnChildToOrderLineGroupWithSameAdvance()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWithContainerAndContainer();
addDirectAdvanceAssignment(container);
@ -1558,8 +1522,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkMoveOrderLineGroupWithAdvanceOnChildToOrderLineInGroupWithSameAdvance()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWithContainerAndContainer();
addDirectAdvanceAssignment(container);
@ -1585,8 +1549,7 @@ public class OrderElementTreeModelTest {
assertNull(element.getAdvanceAssignmentByType(advanceType2));
assertTrue(container2.getDirectAdvanceAssignments().isEmpty());
assertThat(container2.getIndirectAdvanceAssignments().size(),
equalTo(2));
assertThat(container2.getIndirectAdvanceAssignments().size(), equalTo(2));
assertNull(container2.getAdvanceAssignmentByType(advanceType));
assertNotNull(container2.getAdvanceAssignmentByType(advanceType2));
assertNotNull(container2.getIndirectAdvanceAssignment(advanceType2));
@ -1615,16 +1578,12 @@ public class OrderElementTreeModelTest {
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertDirectCriterion(container.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertIndirectCriterion(element.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(), criterion);
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
@ -1637,12 +1596,9 @@ public class OrderElementTreeModelTest {
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion2)) {
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion2) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -1665,16 +1621,12 @@ public class OrderElementTreeModelTest {
assertTrue(order.getCriterionRequirements().isEmpty());
assertThat(container.getCriterionRequirements().size(), equalTo(1));
assertDirectCriterion(container.getCriterionRequirements().iterator()
.next(), criterion);
assertDirectCriterion(container.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getCriterionRequirements().iterator()
.next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0)
.getCriterionRequirements().iterator().next(), criterion);
assertIndirectCriterion(element.getCriterionRequirements().iterator().next(), criterion);
assertThat(element.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(1));
assertIndirectCriterion(element.getHoursGroups().get(0).getCriterionRequirements().iterator().next(), criterion);
assertThat(element2.getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getCriterionRequirements()) {
@ -1687,12 +1639,9 @@ public class OrderElementTreeModelTest {
}
}
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements()
.size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0)
.getCriterionRequirements()) {
if (each.getCriterion().isEquivalent(criterion)
|| each.getCriterion().isEquivalent(criterion2)) {
assertThat(element2.getHoursGroups().get(0).getCriterionRequirements().size(), equalTo(2));
for (CriterionRequirement each : element2.getHoursGroups().get(0).getCriterionRequirements()) {
if ( each.getCriterion().isEquivalent(criterion) || each.getCriterion().isEquivalent(criterion2) ) {
assertTrue(each instanceof IndirectCriterionRequirement);
} else {
fail("Unexpected criterion: " + each.getCriterion());
@ -2015,7 +1964,7 @@ public class OrderElementTreeModelTest {
} else if ( each.getName().equals("element2") ) {
element2 = (OrderLine) each;
} else {
fail("Unexpected OrderElment name: " + each.getName());
fail("Unexpected OrderElement name: " + each.getName());
}
}
@ -2025,8 +1974,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkRemoveElementWithAdvanceOnChildWhichSpread()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
createTreeWith2Task();
assertTrue(order.getIndirectAdvanceAssignments().isEmpty());
@ -2057,8 +2006,8 @@ public class OrderElementTreeModelTest {
@Test
@Transactional
public void checkChildrenAdvanceIsCreatedAndMarkedAsSpreadInOrder()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
throws DuplicateValueTrueReportGlobalAdvanceException, DuplicateAdvanceAssignmentForOrderElementException {
model.addElement("element", 100);
OrderLine element = (OrderLine) order.getChildren().get(0);
@ -2074,8 +2023,7 @@ public class OrderElementTreeModelTest {
assertThat(element.getDirectAdvanceAssignments().size(), equalTo(1));
assertNotNull(element.getAdvanceAssignmentByType(advanceType));
assertNotNull(element.getReportGlobalAdvanceAssignment());
assertTrue(element.getAdvanceAssignmentByType(advanceType)
.getReportGlobalAdvance());
assertTrue(element.getAdvanceAssignmentByType(advanceType).getReportGlobalAdvance());
}
}

View file

@ -97,8 +97,7 @@ import org.zkoss.zk.ui.Desktop;
WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE })
public class OrderModelTest {
public static OrderVersion setupVersionUsing(
IScenarioManager scenarioManager, Order order) {
public static OrderVersion setupVersionUsing(IScenarioManager scenarioManager, Order order) {
Scenario current = scenarioManager.getCurrent();
OrderVersion result = OrderVersion.createInitialVersion(current);
order.setVersionForScenario(current, result);
@ -168,13 +167,11 @@ public class OrderModelTest {
}
private PlanningState createPlanningStateFor(final Order newOrder) {
return adHocTransaction
.runOnAnotherReadOnlyTransaction(new IOnTransaction<PlanningState>() {
return adHocTransaction.runOnAnotherReadOnlyTransaction(new IOnTransaction<PlanningState>() {
@Override
public PlanningState execute() {
return planningStateCreator.createOn(mockDesktop(),
newOrder);
return planningStateCreator.createOn(mockDesktop(), newOrder);
}
});
}
@ -186,25 +183,29 @@ public class OrderModelTest {
order.setName("name");
order.setResponsible("responsible");
order.setCode("code-" + UUID.randomUUID());
BaseCalendar calendar = adHocTransaction
.runOnReadOnlyTransaction(new IOnTransaction<BaseCalendar>() {
BaseCalendar calendar = adHocTransaction.runOnReadOnlyTransaction(new IOnTransaction<BaseCalendar>() {
@Override
public BaseCalendar execute() {
BaseCalendar result = configurationDAO
.getConfigurationWithReadOnlyTransaction()
.getDefaultCalendar();
BaseCalendar result =
configurationDAO.getConfigurationWithReadOnlyTransaction().getDefaultCalendar();
BaseCalendarModel.forceLoadBaseCalendar(result);
return result;
}
});
order.setCalendar(calendar);
return order;
}
private ExternalCompany createValidExternalCompany() {
ExternalCompany externalCompany = ExternalCompany.create(UUID
.randomUUID().toString(), UUID.randomUUID().toString());
ExternalCompany externalCompany = ExternalCompany.create(
UUID.randomUUID().toString(),
UUID.randomUUID().toString());
externalCompanyDAO.save(externalCompany);
return externalCompany;
}
@ -312,8 +313,7 @@ public class OrderModelTest {
@Test(expected = ValidationException.class)
@Transactional
@Ignore("FIXME pending review after rename to libreplan")
public void shouldSendValidationExceptionIfEndDateIsBeforeThanStartingDate()
throws ValidationException {
public void shouldSendValidationExceptionIfEndDateIsBeforeThanStartingDate() throws ValidationException {
Order order = createValidOrder();
order.setDeadline(year(0));
orderModel.setPlanningState(createPlanningStateFor(order));
@ -332,14 +332,12 @@ public class OrderModelTest {
@Test
@Ignore("FIXME pending review after rename to libreplan")
public void testOrderPreserved() throws ValidationException,
InstanceNotFoundException {
public void testOrderPreserved() throws ValidationException, InstanceNotFoundException {
final Order order = createValidOrder();
orderModel.setPlanningState(createPlanningStateFor(order));
final OrderElement[] containers = new OrderLineGroup[10];
for (int i = 0; i < containers.length; i++) {
containers[i] = adHocTransaction
.runOnTransaction(new IOnTransaction<OrderLineGroup>() {
containers[i] = adHocTransaction.runOnTransaction(new IOnTransaction<OrderLineGroup>() {
@Override
public OrderLineGroup execute() {
return OrderLineGroup.create();
@ -372,26 +370,24 @@ public class OrderModelTest {
try {
Order reloaded = orderDAO.find(order.getId());
List<OrderElement> elements = reloaded.getOrderElements();
for (OrderElement orderElement : elements) {
assertThat(((OrderLineGroup) orderElement)
.getIndirectAdvanceAssignments().size(),
equalTo(2));
assertThat(orderElement.getIndirectAdvanceAssignments().size(), equalTo(2));
}
for (int i = 0; i < containers.length; i++) {
assertThat(elements.get(i).getId(),
equalTo(containers[i].getId()));
assertThat(elements.get(i).getId(), equalTo(containers[i].getId()));
}
OrderLineGroup container = (OrderLineGroup) reloaded
.getOrderElements().iterator().next();
OrderLineGroup container = (OrderLineGroup) reloaded.getOrderElements().iterator().next();
List<OrderElement> children = container.getChildren();
for (int i = 0; i < orderElements.length; i++) {
assertThat(children.get(i).getId(),
equalTo(orderElements[i].getId()));
assertThat(children.get(i).getId(), equalTo(orderElements[i].getId()));
}
for (int i = 1; i < containers.length; i++) {
OrderLineGroup orderLineGroup = (OrderLineGroup) containers[i];
assertThat(orderLineGroup.getChildren().size(),
equalTo(1));
assertThat(orderLineGroup.getChildren().size(), equalTo(1));
}
return null;
} catch (Exception e) {

View file

@ -22,22 +22,77 @@
package org.libreplan.web.planner.chart;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.libreplan.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE;
import static org.libreplan.web.WebappGlobalNames.WEBAPP_SPRING_CONFIG_FILE;
import static org.libreplan.web.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_FILE;
import static org.libreplan.web.test.WebappGlobalNames.WEBAPP_SPRING_CONFIG_TEST_FILE;
import static org.libreplan.web.test.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import org.easymock.EasyMock;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.libreplan.business.IDataBootstrap;
import org.libreplan.business.calendars.daos.IBaseCalendarDAO;
import org.libreplan.business.calendars.entities.BaseCalendar;
import org.libreplan.business.common.IAdHocTransactionService;
import org.libreplan.business.common.IOnTransaction;
import org.libreplan.business.common.daos.IConfigurationDAO;
import org.libreplan.business.orders.entities.HoursGroup;
import org.libreplan.business.orders.entities.Order;
import org.libreplan.business.orders.entities.OrderElement;
import org.libreplan.business.orders.entities.OrderLine;
import org.libreplan.business.planner.entities.IOrderEarnedValueCalculator;
import org.libreplan.business.planner.entities.SpecificDayAssignmentsContainer;
import org.libreplan.business.planner.entities.SpecificResourceAllocation;
import org.libreplan.business.planner.entities.Task;
import org.libreplan.business.scenarios.entities.Scenario;
import org.libreplan.business.workingday.ResourcesPerDay;
import org.libreplan.web.calendars.BaseCalendarModel;
import org.libreplan.web.calendars.IBaseCalendarModel;
import org.libreplan.web.common.IConfigurationModel;
import org.libreplan.web.orders.IOrderModel;
import org.libreplan.web.planner.order.PlanningStateCreator;
import org.libreplan.web.planner.order.PlanningStateCreator.PlanningState;
import org.libreplan.web.resources.worker.IAssignedCriterionsModel;
import org.libreplan.web.resources.worker.IWorkerModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.zkforge.timeplot.Timeplot;
import org.zkoss.ganttz.util.Interval;
import org.zkoss.zk.ui.Desktop;
import javax.annotation.Resource;
/**
* Tests for {@link ChartFiller}
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
BUSINESS_SPRING_CONFIG_FILE,
WEBAPP_SPRING_CONFIG_FILE,
WEBAPP_SPRING_CONFIG_TEST_FILE,
WEBAPP_SPRING_SECURITY_CONFIG_FILE,
WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE
})
@Transactional
public class ChartFillerTest {
private ChartFiller chartFiller = new ChartFiller() {
@ -64,26 +119,207 @@ public class ChartFillerTest {
@Test
public void testCalculatedValueForEveryDay() {
SortedMap<LocalDate, BigDecimal> result = chartFiller
.calculatedValueForEveryDay(givenExampleMap(), START_DAY,
FINISH_DAY);
SortedMap<LocalDate, BigDecimal> result =
chartFiller.calculatedValueForEveryDay(givenExampleMap(), START_DAY, FINISH_DAY);
assertThat(result.get(START_DAY), equalTo(BigDecimal.ZERO.setScale(2)));
assertThat(result.get(START_DAY.plusDays(1)),
equalTo(new BigDecimal(25).setScale(2)));
assertThat(result.get(START_DAY.plusDays(1)), equalTo(new BigDecimal(25).setScale(2)));
assertThat(result.get(FIRST_DAY), equalTo(new BigDecimal(100)
.setScale(2)));
assertThat(result.get(FIRST_DAY.plusDays(1)), equalTo(new BigDecimal(
105).setScale(2)));
assertThat(result.get(FIRST_DAY), equalTo(new BigDecimal(100).setScale(2)));
assertThat(result.get(FIRST_DAY.plusDays(1)), equalTo(new BigDecimal(105).setScale(2)));
assertThat(result.get(LAST_DAY), equalTo(new BigDecimal(150)
.setScale(2)));
assertThat(result.get(LAST_DAY.plusDays(1)),
equalTo(new BigDecimal(150).setScale(2)));
assertThat(result.get(LAST_DAY), equalTo(new BigDecimal(150).setScale(2)));
assertThat(result.get(LAST_DAY.plusDays(1)), equalTo(new BigDecimal(150).setScale(2)));
assertThat(result.get(FINISH_DAY), equalTo(new BigDecimal(150)
.setScale(2)));
assertThat(result.get(FINISH_DAY), equalTo(new BigDecimal(150).setScale(2)));
}
@Resource
private IDataBootstrap defaultAdvanceTypesBootstrapListener;
@Resource
private IDataBootstrap scenariosBootstrap;
@Resource
private IDataBootstrap configurationBootstrap;
@Autowired
private IAdHocTransactionService transactionService;
@Before
public void loadRequiredaData() {
IOnTransaction<Void> load = new IOnTransaction<Void>() {
@Override
public Void execute() {
defaultAdvanceTypesBootstrapListener.loadRequiredData();
configurationBootstrap.loadRequiredData();
scenariosBootstrap.loadRequiredData();
return null;
}
};
transactionService.runOnAnotherTransaction(load);
}
// Testing BAC values
// 1. Create Worker
// 2. Create Project
// 3. Create 2 Tasks
// 4. Assign Resources to Tasks
// 5. Check BAC values
@Resource
IBaseCalendarModel baseCalendarModel;
@Autowired
IBaseCalendarDAO baseCalendarDAO;
@Autowired
IConfigurationModel configurationModel;
@Test
public void testBAC(){
createAndSaveWorker();
createAndSaveProject();
createAndSaveTwoTasksForProject();
assignAndSaveResourcesForTasks();
BigDecimal BAC = earnedValueCalculator.getBudgetAtCompletion(orderModel.getOrder());
assertEquals(BAC, new BigDecimal(50));
}
// For creating worker
@Autowired
IWorkerModel workerModel;
@Autowired
IAssignedCriterionsModel assignedCriterionsModel;
private void createAndSaveWorker() {
workerModel.prepareForCreate();
workerModel.getWorker().setFirstName("Neil");
workerModel.getWorker().setSurname("Armstrong");
workerModel.getWorker().setNif("666");
workerModel.getAssignedCriterionsModel().prepareForCreate(workerModel.getWorker());
workerModel.save();
}
// For creating project
@Autowired
IOrderModel orderModel;
@Autowired
private PlanningStateCreator planningStateCreator;
@Autowired
private IAdHocTransactionService adHocTransaction;
@Autowired
private IConfigurationDAO configurationDAO;
private void createAndSaveProject(){
final Order project = Order.create();
project.setDescription("Goal of project: do not be thirsty");
// Create initDate
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, 2016);
project.setInitDate(calendar.getTime());
project.setName("To be not thirsty");
project.setResponsible("human");
project.setCode("code-" + UUID.randomUUID());
BaseCalendar baseCalendar = adHocTransaction.runOnReadOnlyTransaction(new IOnTransaction<BaseCalendar>() {
@Override
public BaseCalendar execute() {
BaseCalendar result =
configurationDAO.getConfigurationWithReadOnlyTransaction().getDefaultCalendar();
BaseCalendarModel.forceLoadBaseCalendar(result);
return result;
}
});
project.setCalendar(baseCalendar);
// Create planningState
PlanningState planningState =
adHocTransaction.runOnAnotherReadOnlyTransaction(new IOnTransaction<PlanningState>() {
@Override
public PlanningStateCreator.PlanningState execute() {
return planningStateCreator.createOn(EasyMock.createNiceMock(Desktop.class), project);
}
});
orderModel.setPlanningState(planningState);
orderModel.save();
}
private void createAndSaveTwoTasksForProject(){
OrderElement task1 = OrderLine.createOrderLineWithUnfixedPercentage(10);
task1.setName("Take bottle");
task1.setCode(UUID.randomUUID().toString());
for (HoursGroup current : task1.getHoursGroups()) current.setCode(UUID.randomUUID().toString());
OrderElement task2 = OrderLine.createOrderLineWithUnfixedPercentage(40);
task2.setName("Drink water");
task2.setCode(UUID.randomUUID().toString());
for (HoursGroup current : task2.getHoursGroups()) current.setCode(UUID.randomUUID().toString());
orderModel.getOrder().add(task1);
orderModel.getOrder().add(task2);
orderModel.save();
}
// For assigning resources to tasks
@Autowired
private IOrderEarnedValueCalculator earnedValueCalculator;
private void assignAndSaveResourcesForTasks(){
// Task 1
Task task1 = (Task) orderModel.getOrder().getAllChildrenAssociatedTaskElements().get(0);
SpecificResourceAllocation specificResourceAllocation1 = SpecificResourceAllocation.create(task1);
specificResourceAllocation1.setResource(workerModel.getWorker());
Scenario orderScenario1 = null;
for (Scenario scenario : orderModel.getOrder().getScenarios().keySet()) {
orderScenario1 = scenario;
}
specificResourceAllocation1.copyAssignments(orderScenario1, orderScenario1);
specificResourceAllocation1.allocate(ResourcesPerDay.amount(1));
for (SpecificDayAssignmentsContainer item : specificResourceAllocation1.getSpecificDayAssignmentsContainers()) {
item.addAll(specificResourceAllocation1.getAssignments());
}
task1.addResourceAllocation(specificResourceAllocation1);
// Task 2
Task task2 = (Task) orderModel.getOrder().getAllChildrenAssociatedTaskElements().get(1);
SpecificResourceAllocation specificResourceAllocation2 = SpecificResourceAllocation.create(task2);
specificResourceAllocation2.setResource(workerModel.getWorker());
Scenario orderScenario2 = null;
for (Scenario scenario : orderModel.getOrder().getScenarios().keySet()) {
orderScenario2 = scenario;
}
specificResourceAllocation2.copyAssignments(orderScenario2, orderScenario2);
specificResourceAllocation2.allocate(ResourcesPerDay.amount(1));
for (SpecificDayAssignmentsContainer item : specificResourceAllocation2.getSpecificDayAssignmentsContainers()) {
item.addAll(specificResourceAllocation2.getAssignments());
}
task2.addResourceAllocation(specificResourceAllocation2);
}
}

View file

@ -68,9 +68,7 @@ public class WorkerModelTest {
private IResourceDAO resourceDAO;
@Test
@Transactional
public void testWorkerValid() throws ValidationException,
InstanceNotFoundException {
public void testWorkerValid() throws ValidationException, InstanceNotFoundException {
IResourceDAO resourceDAOMock = createMock(IResourceDAO.class);
ICriterionDAO criterionServiceMock = createMock(ICriterionDAO.class);
@ -78,20 +76,17 @@ public class WorkerModelTest {
workerToReturn.setFirstName("firstName");
workerToReturn.setSurname("surname");
workerToReturn.setNif("232344243");
// expectations
List<Criterion> criterions = new ArrayList<Criterion>();
expect(
criterionServiceMock
.findByType(PredefinedCriterionTypes.LOCATION))
.andReturn(criterions).anyTimes();
expect(resourceDAOMock.find(workerToReturn.getId()))
.andReturn(workerToReturn);
expect(criterionServiceMock.findByType(PredefinedCriterionTypes.LOCATION)).andReturn(criterions).anyTimes();
expect(resourceDAOMock.find(workerToReturn.getId())).andReturn(workerToReturn);
resourceDAOMock.save(workerToReturn);
workerToReturn.checkNotOverlaps();
replay(resourceDAOMock, criterionServiceMock);
// perform actions
WorkerModel workerModel = new WorkerModel(resourceDAOMock,
criterionServiceMock);
WorkerModel workerModel = new WorkerModel(resourceDAOMock, criterionServiceMock);
workerModel.prepareEditFor(workerToReturn);
workerModel.save();
@ -100,20 +95,16 @@ public class WorkerModelTest {
@Ignore
@Test(expected = IllegalStateException.class)
@Transactional
public void testWorkerInvalid() throws ValidationException,
InstanceNotFoundException, IllegalStateException {
public void testWorkerInvalid() throws ValidationException, InstanceNotFoundException, IllegalStateException {
IResourceDAO resourceDAOMock = createMock(IResourceDAO.class);
ICriterionDAO criterionServiceMock = createMock(ICriterionDAO.class);
final Worker workerToReturn = Worker.create();
// expectations
List<Criterion> criterions = new ArrayList<Criterion>();
expect(
criterionServiceMock
.findByType(PredefinedCriterionTypes.LOCATION))
.andReturn(criterions).anyTimes();
expect(resourceDAOMock.find(workerToReturn.getId())).andReturn(
workerToReturn);
expect(criterionServiceMock.findByType(PredefinedCriterionTypes.LOCATION)).andReturn(criterions).anyTimes();
expect(resourceDAOMock.find(workerToReturn.getId())).andReturn(workerToReturn);
resourceDAOMock.save(workerToReturn);
expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
@ -124,9 +115,9 @@ public class WorkerModelTest {
}
});
replay(resourceDAOMock, criterionServiceMock);
// perform actions
WorkerModel workerModel = new WorkerModel(resourceDAOMock,
criterionServiceMock);
WorkerModel workerModel = new WorkerModel(resourceDAOMock, criterionServiceMock);
workerModel.prepareEditFor(workerToReturn);
workerModel.save();
}

View file

@ -29,8 +29,7 @@ package org.libreplan.web.test;
*/
public class WebappGlobalNames {
public final static String WEBAPP_SPRING_CONFIG_TEST_FILE =
"classpath:/libreplan-webapp-spring-config-test.xml";
public final static String WEBAPP_SPRING_CONFIG_TEST_FILE = "classpath:/libreplan-webapp-spring-config-test.xml";
public final static String WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE =
"classpath:/libreplan-webapp-spring-security-config-test.xml";