diff --git a/NEWS.rst b/NEWS.rst index f25e21154..33764cf2a 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -1712,7 +1712,7 @@ Changes * Use disabled textbox for capacity row in monthly timesheets * Set a pink background for days with zero capacity in the monthly timesheet * Fix align issues due to colspan in the first column of capacity and total rows -* Add capcity row to monthly timesheets +* Add capacity row to monthly timesheets * Add total row to monthly timesheets * Remove commented line * Add button to hide/show extra filtering options diff --git a/doc/src/user/en/21-communications.rst b/doc/src/user/en/21-communications.rst index 41a248464..c092e4260 100644 --- a/doc/src/user/en/21-communications.rst +++ b/doc/src/user/en/21-communications.rst @@ -3,7 +3,7 @@ Subcontractor work description It is possible to keep this field empty. -But if you do, you could get errors in communication functionality when multiple emtpy fields exist. +But if you do, you could get errors in communication functionality when multiple empty fields exist. We recommend to always use a unique work description. diff --git a/ganttzk/src/main/java/org/zkoss/ganttz/i18n/I18nHelper.java b/ganttzk/src/main/java/org/zkoss/ganttz/i18n/I18nHelper.java index bfa327554..9929fb621 100644 --- a/ganttzk/src/main/java/org/zkoss/ganttz/i18n/I18nHelper.java +++ b/ganttzk/src/main/java/org/zkoss/ganttz/i18n/I18nHelper.java @@ -50,8 +50,8 @@ public class I18nHelper { } - //TODO It should be changed since JDK9. /** + * TODO It should be changed since JDK9 * Use of '_' as an identifier might not be supported in releases after Java SE 8. * * @param str diff --git a/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceMeasurement.java b/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceMeasurement.java index 00afe9d8f..f2b55a450 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceMeasurement.java +++ b/libreplan-business/src/main/java/org/libreplan/business/advance/entities/AdvanceMeasurement.java @@ -36,19 +36,6 @@ import org.libreplan.business.planner.entities.consolidations.NonCalculatedConso public class AdvanceMeasurement extends BaseEntity { - public static AdvanceMeasurement create(LocalDate date, BigDecimal value) { - AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement(date, - value); - advanceMeasurement.setNewObject(true); - return advanceMeasurement; - } - - public static AdvanceMeasurement create() { - AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement(); - advanceMeasurement.setNewObject(true); - return advanceMeasurement; - } - private LocalDate date; private BigDecimal value; @@ -58,7 +45,7 @@ public class AdvanceMeasurement extends BaseEntity { private Date communicationDate; @Valid - private Set nonCalculatedConsolidatedValues = new HashSet(); + private Set nonCalculatedConsolidatedValues = new HashSet<>(); public AdvanceMeasurement() { } @@ -71,9 +58,20 @@ public class AdvanceMeasurement extends BaseEntity { } } + public static AdvanceMeasurement create(LocalDate date, BigDecimal value) { + AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement(date, value); + advanceMeasurement.setNewObject(true); + return advanceMeasurement; + } + + public static AdvanceMeasurement create() { + AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement(); + advanceMeasurement.setNewObject(true); + return advanceMeasurement; + } + public void setDate(LocalDate date) { - if ((date != null) && (this.date != null) - && (this.date.compareTo(date) != 0)) { + if ((date != null) && (this.date != null) && (this.date.compareTo(date) != 0)) { resetCommunicationDate(); } this.date = date; @@ -89,13 +87,13 @@ public class AdvanceMeasurement extends BaseEntity { if (value != null) { this.value.setScale(2, BigDecimal.ROUND_DOWN); } - if ((this.value != null) && (value != null) - && (this.value.compareTo(value) != 0)) { + + if ((this.value != null) && (value != null) && (this.value.compareTo(value) != 0)) { resetCommunicationDate(); } + if (advanceAssignment != null) { - advanceAssignment.getOrderElement() - .markAsDirtyLastAdvanceMeasurementForSpreading(); + advanceAssignment.getOrderElement().markAsDirtyLastAdvanceMeasurementForSpreading(); } } @@ -122,8 +120,8 @@ public class AdvanceMeasurement extends BaseEntity { } /** - * Just set the communication date if it was null. Otherwise - * keep the old value stored. + * Just set the communication date if it was null. + * Otherwise keep the old value stored. * * @param communicationDate */ @@ -131,14 +129,13 @@ public class AdvanceMeasurement extends BaseEntity { DirectAdvanceAssignment advanceAssignment = (DirectAdvanceAssignment) getAdvanceAssignment(); if (advanceAssignment.isFake()) { OrderElement orderElement = advanceAssignment.getOrderElement(); - Set directAdvanceAssignments = orderElement - .getAllDirectAdvanceAssignments(advanceAssignment - .getAdvanceType()); + + Set directAdvanceAssignments = + orderElement.getAllDirectAdvanceAssignments(advanceAssignment.getAdvanceType()); + for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) { - for (AdvanceMeasurement advanceMeasurement : directAdvanceAssignment - .getAdvanceMeasurements()) { - advanceMeasurement - .updateCommunicationDate(communicationDate); + for (AdvanceMeasurement advanceMeasurement : directAdvanceAssignment.getAdvanceMeasurements()) { + advanceMeasurement.updateCommunicationDate(communicationDate); } } } else { @@ -159,32 +156,26 @@ public class AdvanceMeasurement extends BaseEntity { } if (this.advanceAssignment instanceof DirectAdvanceAssignment) { - BigDecimal defaultMaxValue = ((DirectAdvanceAssignment) this.advanceAssignment) - .getMaxValue(); - return (this.value.compareTo(defaultMaxValue) <= 0); + BigDecimal defaultMaxValue = ((DirectAdvanceAssignment) this.advanceAssignment).getMaxValue(); + return this.value.compareTo(defaultMaxValue) <= 0; } return true; } @AssertTrue(message = "The current value must be less than the max value.") public boolean isValidPrecisionConstraint() { - if ((this.value == null) || (this.advanceAssignment == null) - || (this.advanceAssignment.getAdvanceType() == null)) { + if ((this.value == null) || (this.advanceAssignment == null) || (this.advanceAssignment.getAdvanceType() == null)) { return true; } - BigDecimal precision = this.advanceAssignment.getAdvanceType() - .getUnitPrecision(); + BigDecimal precision = this.advanceAssignment.getAdvanceType().getUnitPrecision(); BigDecimal result[] = value.divideAndRemainder(precision); BigDecimal zero = (BigDecimal.ZERO).setScale(4); - if (result[1].compareTo(zero) == 0) { - return true; - } - return false; + + return result[1].compareTo(zero) == 0; } - public void setNonCalculatedConsolidatedValues( - Set nonCalculatedConsolidatedValues) { + public void setNonCalculatedConsolidatedValues(Set nonCalculatedConsolidatedValues) { this.nonCalculatedConsolidatedValues = nonCalculatedConsolidatedValues; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java b/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java index a2160b248..6d706ce0b 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/VersionInformation.java @@ -30,7 +30,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * It contains the current version of project and implements of singleton pattern.
+ * It contains the current version of project and implements of singleton pattern. + *
* It also has a cached value with information about last project version published. * It checks the last version against a URL. * @@ -42,15 +43,16 @@ public class VersionInformation { private static final Log LOG = LogFactory.getLog(VersionInformation.class); /** - * URL with a text file only with last number version of LibrePlan + * URL with a text file only with last number version of LibrePlan. */ private static final String LIBREPLAN_VERSION_URL = "http://libreplan.org/VERSION"; /** - * Delay to wait till we check the URL again + * Delay to wait till we check the URL again. + * 1 Day. */ - private static final long DELAY_TO_CHECK_URL = 24 * 60 * 60 * 1000L; // 1 day + private static final long DELAY_TO_CHECK_URL = 24 * 60 * 60 * 1000L; private static final VersionInformation singleton = new VersionInformation(); @@ -69,14 +71,15 @@ public class VersionInformation { URL url = getURL(); String lastVersion = (new BufferedReader(new InputStreamReader(url.openStream()))).readLine(); if (projectVersion != null && lastVersion != null) { - newVersionCached = !projectVersion.equals(lastVersion); + Integer currentVersion = Integer.parseInt(projectVersion.replace(".", "")); + Integer versionFromURL = Integer.parseInt(lastVersion.replace(".", "")); + newVersionCached = versionFromURL > currentVersion; } } catch (MalformedURLException e) { LOG.warn("Problems generating URL to check LibrePlan version. MalformedURLException: " + e.getMessage()); } catch (IOException e) { - LOG.info( - "Could not check LibrePlan version information from " + - LIBREPLAN_VERSION_URL + ". IOException: " + e.getMessage()); + LOG.info("Could not check LibrePlan version information from " + + LIBREPLAN_VERSION_URL + ". IOException: " + e.getMessage()); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java b/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java index 624892527..8f69e85b6 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/common/daos/IntegrationEntityDAO.java @@ -28,7 +28,6 @@ import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.libreplan.business.common.IntegrationEntity; import org.libreplan.business.common.exceptions.InstanceNotFoundException; -import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -39,18 +38,17 @@ import org.springframework.transaction.annotation.Transactional; * @author Fernando Bellas Permuy */ public class IntegrationEntityDAO - extends GenericDAOHibernate implements IIntegrationEntityDAO { + extends GenericDAOHibernate + implements IIntegrationEntityDAO { @Override public boolean existsByCode(String code) { - try { findByCode(code); return true; } catch (InstanceNotFoundException e) { return false; } - } @Override @@ -64,17 +62,17 @@ public class IntegrationEntityDAO @Transactional(readOnly = true) public E findByCode(String code) throws InstanceNotFoundException { - if (StringUtils.isBlank(code)) { - throw new InstanceNotFoundException(null, - getEntityClass().getName()); + if (code == null || StringUtils.isBlank(code)) { + throw new InstanceNotFoundException(null, getEntityClass().getName()); } - E entity = (E) getSession().createCriteria(getEntityClass()).add( - Restrictions.eq("code", code.trim()).ignoreCase()).uniqueResult(); + E entity = (E) getSession() + .createCriteria(getEntityClass()) + .add(Restrictions.eq("code", code.trim()).ignoreCase()) + .uniqueResult(); if (entity == null) { - throw new InstanceNotFoundException( - code, getEntityClass().getName()); + throw new InstanceNotFoundException(code, getEntityClass().getName()); } else { return entity; } @@ -83,22 +81,17 @@ public class IntegrationEntityDAO @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) - public E findByCodeAnotherTransaction(String code) - throws InstanceNotFoundException { - + public E findByCodeAnotherTransaction(String code) throws InstanceNotFoundException { return findByCode(code); - } @Override public E findExistingEntityByCode(String code) { - try { return findByCode(code); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } - } @SuppressWarnings("unchecked") diff --git a/libreplan-business/src/main/java/org/libreplan/business/hibernate/notification/PredefinedDatabaseSnapshots.java b/libreplan-business/src/main/java/org/libreplan/business/hibernate/notification/PredefinedDatabaseSnapshots.java index 6806a4a2f..19c717feb 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/hibernate/notification/PredefinedDatabaseSnapshots.java +++ b/libreplan-business/src/main/java/org/libreplan/business/hibernate/notification/PredefinedDatabaseSnapshots.java @@ -80,6 +80,7 @@ import org.springframework.stereotype.Component; /** * @author Óscar González Fernández + * @author Vova Perebykivskyi */ @Component @Scope(BeanDefinition.SCOPE_SINGLETON) @@ -93,93 +94,131 @@ public class PredefinedDatabaseSnapshots { @Autowired private ISnapshotRefresherService snapshotRefresherService; + @Autowired + private ICriterionTypeDAO criterionTypeDAO; + + @Autowired + private ICriterionDAO criterionDAO; + + @Autowired + private ILabelTypeDAO labelTypeDAO; + + @Autowired + private ILabelDAO labelDAO; + + @Autowired + private IWorkerDAO workerDAO; + + @Autowired + private ICostCategoryDAO costCategoryDAO; + + @Autowired + private IResourceDAO resourceDAO; + + @Autowired + private IExternalCompanyDAO externalCompanyDAO; + + @Autowired + private IOrderDAO orderDAO; + + @Autowired + private IDayAssignmentDAO dayAssignmentDAO; + + @Autowired + private IScenarioManager scenarioManager; + + @Autowired + private IWorkReportLineDAO workReportLineDAO; + + @Autowired + private ICostCalculator hoursCostCalculator; + + @Autowired + private ITaskElementDAO taskElementDAO; + private IAutoUpdatedSnapshot>> criterionsMap; + private IAutoUpdatedSnapshot>> labelsMap; + + private IAutoUpdatedSnapshot> listWorkers; + + private IAutoUpdatedSnapshot> listCostCategories; + + private IAutoUpdatedSnapshot> listCriterion; + + private IAutoUpdatedSnapshot, List>> mapResources; + + private IAutoUpdatedSnapshot> externalCompanies; + + private IAutoUpdatedSnapshot> customerReferences; + + private IAutoUpdatedSnapshot> ordersCodes; + + private IAutoUpdatedSnapshot resourceLoadChartData; + + private IAutoUpdatedSnapshot> workReportLines; + + private IAutoUpdatedSnapshot>> estimatedCostPerTask; + + private IAutoUpdatedSnapshot>> advanceCostPerTask; + + private boolean snapshotsRegistered = false; + public SortedMap> snapshotCriterionsMap() { return criterionsMap.getValue(); } - private IAutoUpdatedSnapshot>> labelsMap; - public Map> snapshotLabelsMap() { return labelsMap.getValue(); } - private IAutoUpdatedSnapshot> listWorkers; - public List snapshotListWorkers() { return listWorkers.getValue(); } - private IAutoUpdatedSnapshot> listCostCategories; - public List snapshotListCostCategories() { return listCostCategories.getValue(); } - private IAutoUpdatedSnapshot> listCriterion; - public List snapshotListCriterion() { return listCriterion.getValue(); } - private IAutoUpdatedSnapshot, List>> mapResources; - public Map, List> snapshotMapResources() { return mapResources.getValue(); } - private IAutoUpdatedSnapshot> externalCompanies; - public List snapshotExternalCompanies() { return externalCompanies.getValue(); } - private IAutoUpdatedSnapshot> customerReferences; - public List snapshotCustomerReferences() { return customerReferences.getValue(); } - private IAutoUpdatedSnapshot> ordersCodes; - public List snapshotOrdersCodes() { return ordersCodes.getValue(); } - private IAutoUpdatedSnapshot - resourceLoadChartData; - public ResourceLoadChartData snapshotResourceLoadChartData() { return resourceLoadChartData.getValue(); } - private IAutoUpdatedSnapshot> workReportLines; - public List snapshotWorkReportLines() { return workReportLines.getValue(); } - private IAutoUpdatedSnapshot>> - estimatedCostPerTask; - public Map> snapshotEstimatedCostPerTask() { return estimatedCostPerTask.getValue(); } - private IAutoUpdatedSnapshot>> - advanceCostPerTask; - public Map> snapshotAdvanceCostPerTask() { return advanceCostPerTask.getValue(); } - private boolean snapshotsRegistered = false; - public void registerSnapshots() { if ( snapshotsRegistered ) { LOG.warn("snapshots have already been registered"); - return; } @@ -242,12 +281,6 @@ public class PredefinedDatabaseSnapshots { return AdHocTransactionService.readOnlyProxy(transactionService, Callable.class, callable); } - @Autowired - private ICriterionTypeDAO criterionTypeDAO; - - @Autowired - private ICriterionDAO criterionDAO; - private Callable>> calculateCriterionsMap() { return () -> { SortedMap> result = new TreeMap<>(getComparatorByName()); @@ -262,15 +295,9 @@ public class PredefinedDatabaseSnapshots { } private Comparator getComparatorByName(){ - return (arg0, arg1) -> (arg0.getName().compareTo(arg1.getName())); + return (arg0, arg1) -> arg0.getName().compareTo(arg1.getName()); } - @Autowired - private ILabelTypeDAO labelTypeDAO; - - @Autowired - private ILabelDAO labelDAO; - private Callable>> calculateLabelsMap() { return () -> { Map> result = new HashMap<>(); @@ -282,15 +309,13 @@ public class PredefinedDatabaseSnapshots { }; } - @Autowired - private IWorkerDAO workerDAO; + private Callable> calculateWorkers() { return () -> workerDAO.getAll(); } - @Autowired - private ICostCategoryDAO costCategoryDAO; + private Callable> calculateListCostCategories() { return () -> costCategoryDAO.findActive(); @@ -300,9 +325,6 @@ public class PredefinedDatabaseSnapshots { return criterionDAO::getAll; } - @Autowired - private IResourceDAO resourceDAO; - private Callable, List>> calculateMapResources() { return () -> { Map, List> result = new HashMap<>(); @@ -314,25 +336,15 @@ public class PredefinedDatabaseSnapshots { }; } - - @Autowired - private IExternalCompanyDAO externalCompanyDAO; - private Callable> calculateExternalCompanies() { return () -> externalCompanyDAO.getExternalCompaniesAreClient(); } - @Autowired - private IOrderDAO orderDAO; - private Callable> calculateCustomerReferences() { return () -> { - // FIXME replace by a HQL query, for god's sake! List result = new ArrayList<>(); - for (Order order : orderDAO.getOrders()) { - if ( (order.getCustomerReference() != null) && (!order.getCustomerReference().isEmpty()) ) { - result.add(order.getCustomerReference()); - } + for (Order order : orderDAO.getOrdersWithNotEmptyCustomersReferences()) { + result.add(order.getCustomerReference()); } return result; }; @@ -348,40 +360,29 @@ public class PredefinedDatabaseSnapshots { }; } - @Autowired - private IDayAssignmentDAO dayAssignmentDAO; - - @Autowired - private IScenarioManager scenarioManager; - private Callable calculateResourceLoadChartData() { return () -> { List dayAssignments = dayAssignmentDAO.getAllFor(scenarioManager.getCurrent(), null, null); List resources = resourceDAO.list(Resource.class); - return new ResourceLoadChartData(dayAssignments, resources); }; } - @Autowired - private IWorkReportLineDAO workReportLineDAO; - private Callable> calculateWorkReportLines() { return () -> workReportLineDAO.list(WorkReportLine.class); } - @Autowired - private ICostCalculator hoursCostCalculator; - @Autowired - private ITaskElementDAO taskElementDAO; private Callable>> calculateEstimatedCostPerTask() { return () -> { Map> map = new HashMap<>(); - taskElementDAO.list(TaskElement.class).stream().filter(task -> task instanceof Task) + taskElementDAO. + list(TaskElement.class) + .stream() + .filter(task -> task instanceof Task) .forEach(task -> map.put(task, hoursCostCalculator.getEstimatedCost((Task) task))); return map; diff --git a/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java b/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java index 1c7070aa1..1d178f275 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java +++ b/libreplan-business/src/main/java/org/libreplan/business/i18n/I18nHelper.java @@ -24,20 +24,21 @@ package org.libreplan.business.i18n; /** * This class provides a function to mark strings to be translated. - * Real translation have to be done in webapp module depending on user language and - * not done here depending on server language. + * Real translation have to be done in webapp module depending on user language and not done here depending on server language. * * @author Manuel Rego Casasnovas */ public class I18nHelper { - private I18nHelper() {} + private I18nHelper() { + } - //TODO It should be changed since JDK9. /** + * TODO It should be changed since JDK9 + * * Use of '_' as an identifier might not be supported in releases after Java SE 8. * - * @param str + * @param text * @return Text depends on locale */ public static String _(String text) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderDAO.java b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderDAO.java index 007ada378..ca8cd9f62 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/IOrderDAO.java @@ -39,48 +39,49 @@ import org.libreplan.business.scenarios.entities.Scenario; import org.libreplan.business.users.entities.User; /** - * Contract for {@link OrderDAO} + * Contract for {@link OrderDAO}. + * * @author Óscar González Fernández * @author Lorenzo Tilve Álvaro * @author Diego Pino Garcia * @author Jacobo Aragunde Pérez + * @author Vova Perebykivskyi */ public interface IOrderDAO extends IIntegrationEntityDAO { /** * Gets all the orders. + * * @return A {@link List} of {@link Order} objects */ List getOrders(); /** - * Builds contents for OrderCostsPerResource report - * @return A {@link List} of {@link OrderCostsPerResourceDTO} objects for - * reporting + * Builds contents for OrderCostsPerResource report. + * + * @return A {@link List} of {@link OrderCostsPerResourceDTO} objects for reporting */ - List getOrderCostsPerResource(List orders, - Date startingDate, Date endingDate, - List criterions); + List getOrderCostsPerResource( + List orders, Date startingDate, Date endingDate, List criterions); /** - * Returns a list of orders filtered by the read authorizations of the indicated - * user. Write authorizations are also counted, because they implicitly suppose - * read access. + * Returns a list of orders filtered by the read authorizations of the indicated user. + * Write authorizations are also counted, because they implicitly suppose read access. + * * @param user User. * @return Filtered list of orders. */ List getOrdersByReadAuthorization(User user); /** - * Returns a list of orders filtered by the write authorizations of the indicated - * user. + * Returns a list of orders filtered by the write authorizations of the indicated user. + * * @param user User. * @return Filtered list of orders. */ List getOrdersByWriteAuthorization(User user); - List getOrdersByReadAuthorizationByScenario(String username, - Scenario scenario); + List getOrdersByReadAuthorizationByScenario(String username, Scenario scenario); List getOrdersByReadAuthorizationBetweenDatesByLabelsCriteriaCustomerAndState( String username, Scenario scenario, Date startDate, Date endDate, @@ -88,30 +89,35 @@ public interface IOrderDAO extends IIntegrationEntityDAO { ExternalCompany customer, OrderStatusEnum state); /** - * Returns the order filtered by the name. If name is blank (whitespace, - * empty ("") or null, it throws InstanceNotFoundException. + * Returns the order filtered by the name. + * If name is blank (whitespace, empty ("") or null, it throws InstanceNotFoundException. + * * @param name * String * @return order Order */ - public Order findByNameAnotherTransaction(String name) - throws InstanceNotFoundException; + Order findByNameAnotherTransaction(String name) throws InstanceNotFoundException; List getOrdersByScenario(Scenario scenario); - List getFilteredTask(List orderElements, - List criterions); + List getFilteredTask(List orderElements, List criterions); - public Order loadOrderAvoidingProxyFor(OrderElement orderElement); + Order loadOrderAvoidingProxyFor(OrderElement orderElement); - public List loadOrdersAvoidingProxyFor( - List orderElement); + List loadOrdersAvoidingProxyFor(List orderElement); boolean existsByNameAnotherTransaction(String name); List getActiveOrders(); - List getCostExpenseSheet(List orders, Date startingDate, - Date endingDate, List criterions); + List getCostExpenseSheet( + List orders, Date startingDate, Date endingDate, List criterions); + + /** + * Get {@link Order} where {@link Order#getCustomerReference()} is not NULL and not equals empty {@link String}. + * + * @return {@link List} + */ + List getOrdersWithNotEmptyCustomersReferences(); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java index fcd1219e6..223dfe04e 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/daos/OrderDAO.java @@ -172,7 +172,7 @@ public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { // Apply filtering if (matchFilterCriterion(each.getOrderElement(), criterions) && isOrderContained(order, orders)) { - // Attach ordername value + // Attach orderName value each.setOrderName(order.getName()); each.setOrderCode(order.getCode()); @@ -455,14 +455,16 @@ public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { * Otherwise, it returns the list of orders identifiers for which the user has read permissions. */ private List getOrdersIdsByReadAuthorization(User user) { - if (user.isInRole(UserRole.ROLE_SUPERUSER) - || user.isInRole(UserRole.ROLE_READ_ALL_PROJECTS) - || user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { + if (user.isInRole(UserRole.ROLE_SUPERUSER) || + user.isInRole(UserRole.ROLE_READ_ALL_PROJECTS) || + user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { + return null; } else { - String strQuery = "SELECT oa.order.id " - + "FROM OrderAuthorization oa " - + "WHERE oa.user = :user "; + String strQuery = "SELECT oa.order.id " + + "FROM OrderAuthorization oa " + + "WHERE oa.user = :user "; + if (!user.getProfiles().isEmpty()) { strQuery += "OR oa.profile IN (:profiles) "; } @@ -479,8 +481,7 @@ public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { @Override public List getOrdersByWriteAuthorization(User user) { - if (user.isInRole(UserRole.ROLE_SUPERUSER) - || user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { + if (user.isInRole(UserRole.ROLE_SUPERUSER) || user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { return getOrders(); } else { @@ -489,8 +490,8 @@ public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { for(OrderAuthorization authorization : authorizations) { if (authorization.getAuthorizationType() == OrderAuthorizationType.WRITE_AUTHORIZATION) { Order order = authorization.getOrder(); - if(!orders.contains(order)) { - order.getName(); //this lines forces the load of the basic attributes of the order + if (!orders.contains(order)) { + order.getName(); // this lines forces the load of the basic attributes of the order orders.add(order); } } @@ -695,8 +696,7 @@ public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public boolean existsByNameAnotherTransaction(String name) { try { - Order order = findByName(name); - return order != null; + return findByName(name)!= null; } catch (InstanceNotFoundException e) { return false; } @@ -764,4 +764,13 @@ public class OrderDAO extends IntegrationEntityDAO implements IOrderDAO { return filteredList; } + @Override + public List getOrdersWithNotEmptyCustomersReferences() { + return getSession() + .createCriteria(Order.class) + .add(Restrictions.isNotNull("customerReference")) + .add(Restrictions.ne("customerReference", "")) + .list(); + } + } diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderElement.java b/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderElement.java index 98e379e0a..6edfd44a6 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderElement.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderElement.java @@ -104,7 +104,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri protected OrderLineGroup parent; protected CriterionRequirementOrderElementHandler criterionRequirementHandler = - CriterionRequirementOrderElementHandler.getInstance(); + CriterionRequirementOrderElementHandler.getInstance(); /** * This field is transient. @@ -355,7 +355,7 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri private boolean wasASchedulingPoint() { TaskSource currentTaskSource = getTaskSource(); // Check if the existing TaskSource is inconsistent with the current scheduling state - if (currentTaskSource != null && + if (currentTaskSource != null && currentTaskSource.getTask() != null && currentTaskSource.getTask().isLeaf() && getSchedulingStateType() != Type.SCHEDULING_POINT) { @@ -535,10 +535,6 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri this.getInfoComponent().setName(name); } - public abstract boolean isLeaf(); - - public abstract List getChildren(); - public Date getInitDate() { return initDate; } @@ -654,9 +650,8 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri Validate.notNull(label); if (!checkAncestorsNoOtherLabelRepeated(label)) { - throw new IllegalArgumentException( - "An ancestor has the same label assigned, " + - "so this element is already inheriting this label"); + throw new IllegalArgumentException("An ancestor has the same label assigned, " + + "so this element is already inheriting this label"); } removeLabelOnChildren(label); @@ -856,10 +851,9 @@ public abstract class OrderElement extends IntegrationEntity implements ICriteri return Collections.unmodifiableSet(criterionRequirements); } - /* + /** * Operations to manage the criterion requirements of a orderElement - * (remove, adding, update of the criterion requirement of the orderElement - * such as the descendant's criterion requirement) + * (remove, adding, update of the criterion requirement of the orderElement such as the descendant's criterion requirement) */ public void setValidCriterionRequirement(IndirectCriterionRequirement requirement,boolean valid) { diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderLine.java b/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderLine.java index 77dd65650..d4ec9fb23 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderLine.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderLine.java @@ -199,7 +199,7 @@ public class OrderLine extends OrderElement { } /** - * Operations for manipulating {@link HoursGroup} + * Operations for manipulating {@link HoursGroup}. */ public void setWorkHours(Integer workHours) throws IllegalArgumentException { @@ -349,8 +349,7 @@ public class OrderLine extends OrderElement { } @Override - public DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment( - IndirectAdvanceAssignment indirectAdvanceAssignment) { + public DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment(IndirectAdvanceAssignment indirectAdvanceAssignment) { return null; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderStatusEnum.java b/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderStatusEnum.java index 70084e8f7..921148c8e 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderStatusEnum.java +++ b/libreplan-business/src/main/java/org/libreplan/business/orders/entities/OrderStatusEnum.java @@ -29,35 +29,49 @@ import java.util.EnumSet; /** * @author Susana Montes Pedreiera * @author Manuel Rego Casasnovas + * @author Vova Perebykivskyi */ public enum OrderStatusEnum { - PRE_SALES(_("PRE-SALES")), - OFFERED(_("OFFERED")), - OUTSOURCED(_("OUTSOURCED")), - ACCEPTED(_("ACCEPTED")), - STARTED(_("STARTED")), - ON_HOLD(_("ON HOLD")), - FINISHED(_("FINISHED")), - CANCELLED(_("CANCELLED")), - STORED(_("ARCHIVED")); + PRE_SALES(_("PRE-SALES"), 0), + OFFERED(_("OFFERED"), 1), + OUTSOURCED(_("OUTSOURCED"), 2), + ACCEPTED(_("ACCEPTED"), 3), + STARTED(_("STARTED"), 4), + ON_HOLD(_("ON HOLD"), 5), + FINISHED(_("FINISHED"), 6), + CANCELLED(_("CANCELLED"), 7), + STORED(_("ARCHIVED"), 8); private String description; - private OrderStatusEnum(String description) { + /** + * For {@link DashboardControllerGlobal}. + * When I am building Global Dashboard page I need to know order of enums in {@link Grid}. + */ + private final int index; + + OrderStatusEnum(String description, int index) { this.description = description; + this.index = index; } + @Override public String toString() { return this.description; } + public int getIndex() { + return this.index; + } + public static OrderStatusEnum getDefault() { return PRE_SALES; } public static EnumSet getVisibleStatus() { - return EnumSet.of(OrderStatusEnum.PRE_SALES, OrderStatusEnum.OFFERED, + return EnumSet.of( + OrderStatusEnum.PRE_SALES, OrderStatusEnum.OFFERED, OrderStatusEnum.OUTSOURCED, OrderStatusEnum.ACCEPTED, OrderStatusEnum.STARTED, OrderStatusEnum.ON_HOLD, OrderStatusEnum.FINISHED); diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/daos/DayAssignmentDAO.java b/libreplan-business/src/main/java/org/libreplan/business/planner/daos/DayAssignmentDAO.java index a515cbad1..c84d029d3 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/daos/DayAssignmentDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/daos/DayAssignmentDAO.java @@ -42,7 +42,7 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; /** - * DAO for {@DayAssignment} + * DAO for {@link DayAssignment}. * * @author Diego Pino García * @author Manuel Rego Casasnovas @@ -50,12 +50,12 @@ import org.springframework.stereotype.Repository; */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) -public class DayAssignmentDAO extends GenericDAOHibernate - implements IDayAssignmentDAO { +public class DayAssignmentDAO extends GenericDAOHibernate implements IDayAssignmentDAO { + + private final String SCENARIO = "scenario"; @Override - public void removeDerived( - Collection assignments) { + public void removeDerived(Collection assignments) { for (DerivedDayAssignment each : assignments) { getSession().delete(each); } @@ -63,54 +63,53 @@ public class DayAssignmentDAO extends GenericDAOHibernate @Override public List getAllFor(Scenario scenario) { - List result = new ArrayList(); + List result = new ArrayList<>(); result.addAll(getSpecific(scenario, null, null, null)); result.addAll(getGeneric(scenario, null, null, null)); result.addAll(getDerived(scenario, null, null, null)); + return result; } @Override - public List getAllFor(Scenario scenario, LocalDate init, - LocalDate end) { - List result = new ArrayList(); + public List getAllFor(Scenario scenario, LocalDate init, LocalDate end) { + List result = new ArrayList<>(); result.addAll(getSpecific(scenario, init, end, null)); result.addAll(getGeneric(scenario, init, end, null)); result.addAll(getDerived(scenario, init, end, null)); + return result; } @Override - public List getAllFor(Scenario scenario, - LocalDate startDateInclusive, LocalDate endDateInclusive, - Resource resource) { - List result = new ArrayList(); - result.addAll(getSpecific(scenario, startDateInclusive, - endDateInclusive, resource)); - result.addAll(getGeneric(scenario, startDateInclusive, - endDateInclusive, resource)); - result.addAll(getDerived(scenario, startDateInclusive, - endDateInclusive, resource)); + public List getAllFor( + Scenario scenario, LocalDate startDateInclusive, LocalDate endDateInclusive, Resource resource) { + + List result = new ArrayList<>(); + result.addAll(getSpecific(scenario, startDateInclusive, endDateInclusive, resource)); + result.addAll(getGeneric(scenario, startDateInclusive, endDateInclusive, resource)); + result.addAll(getDerived(scenario, startDateInclusive, endDateInclusive, resource)); + return result; } - private List getDerived(Scenario scenario, - LocalDate initInclusive, LocalDate endInclusive, Resource resource) { - String queryString = "select d from DerivedDayAssignmentsContainer c " - + "JOIN c.dayAssignments d where c.scenario = :scenario" - + addQueryConditionForInitAndEndDate(initInclusive, - endInclusive) + addQueryConditionsForResource(resource); + private List getDerived( + Scenario scenario, LocalDate initInclusive, LocalDate endInclusive, Resource resource) { + + String queryString = "select d from DerivedDayAssignmentsContainer c " + + "JOIN c.dayAssignments d where c.scenario = :scenario" + + addQueryConditionForInitAndEndDate(initInclusive, endInclusive) + addQueryConditionsForResource(resource); + Query query = getSession().createQuery(queryString); - query = query.setParameter("scenario", scenario); + query = query.setParameter(SCENARIO, scenario); addInitAndEndParameters(query, initInclusive, endInclusive); addResourceParameter(query, resource); + return query.list(); } - private String addQueryConditionForInitAndEndDate(LocalDate initInclusive, - LocalDate endInclusive) { - String initCondition = initInclusive != null ? " and d.day >= :init" - : ""; + private String addQueryConditionForInitAndEndDate(LocalDate initInclusive, LocalDate endInclusive) { + String initCondition = initInclusive != null ? " and d.day >= :init" : ""; String endCondition = endInclusive != null ? " and d.day <= :end" : ""; return initCondition + endCondition; } @@ -119,11 +118,11 @@ public class DayAssignmentDAO extends GenericDAOHibernate return resource != null ? " and d.resource = :resource " : ""; } - private Query addInitAndEndParameters(Query query, LocalDate initInclusive, - LocalDate endInclusive) { + private Query addInitAndEndParameters(Query query, LocalDate initInclusive, LocalDate endInclusive) { if (initInclusive != null) { query.setParameter("init", initInclusive); } + if (endInclusive != null) { query.setParameter("end", endInclusive); } @@ -131,33 +130,34 @@ public class DayAssignmentDAO extends GenericDAOHibernate } private Query addResourceParameter(Query query, Resource resource) { - return resource != null ? query.setParameter("resource", resource) - : query; + return resource != null ? query.setParameter("resource", resource) : query; } - private List getGeneric(Scenario scenario, - LocalDate initInclusive, LocalDate endInclusive, Resource resource) { - String queryString = "select d from GenericDayAssignmentsContainer c " - + "JOIN c.dayAssignments d where c.scenario = :scenario" - + addQueryConditionForInitAndEndDate(initInclusive, - endInclusive) + addQueryConditionsForResource(resource); - Query query = getSession().createQuery(queryString).setParameter( - "scenario", scenario); + private List getGeneric( + Scenario scenario, LocalDate initInclusive, LocalDate endInclusive, Resource resource) { + + String queryString = "select d from GenericDayAssignmentsContainer c " + + "JOIN c.dayAssignments d where c.scenario = :scenario" + + addQueryConditionForInitAndEndDate(initInclusive, endInclusive) + addQueryConditionsForResource(resource); + + Query query = getSession().createQuery(queryString).setParameter(SCENARIO, scenario); addInitAndEndParameters(query, initInclusive, endInclusive); addResourceParameter(query, resource); + return query.list(); } - private List getSpecific(Scenario scenario, - LocalDate initInclusive, LocalDate endInclusive, Resource resource) { - String queryString = "select d from SpecificDayAssignmentsContainer c " - + "JOIN c.dayAssignments d where c.scenario = :scenario" - + addQueryConditionForInitAndEndDate(initInclusive, - endInclusive) + addQueryConditionsForResource(resource); - Query query = getSession().createQuery(queryString).setParameter( - "scenario", scenario); + private List getSpecific( + Scenario scenario, LocalDate initInclusive, LocalDate endInclusive, Resource resource) { + + String queryString = "select d from SpecificDayAssignmentsContainer c " + + "JOIN c.dayAssignments d where c.scenario = :scenario" + + addQueryConditionForInitAndEndDate(initInclusive, endInclusive) + addQueryConditionsForResource(resource); + + Query query = getSession().createQuery(queryString).setParameter(SCENARIO, scenario); addInitAndEndParameters(query, initInclusive, endInclusive); addResourceParameter(query, resource); + return query.list(); } @@ -169,31 +169,29 @@ public class DayAssignmentDAO extends GenericDAOHibernate return criteria.list(); } - private void addDateRestrictionsToDayAssignmentQuery(Criteria criteria, - LocalDate init, LocalDate end) { - if(init != null) { + private void addDateRestrictionsToDayAssignmentQuery(Criteria criteria, LocalDate init, LocalDate end) { + if (init != null) { criteria.add(Restrictions.ge("day", init)); } - if(end != null) { + if (end != null) { criteria.add(Restrictions.le("day", end)); } } @Override public List findByResources(Scenario scenario, List resources) { - // TODO incorporate scenario filtering to the query instead of doing it - // in memory + // TODO incorporate scenario filtering to the query instead of doing it in memory return DayAssignment.withScenario(scenario, findByResources(resources)); } @Override public List findByResources(List resources) { - if (resources.isEmpty()) { - return Collections.emptyList(); - } - Criteria criteria = getSession().createCriteria(DayAssignment.class) - .add(Restrictions.in("resource", resources)); - return criteria.list(); + return resources.isEmpty() + ? Collections.emptyList() + : getSession() + .createCriteria(DayAssignment.class) + .add(Restrictions.in("resource", resources)) + .list(); } } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/CalculatedValue.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/CalculatedValue.java index 7e9594113..9315a3575 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/CalculatedValue.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/CalculatedValue.java @@ -22,10 +22,11 @@ package org.libreplan.business.planner.entities; /** - * It represents the value that is calculated + * It represents the value that is calculated. + * * @author Óscar González Fernández */ public enum CalculatedValue { - NUMBER_OF_HOURS, END_DATE, RESOURCES_PER_DAY; + NUMBER_OF_HOURS, END_DATE, RESOURCES_PER_DAY } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/GenericResourceAllocation.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/GenericResourceAllocation.java index 0aa26dff5..854e1c0db 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/GenericResourceAllocation.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/GenericResourceAllocation.java @@ -74,7 +74,8 @@ public class GenericResourceAllocation extends ResourceAllocation getOrderedAssignmentsFor(Resource resource) { - List list = getOrderedAssignmentsFor().get(resource); - - return list == null ? Collections.emptyList() : Collections.unmodifiableList(list); + List assignments = getOrderedAssignmentsFor().get(resource); + return assignments == null ? Collections.emptyList() : Collections.unmodifiableList(assignments); } private Map> getOrderedAssignmentsFor() { @@ -186,7 +186,6 @@ public class GenericResourceAllocation extends ResourceAllocation createCopy(Scenario scenario) { GenericResourceAllocation allocation = create(); allocation.criterions = new HashSet<>(criterions); - return allocation; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidatedValue.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidatedValue.java index 326af7e30..219ddf61e 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidatedValue.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidatedValue.java @@ -35,26 +35,24 @@ public class CalculatedConsolidatedValue extends ConsolidatedValue { private CalculatedConsolidation consolidation; - public static CalculatedConsolidatedValue create() { - return create(new CalculatedConsolidatedValue()); - } - - public static CalculatedConsolidatedValue create(LocalDate date, - BigDecimal value, IntraDayDate taskEndDate) { - return create(new CalculatedConsolidatedValue(date, value, taskEndDate)); - } - - protected CalculatedConsolidatedValue(LocalDate date, BigDecimal value, - IntraDayDate taskEndDate) { - super(date, value, taskEndDate); - } - /** * Constructor for {@link DeepCopy}. DO NOT USE! */ public CalculatedConsolidatedValue() { } + protected CalculatedConsolidatedValue(LocalDate date, BigDecimal value, IntraDayDate taskEndDate) { + super(date, value, taskEndDate); + } + + public static CalculatedConsolidatedValue create() { + return create(new CalculatedConsolidatedValue()); + } + + public static CalculatedConsolidatedValue create(LocalDate date, BigDecimal value, IntraDayDate taskEndDate) { + return create(new CalculatedConsolidatedValue(date, value, taskEndDate)); + } + public void setConsolidation(CalculatedConsolidation consolidation) { this.consolidation = consolidation; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidation.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidation.java index 6aa59c90d..1942e0544 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidation.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/consolidations/CalculatedConsolidation.java @@ -37,58 +37,50 @@ import org.libreplan.business.util.deepcopy.Strategy; public class CalculatedConsolidation extends Consolidation { - private SortedSet consolidatedValues = new TreeSet( - new ConsolidatedValueComparator()); - - @AfterCopy - private void instantiateConsolidatedValuesWithComparator() { - SortedSet previous = consolidatedValues; - consolidatedValues = new TreeSet( - new ConsolidatedValueComparator()); - consolidatedValues.addAll(previous); - } + private SortedSet consolidatedValues = new TreeSet<>(new ConsolidatedValueComparator()); @OnCopy(Strategy.SHARE) private IndirectAdvanceAssignment indirectAdvanceAssignment; - public static CalculatedConsolidation create(Task task, - IndirectAdvanceAssignment indirectAdvanceAssignment) { - return create(new CalculatedConsolidation(task, - indirectAdvanceAssignment)); - } - - public static CalculatedConsolidation create(Task task, - IndirectAdvanceAssignment indirectAdvanceAssignment, - SortedSet consolidatedValues) { - return create(new CalculatedConsolidation(task, - indirectAdvanceAssignment, - consolidatedValues)); - } - /** * Constructor for {@link DeepCopy}. DO NOT USE! */ public CalculatedConsolidation() { - } - protected CalculatedConsolidation(Task task, - IndirectAdvanceAssignment indirectAdvanceAssignment, - SortedSet consolidatedValues) { - this(task, indirectAdvanceAssignment); - this.setConsolidatedValues(consolidatedValues); - } - - public CalculatedConsolidation(Task task, - IndirectAdvanceAssignment indirectAdvanceAssignment) { + public CalculatedConsolidation(Task task, IndirectAdvanceAssignment indirectAdvanceAssignment) { super(task); this.indirectAdvanceAssignment = indirectAdvanceAssignment; } + protected CalculatedConsolidation(Task task, IndirectAdvanceAssignment indirectAdvanceAssignment, + SortedSet consolidatedValues) { + + this(task, indirectAdvanceAssignment); + this.setConsolidatedValues(consolidatedValues); + } + + @AfterCopy + private void instantiateConsolidatedValuesWithComparator() { + SortedSet previous = consolidatedValues; + consolidatedValues = new TreeSet<>(new ConsolidatedValueComparator()); + consolidatedValues.addAll(previous); + } + + public static CalculatedConsolidation create(Task task, IndirectAdvanceAssignment indirectAdvanceAssignment) { + return create(new CalculatedConsolidation(task, indirectAdvanceAssignment)); + } + + public static CalculatedConsolidation create(Task task, IndirectAdvanceAssignment indirectAdvanceAssignment, + SortedSet consolidatedValues) { + + return create(new CalculatedConsolidation(task, indirectAdvanceAssignment, consolidatedValues)); + } + @Override public SortedSet getConsolidatedValues() { - SortedSet result = new TreeSet( - new ConsolidatedValueComparator()); + SortedSet result; + result = new TreeSet<>(new ConsolidatedValueComparator()); result.addAll(consolidatedValues); return result; } @@ -97,13 +89,11 @@ public class CalculatedConsolidation extends Consolidation { return consolidatedValues; } - public void setConsolidatedValues( - SortedSet consolidatedValues) { + public void setConsolidatedValues(SortedSet consolidatedValues) { this.consolidatedValues = consolidatedValues; } - public void setIndirectAdvanceAssignment( - IndirectAdvanceAssignment indirectAdvanceAssignment) { + public void setIndirectAdvanceAssignment(IndirectAdvanceAssignment indirectAdvanceAssignment) { this.indirectAdvanceAssignment = indirectAdvanceAssignment; } diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/visitors/CalculateFinishedTasksEstimationDeviationVisitor.java b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/visitors/CalculateFinishedTasksEstimationDeviationVisitor.java index 9e19ee7b5..7771b99f7 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/entities/visitors/CalculateFinishedTasksEstimationDeviationVisitor.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/entities/visitors/CalculateFinishedTasksEstimationDeviationVisitor.java @@ -20,9 +20,8 @@ package org.libreplan.business.planner.entities.visitors; /** - * FIXME - * This visitor calculates allocated/spent hours deviation - * for finished tasks. + * This visitor calculates allocated/spent hours deviation for finished tasks. + * * @author Nacho Barrientos */ import java.util.ArrayList; @@ -40,39 +39,32 @@ public class CalculateFinishedTasksEstimationDeviationVisitor extends TaskElemen private List deviations; public CalculateFinishedTasksEstimationDeviationVisitor() { - this.deviations = new ArrayList(); + this.deviations = new ArrayList<>(); } public List getDeviations() { return this.deviations; } - public int getNumberOfConsideredTasks(){ - return deviations.size(); - } - + @Override public void visit(Task task) { if (task.isFinished()) { EffortDuration effort = task.getAssignedEffort(); if (effort.isZero()) { - effort = EffortDuration.hours(task.getOrderElement() - .getWorkHours()); + effort = EffortDuration.hours(task.getOrderElement().getWorkHours()); } if (!effort.isZero()) { - SumChargedEffort sumChargedEffort = task.getOrderElement() - .getSumChargedEffort(); - EffortDuration spentEffort = sumChargedEffort == null ? EffortDuration - .zero() : sumChargedEffort.getTotalChargedEffort(); + SumChargedEffort sumChargedEffort = task.getOrderElement().getSumChargedEffort(); + + EffortDuration spentEffort = + sumChargedEffort == null ? EffortDuration.zero() : sumChargedEffort.getTotalChargedEffort(); + if (!spentEffort.isZero()) { double deviation; if (spentEffort.compareTo(effort) >= 0) { - deviation = spentEffort.minus(effort) - .dividedByAndResultAsBigDecimal(effort) - .doubleValue(); + deviation = spentEffort.minus(effort).dividedByAndResultAsBigDecimal(effort).doubleValue(); } else { - deviation = -effort.minus(spentEffort) - .dividedByAndResultAsBigDecimal(effort) - .doubleValue(); + deviation = -effort.minus(spentEffort).dividedByAndResultAsBigDecimal(effort).doubleValue(); } deviations.add(deviation * 100); @@ -81,6 +73,7 @@ public class CalculateFinishedTasksEstimationDeviationVisitor extends TaskElemen } } + @Override public void visit(TaskGroup taskGroup) { for (TaskElement each: taskGroup.getChildren()) { each.acceptVisitor(this); diff --git a/libreplan-business/src/main/java/org/libreplan/business/planner/limiting/entities/Gap.java b/libreplan-business/src/main/java/org/libreplan/business/planner/limiting/entities/Gap.java index 7f8b877b8..83e4d2895 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/planner/limiting/entities/Gap.java +++ b/libreplan-business/src/main/java/org/libreplan/business/planner/limiting/entities/Gap.java @@ -27,7 +27,6 @@ import static org.libreplan.business.workingday.EffortDuration.zero; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -53,31 +52,23 @@ import org.libreplan.business.workingday.IntraDayDate.PartialDay; * Note: this class has a natural ordering that is inconsistent with equals. * * @author Diego Pino Garcia - * */ public class Gap implements Comparable { + private DateAndHour startTime; + + private DateAndHour endTime; + + private Integer hoursInGap; + + public Gap(Resource resource, DateAndHour startTime, DateAndHour endTime) { + this.startTime = startTime; + this.endTime = endTime; + hoursInGap = calculateHoursInGap(resource, startTime, endTime); + } + public static class GapOnQueue { - public static List onQueue(LimitingResourceQueue queue, - Collection gaps) { - List result = new ArrayList(); - for (Gap each : gaps) { - result.add(each.onQueue(queue)); - } - return result; - } - - public static List onQueue( - LimitingResourceQueue queue, DateAndHour startTime, - DateAndHour endTime) { - - Gap gap = (endTime == null || endTime.compareTo(startTime) <= 0) ? Gap - .untilEnd(queue.getResource(), startTime) : Gap.create( - queue.getResource(), startTime, endTime); - return GapOnQueue.onQueue(queue, Collections.singleton(gap)); - } - private final LimitingResourceQueue originQueue; private final Gap gap; @@ -87,6 +78,23 @@ public class Gap implements Comparable { this.gap = gap; } + public static List onQueue(LimitingResourceQueue queue, Collection gaps) { + List result = new ArrayList<>(); + for (Gap each : gaps) { + result.add(each.onQueue(queue)); + } + return result; + } + + public static List onQueue(LimitingResourceQueue queue, DateAndHour startTime, DateAndHour endTime) { + + Gap gap = (endTime == null || endTime.compareTo(startTime) <= 0) + ? Gap.untilEnd(queue.getResource(), startTime) + : Gap.create(queue.getResource(), startTime, endTime); + + return GapOnQueue.onQueue(queue, Collections.singleton(gap)); + } + public LimitingResourceQueue getOriginQueue() { return originQueue; } @@ -95,13 +103,11 @@ public class Gap implements Comparable { return gap; } - public List splitIntoGapsSatisfyingCriteria( - Set criteria) { - return GapOnQueue.onQueue(originQueue, gap - .splitIntoGapsSatisfyingCriteria(originQueue.getResource(), - criteria)); + public List splitIntoGapsSatisfyingCriteria(Set criteria) { + return GapOnQueue.onQueue(originQueue, gap.splitIntoGapsSatisfyingCriteria(originQueue.getResource(), criteria)); } + @Override public String toString() { return "queue: " + originQueue + "; gap: " + gap; } @@ -109,10 +115,9 @@ public class Gap implements Comparable { } /** - * @author Diego Pino García + * Stores a {@link GapOnQueue} plus its adjacent {@link LimitingResourceQueueElement}. * - * Stores a {@link GapOnQueue} plus its adjacent - * {@link LimitingResourceQueueElement} + * @author Diego Pino García */ public static class GapOnQueueWithQueueElement { @@ -120,16 +125,15 @@ public class Gap implements Comparable { private final GapOnQueue gapOnQueue; - public static GapOnQueueWithQueueElement create(GapOnQueue gapOnQueue, - LimitingResourceQueueElement queueElement) { - return new GapOnQueueWithQueueElement(gapOnQueue, queueElement); - } - GapOnQueueWithQueueElement(GapOnQueue gapOnQueue, LimitingResourceQueueElement queueElement) { this.gapOnQueue = gapOnQueue; this.queueElement = queueElement; } + public static GapOnQueueWithQueueElement create(GapOnQueue gapOnQueue, LimitingResourceQueueElement queueElement) { + return new GapOnQueueWithQueueElement(gapOnQueue, queueElement); + } + public LimitingResourceQueueElement getQueueElement() { return queueElement; } @@ -139,36 +143,31 @@ public class Gap implements Comparable { } /** - * Joins first.gap + second.gap and keeps second.queueElement as - * {@link LimitingResourceQueueElement} + * Joins first.gap + second.gap and keeps second.queueElement as {@link LimitingResourceQueueElement}. * * @param first * @param second - * @return + * @return {@link GapOnQueueWithQueueElement} */ public static GapOnQueueWithQueueElement coalesce( - GapOnQueueWithQueueElement first, - GapOnQueueWithQueueElement second) { + GapOnQueueWithQueueElement first, GapOnQueueWithQueueElement second) { - LimitingResourceQueue queue = first.getGapOnQueue() - .getOriginQueue(); - DateAndHour startTime = first.getGapOnQueue().getGap() - .getStartTime(); + LimitingResourceQueue queue = first.getGapOnQueue().getOriginQueue(); + DateAndHour startTime = first.getGapOnQueue().getGap().getStartTime(); DateAndHour endTime = second.getGapOnQueue().getGap().getEndTime(); - Gap coalescedGap = Gap.create(queue.getResource(), startTime, - endTime); + Gap coalescedGap = Gap.create(queue.getResource(), startTime, endTime); return create(coalescedGap.onQueue(queue), second.getQueueElement()); } + @Override public String toString() { return "gapOnQueue: " + gapOnQueue + "; queueElement: " + queueElement; } } - public static Gap untilEnd(LimitingResourceQueueElement current, - DateAndHour startInclusive) { + public static Gap untilEnd(LimitingResourceQueueElement current, DateAndHour startInclusive) { return untilEnd(current.getResource(), startInclusive); } @@ -176,48 +175,27 @@ public class Gap implements Comparable { return new Gap(resource, startInclusive, null); } - private DateAndHour startTime; - - private DateAndHour endTime; - - private Integer hoursInGap; - - public Gap(Resource resource, DateAndHour startTime, - DateAndHour endTime) { - this.startTime = startTime; - this.endTime = endTime; - hoursInGap = calculateHoursInGap(resource, startTime, endTime); - } - public GapOnQueue onQueue(LimitingResourceQueue queue) { return new GapOnQueue(queue, this); } private Integer calculateHoursInGap(Resource resource, DateAndHour startTime, DateAndHour endTime) { - // TODO remove this method. Use GapRequirements instead if (endTime == null || startTime == null) { // startTime is never null when hours in gap is really use return Integer.MAX_VALUE; } else { - return calculateHoursInGap(resource, startTime.getDate(), startTime - .getHour(), endTime.getDate(), endTime.getHour()); + return calculateHoursInGap( + resource, startTime.getDate(), startTime.getHour(), endTime.getDate(), endTime.getHour()); } } - public int getHoursInGap() { - return hoursInGap; - } - - private Integer calculateHoursInGap(Resource resource, LocalDate startDate, - int startHour, LocalDate endDate, int endHour) { - IntraDayDate intraStart = IntraDayDate.create(startDate, - hours(startHour)); + private Integer calculateHoursInGap(Resource resource, LocalDate startDate, int startHour, LocalDate endDate, int endHour) { + IntraDayDate intraStart = IntraDayDate.create(startDate, hours(startHour)); IntraDayDate intraEnd = IntraDayDate.create(endDate, hours(endHour)); return calculateHoursInGap(resource, intraStart, intraEnd); } - private Integer calculateHoursInGap(Resource resource, IntraDayDate start, - IntraDayDate end) { + private Integer calculateHoursInGap(Resource resource, IntraDayDate start, IntraDayDate end) { final ResourceCalendar calendar = resource.getCalendar(); Iterable days = start.daysUntil(end); EffortDuration result = zero(); @@ -228,14 +206,12 @@ public class Gap implements Comparable { } public List getHoursInGapUntilAllocatingAndGoingToTheEnd( - BaseCalendar calendar, - DateAndHour realStart, DateAndHour allocationEnd, int total) { + BaseCalendar calendar, DateAndHour realStart, DateAndHour allocationEnd, int total) { Validate.isTrue(endTime == null || allocationEnd.compareTo(endTime) <= 0); - Validate.isTrue(startTime == null - || realStart.compareTo(startTime) >= 0); + Validate.isTrue(startTime == null || realStart.compareTo(startTime) >= 0); Validate.isTrue(total >= 0); - List result = new ArrayList(); + List result = new ArrayList<>(); // If endTime is null (last tasks) assume the end is in 10 years from now DateAndHour endDate = getEndTime(); @@ -243,31 +219,24 @@ public class Gap implements Comparable { endDate = DateAndHour.TEN_YEARS_FROM(realStart); } - Iterator daysUntilEnd = realStart.toIntraDayDate() - .daysUntil(endDate.toIntraDayDate()).iterator(); - while (daysUntilEnd.hasNext()) { - PartialDay each = daysUntilEnd.next(); + for (PartialDay each : realStart.toIntraDayDate().daysUntil(endDate.toIntraDayDate())) { int hoursAtDay = calendar.getCapacityOn(each).roundToHours(); int hours = Math.min(hoursAtDay, total); total -= hours; - // Don't add hours when total and hours are zero (it'd be like - // adding an extra 0 hour day when total is completed) - if (total != 0 || hours != 0) { + // Don't add hours when total and hours are zero (it'd be like adding an extra 0 hour day when total is completed) + if ( total != 0 || hours != 0 ) { result.add(hours); } - if (total == 0 - && DateAndHour.from(each.getDate()) - .compareTo(allocationEnd) >= 0) { + if ( total == 0 && DateAndHour.from(each.getDate()).compareTo(allocationEnd) >= 0 ) { break; } } return result; } - public static Gap create(Resource resource, DateAndHour startTime, - DateAndHour endTime) { + public static Gap create(Resource resource, DateAndHour startTime, DateAndHour endTime) { return new Gap(resource, startTime, endTime); } @@ -280,21 +249,18 @@ public class Gap implements Comparable { } /** - * Returns true if the gap starts after earlierStartDateBecauseOfGantt and - * if it's big enough for fitting candidate + * Returns true if the gap starts after earlierStartDateBecauseOfGantt and if it's big enough for fitting candidate. * - * @param hours - * @return + * @param candidate + * @return boolean */ public boolean canFit(LimitingResourceQueueElement candidate) { - LocalDate startAfter = LocalDate.fromDateFields(candidate - .getEarliestStartDateBecauseOfGantt()); - LocalDate endsAfter = LocalDate.fromDateFields(candidate - .getEarliestEndDateBecauseOfGantt()); + LocalDate startAfter = LocalDate.fromDateFields(candidate.getEarliestStartDateBecauseOfGantt()); + LocalDate endsAfter = LocalDate.fromDateFields(candidate.getEarliestEndDateBecauseOfGantt()); - return canSatisfyStartConstraint(startAfter) - && canSatisfyEndConstraint(endsAfter) - && hoursInGap >= candidate.getIntentedTotalHours(); + return canSatisfyStartConstraint(startAfter) && + canSatisfyEndConstraint(endsAfter) && + hoursInGap >= candidate.getIntentedTotalHours(); } private boolean canSatisfyStartConstraint(final LocalDate startsAfter) { @@ -305,6 +271,7 @@ public class Gap implements Comparable { return endTime == null || endsAfter.compareTo(endTime.getDate()) <= 0; } + @Override public String toString() { String result = ""; @@ -322,10 +289,13 @@ public class Gap implements Comparable { if (other == null) { return 1; } + if (this.getStartTime() == null && other.getStartTime() == null) { return 0; + } else if (this.getStartTime() == null) { return -1; + } else if (other.getStartTime() == null) { return 1; } @@ -333,19 +303,17 @@ public class Gap implements Comparable { } public boolean isBefore(Gap gap) { - return (compareTo(gap) < 0); + return compareTo(gap) < 0; } - public List splitIntoGapsSatisfyingCriteria(Resource resource, - Set criteria) { - return splitIntoGapsSatisfyingCriteria(resource, criteria, - getStartTime(), getEndTime()); + public List splitIntoGapsSatisfyingCriteria(Resource resource, Set criteria) { + return splitIntoGapsSatisfyingCriteria(resource, criteria, getStartTime(), getEndTime()); } /** - * Returns a set of {@link Gap} composed by those gaps which satisfy - * criteria within the period: gapStartTime till - * gapEndTime + * Returns a set of {@link Gap} composed by those gaps which satisfy criteria within the period: + * gapStartTime till gapEndTime. + * * @param resource * @param criteria * criteria to be satisfied by resource @@ -353,42 +321,45 @@ public class Gap implements Comparable { * start time of gap * @param gapEndTime * end time of gap - * @return + * @return {@link List} */ - private static List splitIntoGapsSatisfyingCriteria(Resource resource, - Set criteria, DateAndHour gapStartTime, - DateAndHour gapEndTime) { - AvailabilityTimeLine criterionsAvailability = AvailabilityCalculator - .getCriterionsAvailabilityFor(criteria, resource); + private static List splitIntoGapsSatisfyingCriteria( + Resource resource, Set criteria, DateAndHour gapStartTime, DateAndHour gapEndTime) { + + AvailabilityTimeLine criterionsAvailability = + AvailabilityCalculator.getCriterionsAvailabilityFor(criteria, resource); + if (gapStartTime != null) { criterionsAvailability.invalidUntil(gapStartTime.getDate()); } + if (gapEndTime != null) { criterionsAvailability.invalidFrom(gapEndTime.getDate()); } + List validPeriods = criterionsAvailability.getValidPeriods(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (Interval each : validPeriods) { result.add(createGap(resource, each, gapStartTime, gapEndTime)); } return result; } - private static Gap createGap(Resource resource, Interval interval, - DateAndHour originalGapStartTime, DateAndHour originalGapEndTime) { + private static Gap createGap( + Resource resource, Interval interval, DateAndHour originalGapStartTime, DateAndHour originalGapEndTime) { + DateAndHour start = convert(originalGapStartTime, interval.getStart()); DateAndHour end = convert(originalGapEndTime, interval.getEnd()); return Gap.create(resource, start, end); } - private static DateAndHour convert(DateAndHour possibleMatch, - DatePoint datePoint) { + private static DateAndHour convert(DateAndHour possibleMatch, DatePoint datePoint) { if (datePoint instanceof StartOfTime || datePoint instanceof EndOfTime) { return null; } + FixedPoint p = (FixedPoint) datePoint; - if (possibleMatch != null - && possibleMatch.getDate().equals(p.getDate())) { + if (possibleMatch != null && possibleMatch.getDate().equals(p.getDate())) { return possibleMatch; } return DateAndHour.from(p.getDate()); diff --git a/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/IScenarioDAO.java b/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/IScenarioDAO.java index df911cc2a..b861ad209 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/IScenarioDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/IScenarioDAO.java @@ -33,6 +33,7 @@ import org.libreplan.business.scenarios.entities.Scenario; * Contract for {@link ScenarioDAO}. * * @author Manuel Rego Casasnovas + * @author Vova Perebykivskyi */ public interface IScenarioDAO extends IGenericDAO { @@ -44,6 +45,14 @@ public interface IScenarioDAO extends IGenericDAO { List getAll(); + /** + * Gets all {@link Scenario}s except chosen. + * + * @param scenario Selected {@link Scenario} that you want to exclude + * @return {@link List} + */ + List getAllExcept(Scenario scenario); + boolean thereIsOtherWithSameName(Scenario scenario); List findByPredecessor(Scenario scenario); @@ -51,7 +60,6 @@ public interface IScenarioDAO extends IGenericDAO { List getDerivedScenarios(Scenario scenario); void updateDerivedScenariosWithNewVersion( - OrderVersion previousOrderVersion, Order order, - Scenario currentScenario, OrderVersion newOrderVersion); + OrderVersion previousOrderVersion, Order order, Scenario currentScenario, OrderVersion newOrderVersion); } diff --git a/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java b/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java index 244aa4145..f033bd6fc 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java +++ b/libreplan-business/src/main/java/org/libreplan/business/scenarios/daos/ScenarioDAO.java @@ -45,6 +45,7 @@ import org.springframework.transaction.annotation.Transactional; * DAO implementation for {@link Scenario}. * * @author Manuel Rego Casasnovas + * @author Vova Perebykivskyi */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) @@ -118,6 +119,14 @@ public class ScenarioDAO extends GenericDAOHibernate implements return list(Scenario.class); } + @Override + public List getAllExcept(Scenario scenario) { + return getSession() + .createCriteria(Scenario.class) + .add(Restrictions.ne("name", scenario.getName())) + .list(); + } + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) @Override public boolean thereIsOtherWithSameName(Scenario scenario) { @@ -135,14 +144,12 @@ public class ScenarioDAO extends GenericDAOHibernate implements @Override public List findByPredecessor(Scenario scenario) { - if (scenario == null) { - return Collections.emptyList(); - } - - return getSession() - .createCriteria(Scenario.class) - .add(Restrictions.eq("predecessor", scenario)) - .list(); + return scenario == null + ? Collections.emptyList() + : getSession() + .createCriteria(Scenario.class) + .add(Restrictions.eq("predecessor", scenario)) + .list(); } @Override diff --git a/libreplan-business/src/main/java/org/libreplan/business/util/TaskElementVisitor.java b/libreplan-business/src/main/java/org/libreplan/business/util/TaskElementVisitor.java index 085589c0f..2ad4ce6ae 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/util/TaskElementVisitor.java +++ b/libreplan-business/src/main/java/org/libreplan/business/util/TaskElementVisitor.java @@ -20,8 +20,7 @@ package org.libreplan.business.util; /** - * This class represents an abstract visitor to traverse - * task graphs. + * This class represents an abstract visitor to traverse task graphs. * * @author Nacho Barrientos */ @@ -36,8 +35,7 @@ public abstract class TaskElementVisitor { public abstract void visit(TaskGroup taskGroup); /** - * As most of the visitors doesn't need to process the {@link TaskMilestone - * TaskMilestones} is provided a default implementation doing nothing. + * As most of the visitors doesn't need to process the {@link TaskMilestones} is provided a default implementation doing nothing. */ public void visit(TaskMilestone taskMilestone) { // Do nothing diff --git a/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/AfterCopy.java b/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/AfterCopy.java index d1d58347d..0776f278c 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/AfterCopy.java +++ b/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/AfterCopy.java @@ -28,11 +28,9 @@ import java.lang.annotation.Target; /** * @author Óscar González Fernández - * */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AfterCopy { - } diff --git a/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/DeepCopy.java b/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/DeepCopy.java index ed8d82113..fe1275b6f 100644 --- a/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/DeepCopy.java +++ b/libreplan-business/src/main/java/org/libreplan/business/util/deepcopy/DeepCopy.java @@ -47,18 +47,22 @@ import org.libreplan.business.workingday.EffortDuration; /** * @author Óscar González Fernández - * */ public class DeepCopy { - private static Set> inmmutableTypes = new HashSet>(Arrays - .> asList(Boolean.class, String.class, BigDecimal.class, - Double.class, Float.class, Integer.class, Short.class, - Byte.class, Character.class, LocalDate.class, - DateTime.class, EffortDuration.class)); + + private static Set> inmmutableTypes = new HashSet<>(Arrays.>asList( + Boolean.class, String.class, BigDecimal.class, + Double.class, Float.class, Integer.class, + Short.class, Byte.class, Character.class, + LocalDate.class, DateTime.class, EffortDuration.class)); + + private static List DEFAULT_CUSTOM_COPIERS = + Arrays.asList(new DateCopy(), new SetCopy(), new MapCopy(), new ListCopy()); + + private Map alreadyCopiedObjects = new HashMap<>(); public static boolean isImmutableType(Class klass) { - return klass.isPrimitive() || isEnum(klass) - || inmmutableTypes.contains(klass); + return klass.isPrimitive() || isEnum(klass) || inmmutableTypes.contains(klass); } private static boolean isEnum(Class klass) { @@ -69,16 +73,17 @@ public class DeepCopy { } currentClass = currentClass.getSuperclass(); } while (currentClass != null); + return false; } public interface ICustomCopy { - public boolean canHandle(Object object); - public Object instantiateCopy(Strategy strategy, Object originValue); + boolean canHandle(Object object); - public void copyDataToResult(DeepCopy deepCopy, Object origin, - Strategy strategy, Object result); + Object instantiateCopy(Strategy strategy, Object originValue); + + void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result); } private static class DateCopy implements ICustomCopy { @@ -89,9 +94,8 @@ public class DeepCopy { } @Override - public void copyDataToResult(DeepCopy deepCopy, Object origin, - Strategy strategy, Object result) { - // already completed + public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) { + // Already completed } @Override @@ -102,7 +106,7 @@ public class DeepCopy { } - private static abstract class CollectionCopy implements ICustomCopy { + private abstract static class CollectionCopy implements ICustomCopy { @Override public Object instantiateCopy(Strategy strategy, Object originValue) { @@ -112,13 +116,11 @@ public class DeepCopy { protected abstract Collection getResultData(Object originValue); @Override - public void copyDataToResult(DeepCopy deepCopy, Object origin, - Strategy strategy, Object result) { + public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) { copy(deepCopy, origin, strategy, (Collection) result); } - private void copy(DeepCopy deepCopy, Object origin, Strategy strategy, - Collection destination) { + private void copy(DeepCopy deepCopy, Object origin, Strategy strategy, Collection destination) { Strategy childrenStrategy = getChildrenStrategy(strategy); for (Object each : originDataAsIterable(origin)) { destination.add(deepCopy.copy(each, childrenStrategy)); @@ -126,10 +128,7 @@ public class DeepCopy { } private Strategy getChildrenStrategy(Strategy strategy) { - if (strategy == Strategy.SHARE_COLLECTION_ELEMENTS) { - return Strategy.SHARE; - } - return strategy; + return strategy == Strategy.SHARE_COLLECTION_ELEMENTS ? Strategy.SHARE : strategy; } private Iterable originDataAsIterable(Object originValue) { @@ -153,10 +152,7 @@ public class DeepCopy { return new ImplementationInstantiation() { @Override protected Set createDefault() { - if (SortedSet.class.isAssignableFrom(klass)) { - return new TreeSet(); - } - return new HashSet(); + return SortedSet.class.isAssignableFrom(klass) ? new TreeSet<>() : new HashSet<>(); } }.instantiate(klass); } @@ -177,21 +173,20 @@ public class DeepCopy { return new ImplementationInstantiation() { @Override protected Object createDefault() { - return new HashMap(); + return new HashMap<>(); } }.instantiate(klass); } @Override - public void copyDataToResult(DeepCopy deepCopy, Object origin, - Strategy strategy, Object result) { - doCopy(deepCopy, (Map) ((Map) origin), strategy, ((Map) result)); + public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) { + doCopy(deepCopy, (Map) origin, strategy, ((Map) result)); } - private void doCopy(DeepCopy deepCopy, Map origin, - Strategy strategy, Map resultMap) { + private void doCopy(DeepCopy deepCopy, Map origin, Strategy strategy, Map resultMap) { Strategy keyStrategy = getKeysStrategy(strategy); Strategy valueStrategy = getValuesStrategy(strategy); + for (Entry entry : origin.entrySet()) { Object key = deepCopy.copy(entry.getKey(), keyStrategy); Object value = deepCopy.copy(entry.getValue(), valueStrategy); @@ -200,19 +195,15 @@ public class DeepCopy { } private Strategy getKeysStrategy(Strategy strategy) { - if (Strategy.ONLY_SHARE_KEYS == strategy - || Strategy.SHARE_COLLECTION_ELEMENTS == strategy) { - return Strategy.SHARE; - } - return strategy; + return Strategy.ONLY_SHARE_KEYS == strategy || Strategy.SHARE_COLLECTION_ELEMENTS == strategy + ? Strategy.SHARE + : strategy; } private Strategy getValuesStrategy(Strategy strategy) { - if (Strategy.ONLY_SHARE_VALUES == strategy - || Strategy.SHARE_COLLECTION_ELEMENTS == strategy) { - return Strategy.SHARE; - } - return strategy; + return Strategy.ONLY_SHARE_VALUES == strategy || Strategy.SHARE_COLLECTION_ELEMENTS == strategy + ? Strategy.SHARE + : strategy; } } @@ -232,7 +223,7 @@ public class DeepCopy { return new ImplementationInstantiation() { @Override protected Object createDefault() { - return new ArrayList(); + return new ArrayList<>(); } }.instantiate(klass); } @@ -242,8 +233,8 @@ public class DeepCopy { private static abstract class ImplementationInstantiation { private static final String[] VETOED_IMPLEMENTATIONS = { - "PersistentSet", "PersistentList", "PersistentMap", - "PersistentSortedSet" }; + "PersistentSet", "PersistentList", "PersistentMap", "PersistentSortedSet" + }; ImplementationInstantiation() { } @@ -251,10 +242,9 @@ public class DeepCopy { T instantiate(Class type) { if (!isVetoed(type)) { try { - Constructor constructor = type - .getConstructor(); + Constructor constructor = type.getConstructor(); return (T) type.cast(constructor.newInstance()); - } catch (Exception e) { + } catch (Exception ignored) { } } return (T) createDefault(); @@ -273,12 +263,6 @@ public class DeepCopy { protected abstract Object createDefault(); } - private static List DEFAULT_CUSTOM_COPIERS = Arrays - . asList(new DateCopy(), new SetCopy(), new MapCopy(), - new ListCopy()); - - private Map alreadyCopiedObjects = new HashMap(); - private static class ByIdentity { private final Object wrapped; @@ -318,13 +302,16 @@ public class DeepCopy { if (couldBeProxyValue == null) { return null; } + T value = desproxify(couldBeProxyValue); if (alreadyCopiedObjects.containsKey(byIdentity(value))) { return (T) alreadyCopiedObjects.get(byIdentity(value)); } + if (Strategy.SHARE == strategy || isImmutable(value)) { return value; } + ICustomCopy copier = findCopier(value); if (copier != null) { Object resultData = copier.instantiateCopy(strategy, value); @@ -332,18 +319,18 @@ public class DeepCopy { copier.copyDataToResult(this, value, strategy, resultData); return (T) resultData; } + T result = instantiateUsingDefaultConstructor(getTypedClassFrom(value)); alreadyCopiedObjects.put(byIdentity(value), result); copyProperties(value, result); - callAferCopyHooks(result); + callAfterCopyHooks(result); return result; } private T desproxify(T value) { if (value instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) value; - return (T) proxy.getHibernateLazyInitializer() - .getImplementation(); + return (T) proxy.getHibernateLazyInitializer().getImplementation(); } return value; } @@ -364,9 +351,7 @@ public class DeepCopy { } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { - throw new IllegalArgumentException( - "could not invoke default no-args constructor for " - + klass, e); + throw new IllegalArgumentException("could not invoke default no-args constructor for " + klass, e); } try { return constructor.newInstance(); @@ -382,7 +367,7 @@ public class DeepCopy { if (!isIgnored(each)) { Object sourceValue = readFieldValue(source, each); if (sourceValue != null) { - Strategy strategy = getStrategy(each, sourceValue); + Strategy strategy = getStrategy(each); try { writeFieldValue(target, each, copy(sourceValue, strategy)); } catch (Exception e) { @@ -395,7 +380,7 @@ public class DeepCopy { } private List getAllFieldsFor(Object source) { - List result = new ArrayList(); + List result = new ArrayList<>(); Class currentClass = source.getClass(); while (currentClass != null) { result.addAll(Arrays.asList(currentClass.getDeclaredFields())); @@ -433,7 +418,7 @@ public class DeepCopy { } } - private Strategy getStrategy(Field field, Object sourceValue) { + private Strategy getStrategy(Field field) { OnCopy onCopy = field.getAnnotation(OnCopy.class); return onCopy != null ? onCopy.value() : null; } @@ -447,7 +432,7 @@ public class DeepCopy { return null; } - private void callAferCopyHooks(Object value) { + private void callAfterCopyHooks(Object value) { assert value != null; for (Method each : getAfterCopyHooks(value.getClass())) { each.setAccessible(true); @@ -461,7 +446,7 @@ public class DeepCopy { private List getAfterCopyHooks(Class klass) { Class current = klass; - List result = new ArrayList(); + List result = new ArrayList<>(); while (current != null) { result.addAll(getAfterCopyDeclaredAt(current)); current = current.getSuperclass(); @@ -470,7 +455,7 @@ public class DeepCopy { } private List getAfterCopyDeclaredAt(Class klass) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (Method each : klass.getDeclaredMethods()) { if (isAfterCopyHook(each)) { result.add(each); diff --git a/libreplan-business/src/test/java/org/libreplan/business/test/planner/entities/GenericResourceAllocationTest.java b/libreplan-business/src/test/java/org/libreplan/business/test/planner/entities/GenericResourceAllocationTest.java index cd7dba587..4b4f60f2b 100644 --- a/libreplan-business/src/test/java/org/libreplan/business/test/planner/entities/GenericResourceAllocationTest.java +++ b/libreplan-business/src/test/java/org/libreplan/business/test/planner/entities/GenericResourceAllocationTest.java @@ -38,7 +38,15 @@ import static org.libreplan.business.workingday.EffortDuration.hours; import static org.libreplan.business.workingday.EffortDuration.zero; import java.math.BigDecimal; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Map; +import java.util.HashMap; +import java.util.Collection; +import java.util.Collections; import org.apache.commons.lang3.Validate; import org.easymock.IAnswer; diff --git a/libreplan-business/src/test/java/org/libreplan/business/test/resources/entities/ResourceTest.java b/libreplan-business/src/test/java/org/libreplan/business/test/resources/entities/ResourceTest.java index 14d5b09f7..090ff8ac5 100644 --- a/libreplan-business/src/test/java/org/libreplan/business/test/resources/entities/ResourceTest.java +++ b/libreplan-business/src/test/java/org/libreplan/business/test/resources/entities/ResourceTest.java @@ -33,8 +33,6 @@ import static org.libreplan.business.test.resources.daos.CriterionSatisfactionDA import static org.libreplan.business.test.resources.daos.CriterionSatisfactionDAOTest.year; import static org.libreplan.business.workingday.EffortDuration.hours; -import java.util.*; - import org.joda.time.Days; import org.joda.time.LocalDate; import org.junit.Before; @@ -60,6 +58,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + /** * Tests for {@link Resource}. *
diff --git a/libreplan-business/src/test/java/org/libreplan/business/test/scenarios/bootstrap/ScenariosBootstrapTest.java b/libreplan-business/src/test/java/org/libreplan/business/test/scenarios/bootstrap/ScenariosBootstrapTest.java index 79e120bb0..6bf14ff4c 100644 --- a/libreplan-business/src/test/java/org/libreplan/business/test/scenarios/bootstrap/ScenariosBootstrapTest.java +++ b/libreplan-business/src/test/java/org/libreplan/business/test/scenarios/bootstrap/ScenariosBootstrapTest.java @@ -27,7 +27,9 @@ import static org.junit.Assert.assertTrue; import static org.libreplan.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE; import static org.libreplan.business.test.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_TEST_FILE; +import java.util.Date; import java.util.Set; +import java.util.UUID; import javax.annotation.Resource; @@ -48,7 +50,6 @@ import org.libreplan.business.scenarios.daos.IOrderVersionDAO; import org.libreplan.business.scenarios.daos.IScenarioDAO; import org.libreplan.business.scenarios.entities.OrderVersion; import org.libreplan.business.scenarios.entities.Scenario; -import org.libreplan.business.test.scenarios.daos.ScenarioDAOTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -106,8 +107,7 @@ public class ScenariosBootstrapTest { deleteSchedulingStatesByOrderVersion.executeUpdate(); session.flush(); - Query deleteSchedulingDataForVersion = - session.createSQLQuery("DELETE FROM scheduling_data_for_version"); + Query deleteSchedulingDataForVersion = session.createSQLQuery("DELETE FROM scheduling_data_for_version"); deleteSchedulingDataForVersion.executeUpdate(); session.flush(); @@ -115,17 +115,22 @@ public class ScenariosBootstrapTest { for (Order order : orderDAO.findAll()) { orderDAO.remove(order.getId()); } - // TODO: replace with Hibernate Criteria - for (Scenario scenario : scenarioDAO.getAll()) { - if (!"master".equals(scenario.getName())) { + + Scenario masterScenario = null; + try { + masterScenario = PredefinedScenarios.MASTER.getScenario(); + } catch (RuntimeException ignored) { + } + + if ( masterScenario != null ) { + for (Scenario scenario : scenarioDAO.getAllExcept(masterScenario)) { scenarioDAO.remove(scenario.getId()); } - else { - for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) { - scenario.removeVersion(orderVersion); - } - session.flush(); + + for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) { + masterScenario.removeVersion(orderVersion); } + session.flush(); } for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) { @@ -140,8 +145,18 @@ public class ScenariosBootstrapTest { private Order givenOrderStored() { - // TODO : refactor this ( do not use method from other testClass ) - return ScenarioDAOTest.createOrderStored(orderDAO, configurationDAO); + return createOrderStored(orderDAO, configurationDAO); + } + + public Order createOrderStored(IOrderDAO orderDAO, IConfigurationDAO configurationDAO) { + Order order = Order.create(); + order.setInitDate(new Date()); + order.setName("name-" + UUID.randomUUID().toString()); + order.setCode("code-" + UUID.randomUUID().toString()); + order.setCalendar(configurationDAO.getConfiguration().getDefaultCalendar()); + orderDAO.save(order); + + return order; } @Test diff --git a/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/DeepCopyTest.java b/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/DeepCopyTest.java index c16fab46d..9acc0a4a6 100644 --- a/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/DeepCopyTest.java +++ b/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/DeepCopyTest.java @@ -43,6 +43,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.Collections; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; @@ -58,7 +59,6 @@ import org.libreplan.business.util.deepcopy.EntityExamples.TestEnum; /** * @author Óscar González Fernández - * */ public class DeepCopyTest { @@ -69,8 +69,7 @@ public class DeepCopyTest { @Test(expected = IllegalArgumentException.class) public void theEntityToCopyMustHaveNotEmptyConstructor() { - EntityWithoutNoArgsConstructor entity = new EntityWithoutNoArgsConstructor( - "bla"); + EntityWithoutNoArgsConstructor entity = new EntityWithoutNoArgsConstructor("bla"); new DeepCopy().copy(entity); } @@ -106,11 +105,13 @@ public class DeepCopyTest { @Test public void itKnowsSomeTypesAreImmutable() { - Iterable> immutableTypes = Arrays.> asList( + Iterable> immutableTypes = Arrays.asList( String.class, BigDecimal.class, Double.class, Float.class, Integer.class, Short.class, Byte.class, Character.class, LocalDate.class, Boolean.class, DateTime.class, double.class, - float.class, int.class, short.class, byte.class, char.class); + float.class, int.class, short.class, byte.class, + char.class); + assertThat(immutableTypes, everyItem(immutable())); } @@ -150,8 +151,7 @@ public class DeepCopyTest { @Test public void setsAreCopied() { EntityA entityA = new EntityA(); - HashSet originalSet = new HashSet(asList("test", - 2, 3, new Date())); + HashSet originalSet = new HashSet<>(asList("test", 2, 3, new Date())); entityA.setSetProperty(originalSet); EntityA copy = new DeepCopy().copy(entityA); assertEquals(originalSet, copy.getSetProperty()); @@ -161,8 +161,7 @@ public class DeepCopyTest { @Test public void theSetImplementationClassIsPreservedIfPossible() { EntityA entityA = new EntityA(); - Set originalSet = new LinkedHashSet(asList("test", 2, - 3, new Date())); + Set originalSet = new LinkedHashSet<>(asList("test", 2, 3, new Date())); entityA.setSetProperty(originalSet); EntityA copy = new DeepCopy().copy(entityA); assertThat(copy.getSetProperty(), instanceOf(LinkedHashSet.class)); @@ -171,9 +170,8 @@ public class DeepCopyTest { @Test public void setsInsideSetsAreRecursivelyCopiedWithoutProblem() { EntityA entityA = new EntityA(); - HashSet innerSet = new HashSet(asList("bla", 3)); - HashSet originalSet = new HashSet(asList("test", 2, 3, - new Date(), innerSet)); + HashSet innerSet = new HashSet<>(asList("bla", 3)); + HashSet originalSet = new HashSet<>(asList("test", 2, 3, new Date(), innerSet)); entityA.setSetProperty(originalSet); EntityA copy = new DeepCopy().copy(entityA); assertEquals(originalSet, copy.getSetProperty()); @@ -183,7 +181,7 @@ public class DeepCopyTest { @Test public void mapsAreCopied() { EntityA entityA = new EntityA(); - HashMap originalMap = new HashMap(); + HashMap originalMap = new HashMap<>(); originalMap.put("aa", "blabla"); entityA.setMapProperty(originalMap); EntityA copy = new DeepCopy().copy(entityA); @@ -194,7 +192,7 @@ public class DeepCopyTest { @Test public void mapImplementationIsPreservedIfPossible() { EntityA entityA = new EntityA(); - LinkedHashMap mapProperty = new LinkedHashMap(); + LinkedHashMap mapProperty = new LinkedHashMap<>(); mapProperty.put("ab", "abc"); entityA.setMapProperty(mapProperty); EntityA copy = new DeepCopy().copy(entityA); @@ -204,7 +202,7 @@ public class DeepCopyTest { @Test public void listsAreCopied() { EntityA entityA = new EntityA(); - ArrayList originalList = new ArrayList(); + ArrayList originalList = new ArrayList<>(); originalList.add(2); originalList.add(10); originalList.add("abla"); @@ -217,7 +215,7 @@ public class DeepCopyTest { @Test public void listImplementationIsPreservedIfPossible() { EntityA entityA = new EntityA(); - LinkedList originalList = new LinkedList(); + LinkedList originalList = new LinkedList<>(); originalList.add(2); entityA.setListProperty(originalList); EntityA copy = new DeepCopy().copy(entityA); @@ -244,7 +242,7 @@ public class DeepCopyTest { @Test public void sharedCollectionsAreCopiedWithTheSameReference() { EntityA entityA = new EntityA(); - List originalList = Arrays.asList("bla"); + List originalList = Collections.singletonList("bla"); entityA.setSharedListProperty(originalList); EntityA copy = new DeepCopy().copy(entityA); assertSame(originalList, copy.getSharedListProperty()); @@ -253,64 +251,54 @@ public class DeepCopyTest { @Test public void sharedCollectionElementsKeptTheReferences() { EntityA entityA = new EntityA(); - HashSet originalSet = new HashSet(); + HashSet originalSet = new HashSet<>(); originalSet.add(new Date()); entityA.setSharedElementsProperty(originalSet); EntityA copy = new DeepCopy().copy(entityA); assertNotSame(originalSet, copy.getSharedElementsProperty()); - assertSame(originalSet.iterator().next(), copy - .getSharedElementsProperty().iterator().next()); + assertSame(originalSet.iterator().next(), copy.getSharedElementsProperty().iterator().next()); } @Test public void sharedKeyElementsKeepTheSameReferencesForTheKeys() { EntityA entityA = new EntityA(); - Map originalMap = new HashMap(); + Map originalMap = new HashMap<>(); EntityA originalValue = new EntityA(); Date originalKey = new Date(); originalMap.put(originalKey, originalValue); entityA.setSharedKeysMapProperty(originalMap); EntityA copy = new DeepCopy().copy(entityA); - Map sharedKeysMapProperty = copy - .getSharedKeysMapProperty(); - assertSame(originalKey, sharedKeysMapProperty.keySet().iterator() - .next()); - assertNotSame(originalValue, sharedKeysMapProperty.values().iterator() - .next()); + Map sharedKeysMapProperty = copy.getSharedKeysMapProperty(); + assertSame(originalKey, sharedKeysMapProperty.keySet().iterator().next()); + assertNotSame(originalValue, sharedKeysMapProperty.values().iterator().next()); } @Test public void sharedValueElementsKeepTheSameReferencesForTheValues() { EntityA entityA = new EntityA(); - Map originalMap = new HashMap(); + Map originalMap = new HashMap<>(); EntityA originalValue = new EntityA(); Date originalKey = new Date(); originalMap.put(originalKey, originalValue); entityA.setSharedValuesMapProperty(originalMap); EntityA copy = new DeepCopy().copy(entityA); - Map copiedMap = copy - .getSharedValuesMapProperty(); - assertNotSame(originalKey, copiedMap.keySet().iterator() - .next()); - assertSame(originalValue, copiedMap.values().iterator() - .next()); + Map copiedMap = copy.getSharedValuesMapProperty(); + assertNotSame(originalKey, copiedMap.keySet().iterator().next()); + assertSame(originalValue, copiedMap.values().iterator().next()); } @Test public void aSharedCollectionElementsMapKeepTheSameReferencesForTheKeysAndTheValues() { EntityA entityA = new EntityA(); - Map originalMap = new HashMap(); + Map originalMap = new HashMap<>(); EntityA originalValue = new EntityA(); Date originalKey = new Date(); originalMap.put(originalKey, originalValue); entityA.setSharedCollectionElementsMapProperty(originalMap); EntityA copy = new DeepCopy().copy(entityA); - Map copiedMap = copy - .getSharedCollectionElementsMapProperty(); - assertSame(originalKey, copiedMap.keySet().iterator() - .next()); - assertSame(originalValue, copiedMap.values().iterator() - .next()); + Map copiedMap = copy.getSharedCollectionElementsMapProperty(); + assertSame(originalKey, copiedMap.keySet().iterator().next()); + assertSame(originalValue, copiedMap.values().iterator().next()); } @Test @@ -342,12 +330,11 @@ public class DeepCopyTest { EntityA entityA = new EntityA(); parent.setEntityAProperty(entityA); entityA.setParentProperty(parent); - HashSet originalSet = new HashSet(); + HashSet originalSet = new HashSet<>(); parent.setSetProperty(originalSet); entityA.setSetProperty(originalSet); Parent copy = new DeepCopy().copy(parent); - assertSame(copy.getSetProperty(), copy.getEntityAProperty() - .getSetProperty()); + assertSame(copy.getSetProperty(), copy.getEntityAProperty().getSetProperty()); } @Test @@ -382,8 +369,8 @@ public class DeepCopyTest { public void equalObjectsButDifferentAreNotReused() { EntityA entityA = new EntityA(); DeepCopy deepCopy = new DeepCopy(); - entityA.setSet1(new HashSet()); - entityA.setSet2(new HashSet()); + entityA.setSet1(new HashSet<>()); + entityA.setSet2(new HashSet<>()); EntityA copied = deepCopy.copy(entityA); assertNotSame(copied.getSet1(), copied.getSet2()); } diff --git a/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/EntityExamples.java b/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/EntityExamples.java index 32a215c22..0129f14b6 100644 --- a/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/EntityExamples.java +++ b/libreplan-business/src/test/java/org/libreplan/business/util/deepcopy/EntityExamples.java @@ -30,7 +30,6 @@ import java.util.Set; /** * @author Óscar González Fernández - * */ public class EntityExamples { @@ -40,15 +39,14 @@ public class EntityExamples { public enum TestEnum { A { }, - B; + B } public static class Parent { + private EntityA entityAProperty; - private String prueba = "bar"; - - private Set setProperty = new HashSet(); + private Set setProperty = new HashSet<>(); public EntityA getEntityAProperty() { return entityAProperty; @@ -70,9 +68,8 @@ public class EntityExamples { public static class EntityA { - private static final String staticProperty = "foo"; - private final String finalProperty = "bar"; + private String stringProperty; private int intProperty = 2; @@ -83,7 +80,7 @@ public class EntityExamples { private Set setProperty; - private Map mapProperty = new HashMap(); + private Map mapProperty = new HashMap<>(); private List listProperty; @@ -314,9 +311,6 @@ public class EntityExamples { } public static class SubClassExample extends SuperclassExample { - - private int intProperty; - } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/IJiraOrderElementSynchronizer.java b/libreplan-webapp/src/main/java/org/libreplan/importers/IJiraOrderElementSynchronizer.java index 04a7b5711..49b73524c 100755 --- a/libreplan-webapp/src/main/java/org/libreplan/importers/IJiraOrderElementSynchronizer.java +++ b/libreplan-webapp/src/main/java/org/libreplan/importers/IJiraOrderElementSynchronizer.java @@ -30,24 +30,21 @@ import org.libreplan.business.orders.entities.OrderSyncInfo; import org.libreplan.importers.jira.IssueDTO; /** - * Synchronize order elements inclusive progress assignments and measurements of - * an existing order with Jira issues. - * - * Jira issues will be retrieved from Jira RESTful web service using - * {@link JiraRESTClient} + * Synchronize order elements inclusive progress assignments and measurements of an existing order with Jira issues. + * Jira issues will be retrieved from Jira RESTful web service using {@link JiraRESTClient}. * * @author Miciele Ghiorghis */ public interface IJiraOrderElementSynchronizer { /** - * Gets all distinct jira lables from an external 'php' script. + * Gets all distinct JIRA lables from an external 'php' script. * - * FIXME: This is because at this moment Jira doesn't support Labels - * request. As workaround we build a simple php script to do the query in - * Jira database and returns a comma separated string(labels). Once Jira - * supports the labels request this method will be modified. More info: - * https://jira.atlassian.com/browse/JRA-29409 + * FIXME: This is because at this moment Jira doesn't support Labels request. + * As workaround we build a simple php script to do the query in + * Jira database and returns a comma separated string(labels). + * Once Jira supports the labels request this method will be modified. + * More info: https://jira.atlassian.com/browse/JRA-29409 * * @return A list of labels * @throws ConnectorException @@ -56,13 +53,12 @@ public interface IJiraOrderElementSynchronizer { List getAllJiraLabels() throws ConnectorException; /** - * Get all jira issues based on the specified label parameter - * from jira RESTFul web service + * Get all JIRA issues based on the specified label parameter from JIRA RESTFul web service. * * @param label - * search criteria for jira issues + * search criteria for JIRA issues * - * @return list of jira issues + * @return list of JIRA issues * @throws ConnectorException * if connector not found or contains invalid connection values */ @@ -70,26 +66,23 @@ public interface IJiraOrderElementSynchronizer { /** * Synchronizes the list of {@link OrderElement}s, - * {@link DirectAdvanceAssignment}s and {@link AdvanceMeasurement}s of the - * given {@link Order} with jira issues. + * {@link DirectAdvanceAssignment}s and {@link AdvanceMeasurement}s of the given {@link Order} with JIRA issues. * - * Loops through all jira issues and check if an - * {@link OrderElement} of the given order exists. If it - * exists, update the {@link OrderElement} with the issue item. If not - * create new {@link OrderElement}, update it with the issue item and add to - * the order and start synchronization of - * {@link DirectAdvanceAssignment} and {@link AdvanceMeasurement} + * Loops through all JIRA issues and check if an {@link OrderElement} of the given order exists. + * If it exists, update the {@link OrderElement} with the issue item. + * If not create new {@link OrderElement}, update it with the issue item and add to + * the order and start synchronization of {@link DirectAdvanceAssignment} and {@link AdvanceMeasurement}. * * @param order * an existing order where its orderElements will be synchronized - * with jira issues + * with JIRA issues * @param issues - * jira issues + * JIRA issues */ void syncOrderElementsWithJiraIssues(List issues, Order order); /** - * Saves synchronization info + * Saves synchronization info. * * @param key * the key(label) @@ -99,7 +92,7 @@ public interface IJiraOrderElementSynchronizer { void saveSyncInfo(String key, Order order); /** - * Gets the most recent synchronized info + * Gets the most recent synchronized info. * * @param order * the order @@ -108,17 +101,15 @@ public interface IJiraOrderElementSynchronizer { OrderSyncInfo getOrderLastSyncInfo(Order order); /** - * returns synchronization info, success or fail info + * Returns synchronization info, success or fail info. */ SynchronizationInfo getSynchronizationInfo(); /** - * Synchronize order elements with JIRA issues if they already synchronized - * using - * {@link IJiraOrderElementSynchronizer#syncOrderElementsWithJiraIssues(List, Order) + * Synchronize order elements with JIRA issues if they already synchronized using + * {@link IJiraOrderElementSynchronizer#syncOrderElementsWithJiraIssues(List, Order). * - * It gets then an already synchronized orders from the - * {@link OrderSyncInfo} and re-synchronize them + * It gets then an already synchronized orders from the {@link OrderSyncInfo} and re-synchronize them. * * @return a list of {@link SynchronizationInfo} * diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/OrderElementDTO.java b/libreplan-webapp/src/main/java/org/libreplan/importers/OrderElementDTO.java index f1c0e8b2b..c6b0217b9 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/importers/OrderElementDTO.java +++ b/libreplan-webapp/src/main/java/org/libreplan/importers/OrderElementDTO.java @@ -26,8 +26,8 @@ import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.planner.entities.TaskElement; /** - * Class that represents no persistent imported tasks.
- * + * Class that represents no persistent imported tasks. + *
* At these moment it only represent the tasks that can have any subtasks. * * @author Alba Carro Pérez @@ -81,7 +81,7 @@ public class OrderElementDTO implements IHasTaskAssociated { public ConstraintDTO constraint; /** - * Contraint date of this task. + * Constraint date of this task. */ public Date constraintDate; @@ -90,14 +90,14 @@ public class OrderElementDTO implements IHasTaskAssociated { */ public TaskElement taskElement; - @Override - public TaskElement getTaskAssociated() { - return taskElement; - } - /** * Name of the calendar that this OrderElementDTO is linked to. */ public String calendarName = null; + @Override + public TaskElement getTaskAssociated() { + return taskElement; + } + } diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java index 70f7fd0aa..6b4486bf9 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java +++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/EmailConnectionValidator.java @@ -20,7 +20,6 @@ package org.libreplan.importers.notifications; import org.libreplan.business.common.daos.IConnectorDAO; -import org.libreplan.business.common.entities.Connector; import org.libreplan.business.common.entities.ConnectorProperty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; @@ -94,26 +93,30 @@ public class EmailConnectionValidator { Transport transport = null; try { - if ( protocol.equals("SMTP") ) { + if ( "SMTP".equals(protocol) ) { properties.setProperty("mail.smtp.port", port); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(properties, null); transport = session.getTransport("smtp"); - if ( "".equals(usrnme) && "".equals(psswrd) ) + if ( "".equals(usrnme) && "".equals(psswrd) ) { transport.connect(); + } - } else if ( protocol.equals("STARTTLS") ) { + + } else if ( "STARTTLS".equals(protocol) ) { properties.setProperty("mail.smtps.port", port); properties.setProperty("mail.smtps.host", host); - properties.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000)); + properties.setProperty("mail.smtps.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(properties, null); transport = session.getTransport("smtps"); - if ( !"".equals(usrnme) && psswrd != null ) + if ( !"".equals(usrnme) && psswrd != null ) { transport.connect(host, usrnme, psswrd); + } + } if ( transport != null && transport.isConnected() ) return true; @@ -128,19 +131,20 @@ public class EmailConnectionValidator { } public List getEmailConnectorProperties() { - Connector connector = connectorDAO.findUniqueByName("E-mail"); - - return connector.getProperties(); + return connectorDAO.findUniqueByName("E-mail").getProperties(); } public boolean isConnectionActivated() { List emailConnectorProperties = getEmailConnectorProperties(); for (ConnectorProperty item : emailConnectorProperties) { - if ( item.getKey().equals("Activated") ) - if ( item.getValue().equals("Y") ) + if ( "Activated".equals(item.getKey()) ) { + if ( "Y".equals(item.getValue()) ) { return true; - else break; + } else { + break; + } + } } return false; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java index c371f14b2..a914c859b 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java +++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldFinish.java @@ -47,7 +47,7 @@ import java.util.List; * and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_FINISH}. * Data will be send when current day equals to finish date. * - * @author Created by Vova Perebykivskyi on 21.01.2016. + * @author Vova Perebykivskyi */ @Component @@ -77,9 +77,11 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob { List notifications = emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH); - for (int i = 0; i < notifications.size(); i++) - if ( composeMessageForUser(notifications.get(i)) ) + for (int i = 0; i < notifications.size(); i++) { + if ( composeMessageForUser(notifications.get(i)) ) { deleteSingleNotification(notifications.get(i)); + } + } } } } @@ -120,11 +122,10 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob { private void sendEmailNotificationAboutTaskShouldFinish(TaskElement item){ - List> list = new ArrayList<>(); - list.addAll(item.getAllResourceAllocations()); + List> resourceAllocations = new ArrayList<>(item.getAllResourceAllocations()); List resources = new ArrayList<>(); - for (ResourceAllocation allocation : list) + for (ResourceAllocation allocation : resourceAllocations) resources.add(allocation.getAssociatedResources().get(0)); for (Resource resourceItem : resources){ diff --git a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java index 2cde7ac07..117232d96 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java +++ b/libreplan-webapp/src/main/java/org/libreplan/importers/notifications/realization/SendEmailOnTaskShouldStart.java @@ -47,7 +47,7 @@ import java.util.List; * and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_START}. * Data will be send if current data equals to start date. * - * @author Created by Vova Perebykivskyi on 20.01.2016. + * @author Vova Perebykivskyi */ @Component @@ -79,8 +79,9 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob { emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START); for (EmailNotification notification : notifications) - if ( composeMessageForUser(notification) ) + if ( composeMessageForUser(notification) ) { deleteSingleNotification(notification); + } } } } @@ -118,11 +119,10 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob { } private void sendEmailNotificationAboutTaskShouldStart(TaskElement item) { - List> list = new ArrayList<>(); - list.addAll(item.getAllResourceAllocations()); + List> resourceAllocations = new ArrayList<>(item.getAllResourceAllocations()); List resources = new ArrayList<>(); - for (ResourceAllocation allocation : list) + for (ResourceAllocation allocation : resourceAllocations) resources.add(allocation.getAssociatedResources().get(0)); for (Resource resourceItem : resources) { diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/I18nHelper.java b/libreplan-webapp/src/main/java/org/libreplan/web/I18nHelper.java index dfc46bd8c..4bef3350e 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/I18nHelper.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/I18nHelper.java @@ -42,6 +42,9 @@ public class I18nHelper { private static HashMap localesCache = new HashMap<>(); + private I18nHelper() { + } + public static I18n getI18n() { setPreferredLocale(); @@ -89,11 +92,9 @@ public class I18nHelper { return i18n; } - private I18nHelper() { - } - - //TODO It should be changed since JDK9. /** + * TODO It should be changed since JDK9 + * * Use of '_' as an identifier might not be supported in releases after Java SE 8. * * @param str diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java index 04bbe25b5..22d7c2d04 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/ConfigurationController.java @@ -172,7 +172,8 @@ public class ConfigurationController extends GenericForwardComposer { private String LOGO_PREVIEW_COMPONENT = "logoPreview"; - public ConfigurationController() {} + public ConfigurationController() { + } @Override public void doAfterCompose(Component comp) throws Exception { @@ -389,7 +390,6 @@ public class ConfigurationController extends GenericForwardComposer { public void testConnection() { if (selectedConnector == null) { messages.showMessage(Level.ERROR, _("Please select a connector to test it")); - return; } @@ -487,6 +487,7 @@ public class ConfigurationController extends GenericForwardComposer { if ("SMTP".equals(protocolsCombobox.getSelectedItem().getLabel())) { props.setProperty("mail.smtp.port", port); props.setProperty("mail.smtp.host", host); + props.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(props, null); transport = session.getTransport("smtp"); @@ -497,6 +498,7 @@ public class ConfigurationController extends GenericForwardComposer { else if (STARTTLS_PROTOCOL.equals(protocolsCombobox.getSelectedItem().getLabel())) { props.setProperty("mail.smtps.port", port); props.setProperty("mail.smtps.host", host); + props.setProperty("mail.smtps.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(props, null); transport = session.getTransport("smtps"); @@ -1588,7 +1590,8 @@ public class ConfigurationController extends GenericForwardComposer { ch = in.read(buffer); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } finally { try { @@ -1596,7 +1599,8 @@ public class ConfigurationController extends GenericForwardComposer { out.close(); in.close(); - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } Util.setLogoFromTarget(media.getName()); @@ -1651,6 +1655,7 @@ public class ConfigurationController extends GenericForwardComposer { try { fileToDelete = ContextLoaderListener.getCurrentWebApplicationContext().getResource(name).getFile(); fileToDelete.delete(); - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/GatheredUsageStats.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/GatheredUsageStats.java index 275ae1ea4..d77910f37 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/GatheredUsageStats.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/GatheredUsageStats.java @@ -121,16 +121,38 @@ public class GatheredUsageStats { private String oldestDate; public GatheredUsageStats() { - this.userDAO = (IUserDAO) SpringUtil.getBean("userDAO"); - this.orderModel = (IOrderModel) SpringUtil.getBean("orderModel"); - this.workReportModel = (IWorkReportModel) SpringUtil.getBean("workReportModel"); - this.workerModel = (IWorkerModel) SpringUtil.getBean("workerModel"); - this.machineModel = (IMachineModel) SpringUtil.getBean("machineModel"); - this.expenseSheetModel = (IExpenseSheetModel) SpringUtil.getBean("expenseSheetModel"); - this.materialsModel = (IMaterialsModel) SpringUtil.getBean("materialsModel"); + if ( this.userDAO == null ) { + this.userDAO = (IUserDAO) SpringUtil.getBean("userDAO"); + } - this.assignedTaskQualityFormsToOrderElementModel = (IAssignedTaskQualityFormsToOrderElementModel) - SpringUtil.getBean("assignedTaskQualityFormsToOrderElementModel"); + if ( this.orderModel == null ) { + this.orderModel = (IOrderModel) SpringUtil.getBean("orderModel"); + } + + if ( this.workReportModel == null ) { + this.workReportModel = (IWorkReportModel) SpringUtil.getBean("workReportModel"); + } + + if ( this.workerModel == null ) { + this.workerModel = (IWorkerModel) SpringUtil.getBean("workerModel"); + } + + if ( this.machineModel == null ) { + this.machineModel = (IMachineModel) SpringUtil.getBean("machineModel"); + } + + if ( this.expenseSheetModel == null ) { + this.expenseSheetModel = (IExpenseSheetModel) SpringUtil.getBean("expenseSheetModel"); + } + + if ( this.materialsModel == null ) { + this.materialsModel = (IMaterialsModel) SpringUtil.getBean("materialsModel"); + } + + if ( this.assignedTaskQualityFormsToOrderElementModel == null ) { + this.assignedTaskQualityFormsToOrderElementModel = (IAssignedTaskQualityFormsToOrderElementModel) + SpringUtil.getBean("assignedTaskQualityFormsToOrderElementModel"); + } initialize(); } @@ -160,7 +182,8 @@ public class GatheredUsageStats { sb.append(Integer.toString((anEncoded & 0xff) + 0x100, 16).substring(1)); } - } catch (NoSuchAlgorithmException | UnsupportedEncodingException ignored) {} + } catch (NoSuchAlgorithmException | UnsupportedEncodingException ignored) { + } return sb.toString(); } @@ -229,7 +252,6 @@ public class GatheredUsageStats { connection.getInputStream(); } catch (IOException ignored) { - } finally { if ( connection != null ) { connection.disconnect(); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/TemplateController.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/TemplateController.java index 07c1c67af..dbb92a641 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/TemplateController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/TemplateController.java @@ -91,11 +91,7 @@ public class TemplateController extends GenericForwardComposer { } public List getScenarios() { - if ( templateModel == null ) { - return Collections.emptyList(); - } - - return templateModel.getScenarios(); + return templateModel == null ? Collections.emptyList() : templateModel.getScenarios(); } public String getCompanyLogoURL() { @@ -183,7 +179,6 @@ public class TemplateController extends GenericForwardComposer { return asDisplayProperty(templateModel.hasChangedDefaultPassword(mandatoryUser)); } - private String asDisplayProperty(boolean passwordChanged) { return passwordChanged ? "none" : "inline"; } @@ -229,13 +224,9 @@ public class TemplateController extends GenericForwardComposer { } public boolean isNewVersionAvailable() { - if ( templateModel.isCheckNewVersionEnabled() ) { - - if ( VersionInformation.isNewVersionAvailable() ){ - lastVersionNumber = VersionInformation.getLastVersion(); - - return true; - } + if ( templateModel.isCheckNewVersionEnabled() && VersionInformation.isNewVersionAvailable() ) { + lastVersionNumber = VersionInformation.getLastVersion(); + return true; } return false; @@ -243,14 +234,15 @@ public class TemplateController extends GenericForwardComposer { public String getUsername() { CustomUser user = SecurityUtils.getLoggedUser(); - return (user == null) ? "" : user.getUsername(); } - public String getVersionMessage(){ - return _("A new version ") + - lastVersionNumber + - _(" of LibrePlan is available. Please check next link for more information:"); + /** + * Should be public! + * Used in template.zul + */ + public String getVersionMessage() { + return _("A new version ") + lastVersionNumber + _(" of LibrePlan is available. Please check next link for more information:"); } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/Util.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/Util.java index 4d7885fd5..642858ed3 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/Util.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/Util.java @@ -104,7 +104,8 @@ public class Util { */ public static Image logo; - private Util() {} + private Util() { + } /** * Forces to reload the bindings of the provided components if there is an associated {@link DefaultBinder}. @@ -201,7 +202,7 @@ public class Util { public static void saveBindings(Component... toReload) { for (Component reload : toReload) { - + /* TODO resolve deprecated */ DataBinder binder = Util.getBinder(reload); if (binder != null) { @@ -224,7 +225,7 @@ public class Util { } } - public static void createBindingsFor(org.zkoss.zk.ui.Component result) { + public static void createBindingsFor(Component result) { if (ignoreCreateBindings.get()) { return; } @@ -290,7 +291,6 @@ public class Util { public static Textbox bind(Textbox textBox, Getter getter) { textBox.setValue(getter.get()); textBox.setDisabled(true); - return textBox; } @@ -323,16 +323,15 @@ public class Util { * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Textbox}. * - * @param textBox - * The {@link Textbox} to be bound + * @param comboBox + * The {@link Combobox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. - * @return The {@link Textbox} bound + * @return The {@link Combobox} bound */ public static Combobox bind(Combobox comboBox, Getter getter) { comboBox.setSelectedItem(getter.get()); comboBox.setDisabled(true); - return comboBox; } @@ -340,13 +339,14 @@ public class Util { * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * used to get the value that is going to be showed in the {@link Textbox}. * The {@link Setter} will be used to store the value inserted by the user in the {@link Textbox}. - * @param textBox - * The {@link Textbox} to be bound + * + * @param comboBox + * The {@link Combobox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. * @param setter * The {@link Setter} interface that will implement a set method. - * @return The {@link Textbox} bound + * @return The {@link Combobox} bound */ public static Combobox bind(final Combobox comboBox, final Getter getter, @@ -455,7 +455,7 @@ public class Util { * Binds a {@link Timebox} with a {@link Getter}. * The {@link Getter} will be used to get the value that is going to be showed in the {@link Timebox}. * - * @param dateBox + * @param timeBox * The {@link Timebox} to be bound * @param getter * The {@link Getter} interface that will implement a get method. @@ -549,7 +549,6 @@ public class Util { public static Checkbox bind(final Checkbox checkBox, final Getter getter) { checkBox.setChecked(getter.get()); checkBox.setDisabled(true); - return checkBox; } @@ -558,7 +557,7 @@ public class Util { * The {@link Getter} will be used to get the value that is going to be showed in the {@link Checkbox}. * The {@link Setter} will be used to store the value inserted by the user in the {@link Checkbox}. * - * @param decimalBox + * @param checkBox * @param getter * The {@link Getter} interface that will implement a get method. * @param setter @@ -579,7 +578,7 @@ public class Util { * Binds a {@link Checkbox} with a {@link Getter}. * The {@link Getter} will be used to get the value that is going to be showed in the {@link Checkbox}. * - * @param Radio + * @param radio * The {@link Radio} to be bound * @param getter * The {@link Getter} interface that will implement a get method. @@ -588,7 +587,6 @@ public class Util { public static Radio bind(final Radio radio, final Getter getter) { radio.setSelected(getter.get()); radio.setDisabled(true); - return radio; } @@ -597,7 +595,7 @@ public class Util { * The {@link Getter} will be used to get the value that is going to be showed in the {@link Radio}. * The {@link Setter} will be used to store the value inserted by the user in the {@link Radio}. * - * @param decimalBox + * @param radio * The {@link Radio} to be bound * @param getter * he {@link Getter} interface that will implement a get method. @@ -629,7 +627,6 @@ public class Util { public static Bandbox bind(Bandbox bandBox, Getter getter) { bandBox.setValue(getter.get()); bandBox.setDisabled(true); - return bandBox; } @@ -663,7 +660,7 @@ public class Util { * Creates an edit button with class and icon already set. * * @param eventListener - * A event listener for {@link Events.ON_CLICK} + * A event listener for {@link Events#ON_CLICK} * @return An edit {@link Button} */ public static Button createEditButton(EventListener eventListener) { @@ -682,7 +679,7 @@ public class Util { * Creates a remove button with class and icon already set. * * @param eventListener - * A event listener for {@link Events.ON_CLICK} + * A event listener for {@link Events#ON_CLICK} * @return A remove {@link Button} */ public static Button createRemoveButton(EventListener eventListener) { @@ -740,7 +737,7 @@ public class Util { * new listeners to add */ public static void ensureUniqueListeners(Component component, String eventName, EventListener... uniqueListeners) { - //TODO Replace deprecated method + // TODO Replace deprecated method Iterator listenerIterator = component.getListenerIterator(eventName); while (listenerIterator.hasNext()) { @@ -784,10 +781,9 @@ public class Util { /** * Gets money format for a {@link Decimalbox} using 2 figures for the - * decimal part and concatenating the currency symbol + * decimal part and concatenating the currency symbol. * - * @return Format for a {@link Decimalbox} ###.## plus currency - * symbol + * @return Format for a {@link Decimalbox} ###.## plus currency symbol */ public static String getMoneyFormat() { return "###.## " + escapeDecimalFormatSpecialChars(getCurrencySymbol()); @@ -893,8 +889,8 @@ public class Util { return dateTime == null ? "" : DateFormat - .getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locales.getCurrent()) - .format(dateTime); + .getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locales.getCurrent()) + .format(dateTime); } /** @@ -919,8 +915,7 @@ public class Util { } /** - * Format specific time using the {@link DateFormat#SHORT} - * format and showing only the time. + * Format specific time using the {@link DateFormat#SHORT} format and showing only the time. */ public static String formatTime(LocalTime time) { return time == null ? "" : formatTime(time.toDateTimeToday().toDate()); @@ -940,7 +935,8 @@ public class Util { .getFile() .getPath()); - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } /** @@ -962,7 +958,8 @@ public class Util { .getFile() .getPath()); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/components/finders/Finder.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/components/finders/Finder.java index e098b35cf..dc9baa001 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/components/finders/Finder.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/components/finders/Finder.java @@ -45,6 +45,7 @@ public abstract class Finder implements IFinder { } @Transactional(readOnly = true) + @Override public SimpleListModelExt getModel() { return new SimpleListModelExt(getAll()); } @@ -73,13 +74,11 @@ public abstract class Finder implements IFinder { * Use _toString() to indicate how an object is shown in the list of matching elements. */ private class ComboWorkerRenderer implements ComboitemRenderer { - @Override public void render(Comboitem item, Object data, int i) { item.setLabel(_toString(data)); item.setValue(data); } - } /** @@ -102,8 +101,8 @@ public abstract class Finder implements IFinder { /** * Searches for value among all model entries. * - * entryMatchesText method is used to check if an entry matches or not. - * Overwrite this method to provide your own behaviour + * {@link #entryMatchesText(String, String)}is used to check if an entry matches or not. + * Overwrite this method to provide your own behaviour. * * @param value * String to search @@ -120,10 +119,10 @@ public abstract class Finder implements IFinder { final LinkedList data = new LinkedList(); for (int i = 0; i < getSize(); i++) { - if ( idx.equals("") || entryMatchesText(_toString(getElementAt(i)), idx) ) { + if ( "".equals(idx) || entryMatchesText(_toString(getElementAt(i)), idx) ) { data.add(getElementAt(i)); if ( --nRows <= 0 ) { - break; // done + break; // Done } } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/common/typeconverters/DateConverter.java b/libreplan-webapp/src/main/java/org/libreplan/web/common/typeconverters/DateConverter.java index 3480b2975..ec97d66dc 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/common/typeconverters/DateConverter.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/common/typeconverters/DateConverter.java @@ -28,7 +28,7 @@ import org.zkoss.zk.ui.Component; import org.zkoss.zkplus.databind.TypeConverter; /** - * Converter for the type java.util.Date + * Converter for the type {@link Date}. * * @author Diego Pino Garcia * diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/costcategories/ResourcesCostCategoryAssignmentController.java b/libreplan-webapp/src/main/java/org/libreplan/web/costcategories/ResourcesCostCategoryAssignmentController.java index 50c576e7a..377834b67 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/costcategories/ResourcesCostCategoryAssignmentController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/costcategories/ResourcesCostCategoryAssignmentController.java @@ -50,7 +50,7 @@ import org.zkoss.zul.Row; import org.zkoss.zul.RowRenderer; /** - * Controller for CRUD actions over a {@link ResourcesCostCategoryAssignment} + * Controller for CRUD actions over a {@link ResourcesCostCategoryAssignment}. * * @author Jacobo Aragunde Perez */ @@ -67,8 +67,10 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); - resourcesCostCategoryAssignmentModel = - (IResourcesCostCategoryAssignmentModel) SpringUtil.getBean("resourcesCostCategoryAssignmentModel"); + if ( resourcesCostCategoryAssignmentModel == null ) { + resourcesCostCategoryAssignmentModel = + (IResourcesCostCategoryAssignmentModel) SpringUtil.getBean("resourcesCostCategoryAssignmentModel"); + } comp.setAttribute("assignmentController", this, true); this.listResourcesCostCategoryAssignments = (Grid) comp.getFellowIfAny("listResourcesCostCategoryAssignments"); @@ -90,12 +92,11 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom private CostCategory getCostCategory(Row listitem) { ResourcesCostCategoryAssignment assignment = listitem.getValue(); - return assignment.getCostCategory(); } /** - * Append a Autocomplete @{link CostCategory} to row + * Append a Autocomplete @{link CostCategory} to row. * * @param row */ @@ -118,7 +119,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom public void onEvent(Event event) { final Comboitem comboitem = autocomplete.getSelectedItem(); - if(comboitem != null) { + if (comboitem != null) { // Update resourcesCostCategoryAssignment ResourcesCostCategoryAssignment assignment = row.getValue(); assignment.setCostCategory(comboitem.getValue()); @@ -130,15 +131,17 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom } public void confirmRemove(ResourcesCostCategoryAssignment assignment) { - int status = Messagebox.show(_("Confirm deleting this hour cost. Are you sure?"), _("Delete"), + int status = Messagebox.show( + _("Confirm deleting this hour cost. Are you sure?"), _("Delete"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION); + if (Messagebox.OK == status) { removeCostCategoryAssignment(assignment); } } /** - * Append a delete {@link Button} to {@link Row} + * Append a delete {@link Button} to {@link Row}. * * @param row */ @@ -147,6 +150,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom delete.setHoverImage("/common/img/ico_borrar.png"); delete.setSclass("icono"); delete.setTooltiptext(_("Delete")); + delete.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) { @@ -157,7 +161,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom } /** - * Append a Datebox "init date" to row + * Append a Datebox "init date" to row. * * @param row */ @@ -183,42 +187,41 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom } /** - * Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment} + * Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment}. * * @param dateBoxInitDate - * @param hourCost + * @param assignment */ - private void bindDateboxInitDate(final Datebox dateBoxInitDate, - final ResourcesCostCategoryAssignment assignment) { - Util.bind(dateBoxInitDate, new Util.Getter() { + private void bindDateboxInitDate(final Datebox dateBoxInitDate, final ResourcesCostCategoryAssignment assignment) { - @Override - public Date get() { - LocalDate dateTime = assignment.getInitDate(); - if (dateTime != null) { - return new Date(dateTime.getYear()-1900, - dateTime.getMonthOfYear()-1,dateTime.getDayOfMonth()); - } - return null; - } - - }, new Util.Setter() { - - @Override - public void set(Date value) { - if (value != null) { - assignment.setInitDate(new LocalDate(value.getYear()+1900, - value.getMonth()+1,value.getDate())); - } - else { - assignment.setInitDate(null); - } - } - }); + Util.bind( + dateBoxInitDate, + new Util.Getter() { + @Override + public Date get() { + LocalDate dateTime = assignment.getInitDate(); + /* TODO resolve deprecated */ + return dateTime != null + ? new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth()) + : null; + } + }, + new Util.Setter() { + @Override + public void set(Date value) { + if (value != null) { + /* TODO resolve deprecated */ + assignment.setInitDate(new LocalDate(value.getYear() + 1900, value.getMonth() + 1,value.getDate())); + } + else { + assignment.setInitDate(null); + } + } + }); } /** - * Append a Datebox "end date" to row + * Append a Datebox "end date" to row. * * @param row */ @@ -226,6 +229,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom Datebox endDateBox = new Datebox(); bindDateboxEndDate(endDateBox, row.getValue()); LocalDate initDate = ((ResourcesCostCategoryAssignment)row.getValue()).getInitDate(); + if (initDate != null) { endDateBox.setConstraint("after " + String.format("%04d", initDate.getYear()) + @@ -236,38 +240,36 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom } /** - * Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment} + * Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment}. * - * @param dateBoxInitDate - * @param hourCost + * @param dateBoxEndDate + * @param assignment */ - private void bindDateboxEndDate(final Datebox dateBoxEndDate, - final ResourcesCostCategoryAssignment assignment) { - Util.bind(dateBoxEndDate, new Util.Getter() { - - @Override - public Date get() { - LocalDate dateTime = assignment.getEndDate(); - if (dateTime != null) { - return new Date(dateTime.getYear()-1900, - dateTime.getMonthOfYear()-1,dateTime.getDayOfMonth()); - } - - return null; - } - - }, new Util.Setter() { - @Override - public void set(Date value) { - if (value != null) { - /* TODO resolve deprecated */ - assignment.setEndDate(new LocalDate(value.getYear() + 1900, value.getMonth() + 1, value.getDate())); - } - else { - assignment.setEndDate(null); - } - } - }); + private void bindDateboxEndDate(final Datebox dateBoxEndDate, final ResourcesCostCategoryAssignment assignment) { + Util.bind( + dateBoxEndDate, + new Util.Getter() { + @Override + public Date get() { + LocalDate dateTime = assignment.getEndDate(); + /* TODO resolve deprecated */ + return dateTime != null + ? new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1,dateTime.getDayOfMonth()) + : null; + } + }, + new Util.Setter() { + @Override + public void set(Date value) { + if (value != null) { + /* TODO resolve deprecated */ + assignment.setEndDate(new LocalDate(value.getYear() + 1900, value.getMonth() + 1, value.getDate())); + } + else { + assignment.setEndDate(null); + } + } + }); } public CostCategoryAssignmentRenderer getCostCategoryAssignmentsRenderer() { diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/CostStatusModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/CostStatusModel.java index 9af62644f..418991fb9 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/CostStatusModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/CostStatusModel.java @@ -32,16 +32,14 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** + * Model for UI operations related to CostStatus in Dashboard view. + * + * FIXME: This Model contains several operations for calculating 'Earned Value' measures related with cost. + * The code for calculating the basic measures: BCWP, ACWP and BCWS is copied from {@link OrderPlanningModel}. + * At this moment this code cannot be reused as it's coupled with the logic for displaying the 'Earned Value' chart. + * We may consider to refactor this code in the future. + * * @author Diego Pino García - * - * Model for UI operations related to CostStatus in Dashboard view - * - * FIXME: This Model contains several operations for calculating 'Earned - * Value' measures related with cost. The code for calculating the basic - * measures: BCWP, ACWP and BCWS is copied from - * {@link OrderPlanningModel}. At this moment this code cannot be reused - * as it's coupled with the logic for displaying the 'Earned Value' - * chart. We may consider to refactor this code in the future. */ @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) @@ -53,7 +51,6 @@ public class CostStatusModel implements ICostStatusModel { private Order order; public CostStatusModel() { - } @Override @@ -64,8 +61,7 @@ public class CostStatusModel implements ICostStatusModel { @Override public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost, BigDecimal actualCost) { - return earnedValueCalculator.getCostPerformanceIndex(budgetedCost, - actualCost); + return earnedValueCalculator.getCostPerformanceIndex(budgetedCost, actualCost); } @Override @@ -75,8 +71,7 @@ public class CostStatusModel implements ICostStatusModel { @Override public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion, BigDecimal costPerformanceIndex) { - return earnedValueCalculator.getEstimateAtCompletion( - budgetAtCompletion, costPerformanceIndex); + return earnedValueCalculator.getEstimateAtCompletion(budgetAtCompletion, costPerformanceIndex); } @Override diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/DashboardControllerGlobal.java b/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/DashboardControllerGlobal.java index d5ced2a8e..1eb93fb2a 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/DashboardControllerGlobal.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/dashboard/DashboardControllerGlobal.java @@ -2,6 +2,7 @@ package org.libreplan.web.dashboard; import org.libreplan.business.orders.entities.Order; +import org.libreplan.business.orders.entities.OrderStatusEnum; import org.libreplan.web.orders.IOrderModel; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; @@ -24,14 +25,15 @@ import java.util.List; * * @author Vova Perebykivskyi */ - @org.springframework.stereotype.Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class DashboardControllerGlobal extends GenericForwardComposer { - // TODO enumns instead of numbers ( 0, 1, 2, 3, ... ) // TODO 1 list instead of 8 + // TODO insert Label only in needed Cell + // ( is it possible at all? Seems that we need to make own Grid ) + // Because we cannot createCell at selected row-index, column-index private IOrderModel orderModel; @@ -61,7 +63,11 @@ public class DashboardControllerGlobal extends GenericForwardComposer { public void doAfterCompose(Component component) throws Exception { super.doAfterCompose(component); component.setAttribute("dashboardControllerGlobal", this, true); - orderModel = (IOrderModel) SpringUtil.getBean("orderModel"); + + if ( orderModel == null ) { + orderModel = (IOrderModel) SpringUtil.getBean("orderModel"); + } + fillOrderLists(); setupPipelineGrid(); showStoredColumn(); @@ -128,7 +134,8 @@ public class DashboardControllerGlobal extends GenericForwardComposer { onHoldOrders.size(), finishedOrders.size(), cancelledOrders.size(), - storedOrders.size() }; + storedOrders.size() + }; int rowsCount = findMaxList(sizes); @@ -146,18 +153,18 @@ public class DashboardControllerGlobal extends GenericForwardComposer { pipelineGrid.appendChild(rows); // Fill data into first column and so on with other columns divided by Enter in code - processList(preSalesOrders, 0); - processList(offeredOrders, 1); - processList(outsourcedOrders, 2); - processList(acceptedOrders, 3); - processList(startedOrders, 4); - processList(onHoldOrders, 5); - processList(finishedOrders, 6); - processList(cancelledOrders, 7); - processList(storedOrders, 8); + processList(preSalesOrders, OrderStatusEnum.PRE_SALES); + processList(offeredOrders, OrderStatusEnum.OFFERED); + processList(outsourcedOrders, OrderStatusEnum.OUTSOURCED); + processList(acceptedOrders, OrderStatusEnum.ACCEPTED); + processList(startedOrders, OrderStatusEnum.STARTED); + processList(onHoldOrders, OrderStatusEnum.ON_HOLD); + processList(finishedOrders, OrderStatusEnum.FINISHED); + processList(cancelledOrders, OrderStatusEnum.CANCELLED); + processList(storedOrders, OrderStatusEnum.STORED); } - private void processList(List currentList, int index) { + private void processList(List currentList, OrderStatusEnum orderStatus) { if ( !currentList.isEmpty() ) { for (int i = 0; i < currentList.size(); i++) { @@ -165,14 +172,14 @@ public class DashboardControllerGlobal extends GenericForwardComposer { String outputInit = getOrderInitDate(currentList.get(i)); String outputDeadline = getOrderDeadline(currentList.get(i)); - ( (Label) pipelineGrid.getCell(i, index) ).setValue(currentList.get(i).getName()); + ( (Label) pipelineGrid.getCell(i, orderStatus.getIndex()) ).setValue(currentList.get(i).getName()); String tooltipText = "Start date: " + outputInit + "\n" + "End date: " + outputDeadline + "\n" + "Progress: " + currentList.get(i).getAdvancePercentage() + " %"; - ( (Label) pipelineGrid.getCell(i, index) ).setTooltiptext(tooltipText); - ( (Label) pipelineGrid.getCell(i, index) ).setClass("label-highlight"); + ( (Label) pipelineGrid.getCell(i, orderStatus.getIndex()) ).setTooltiptext(tooltipText); + ( (Label) pipelineGrid.getCell(i, orderStatus.getIndex()) ).setClass("label-highlight"); } catch (ParseException e) { e.printStackTrace(); } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourceQueueModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourceQueueModel.java index db31397ea..a07d968fe 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourceQueueModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourceQueueModel.java @@ -142,8 +142,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { private Scenario master; - private Map> toBeSavedDependencies = - new HashMap<>(); + private Map> toBeSavedDependencies = new HashMap<>(); private boolean checkAllocationIsAppropriative = true; @@ -191,7 +190,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } private boolean isEarlier(LimitingResourceQueueElement arg1, LimitingResourceQueueElement arg2) { - return (arg1.getStartDate().isBefore(arg2.getStartDate())); + return arg1.getStartDate().isBefore(arg2.getStartDate()); } private LimitingResourceQueueElement getFirstLimitingResourceQueueElement(LimitingResourceQueue queue) { @@ -199,7 +198,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } private LimitingResourceQueueElement getFirstChild(SortedSet elements) { - return (elements.isEmpty()) ? null : elements.iterator().next(); + return elements.isEmpty() ? null : elements.iterator().next(); } /** @@ -233,8 +232,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { private void initializeTask(Task task) { if ( hasResourceAllocation(task) ) { - ResourceAllocation resourceAllocation = - initializeResourceAllocationIfNecessary(getResourceAllocation(task)); + ResourceAllocation resourceAllocation = initializeResourceAllocationIfNecessary(getResourceAllocation(task)); task.setResourceAllocation(resourceAllocation); } @@ -275,8 +273,10 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } } - // FIXME: Needed to fetch order.name in QueueComponent.composeTooltiptext. - // Try to replace it with a HQL query instead of iterating all the way up through order + /** + * FIXME: Needed to fetch order.name in QueueComponent.composeTooltiptext + * Try to replace it with a HQL query instead of iterating all the way up through order. + */ private void initializeRootOrder(Task task) { Hibernate.initialize(task.getOrderElement()); OrderElement order = task.getOrderElement(); @@ -318,21 +318,23 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } private ResourceAllocation initializeResourceAllocationIfNecessary(ResourceAllocation resourceAllocation) { - if ( resourceAllocation instanceof HibernateProxy ) { + ResourceAllocation newResourceAllocation = resourceAllocation; - resourceAllocation = (ResourceAllocation) ((HibernateProxy) resourceAllocation) + if ( newResourceAllocation instanceof HibernateProxy ) { + + newResourceAllocation = (ResourceAllocation) ((HibernateProxy) newResourceAllocation) .getHibernateLazyInitializer().getImplementation(); - if ( resourceAllocation instanceof GenericResourceAllocation ) { - GenericResourceAllocation generic = (GenericResourceAllocation) resourceAllocation; + if ( newResourceAllocation instanceof GenericResourceAllocation ) { + GenericResourceAllocation generic = (GenericResourceAllocation) newResourceAllocation; initializeCriteria(generic.getCriterions()); } - Hibernate.initialize(resourceAllocation.getAssignments()); - Hibernate.initialize(resourceAllocation.getLimitingResourceQueueElement()); + Hibernate.initialize(newResourceAllocation.getAssignments()); + Hibernate.initialize(newResourceAllocation.getLimitingResourceQueueElement()); } - return resourceAllocation; + return newResourceAllocation; } private void initializeCriteria(Set criteria) { @@ -354,7 +356,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { for (LimitingResourceQueue each : queues) { initializeLimitingResourceQueue(each); } - return queues; } @@ -392,10 +393,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { @Override @Transactional(readOnly = true) public boolean userCanRead(Order order, String loginName) { - if ( SecurityUtils.isSuperuserOrUserInRoles( - UserRole.ROLE_READ_ALL_PROJECTS, - UserRole.ROLE_EDIT_ALL_PROJECTS)) { - + if ( SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_READ_ALL_PROJECTS, UserRole.ROLE_EDIT_ALL_PROJECTS)) { return true; } @@ -412,7 +410,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { // This case shouldn't happen, because it would mean that there isn't a logged user // anyway, if it happened we don't allow the user to pass. } - return false; } @@ -460,16 +457,15 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } /** - * After an allocation dependencies might be broken, this method unschedules - * elements affected by an allocation and reschedule them again in - * topological order, so dependencies are satisfied. + * After an allocation dependencies might be broken, this method unscheduled + * elements affected by an allocation and reschedule them again in topological order, so dependencies are satisfied. * * If the allocation was appropriative it also allocates those elements that * might be unscheduled before due to the appropriative allocation. * * @param allocation * @param moved - * @return + * @return {@link Collection} */ private Collection rescheduleAffectedElementsToSatisfyDependencies( AllocationSpec allocation, List moved) { @@ -597,7 +593,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { for (Edge each : edges) { result = DateAndHour.max(result, calculateStart(previous, each.type)); } - return result; } @@ -634,8 +629,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } /** - * @return null if no suitable gap found; the allocation found - * otherwise + * @return null if no suitable gap found; the allocation found otherwise */ private AllocationSpec insertAtGap(InsertionRequirements requirements) { return doAppropriativeIfNecessary(findAllocationSpecFor(requirements), requirements); @@ -673,21 +667,16 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { if ( checkAllocationIsAppropriative() && requirements.isAppropiativeAllocation(allocation) ) { return doAppropriativeAllocation(requirements); } - return allocation; } - return null; } private AllocationSpec insertAtGap(InsertionRequirements requirements, LimitingResourceQueue queue) { - AllocationSpec allocationStillNotDone = findAllocationSpecForInQueue(requirements, queue); - - return doAppropriativeIfNecessary(allocationStillNotDone, requirements); + return doAppropriativeIfNecessary(findAllocationSpecForInQueue(requirements, queue), requirements); } - private AllocationSpec findAllocationSpecForInQueue(InsertionRequirements requirements, - LimitingResourceQueue queue) { + private AllocationSpec findAllocationSpecForInQueue(InsertionRequirements requirements, LimitingResourceQueue queue) { List potentiallyValidGapsFor = new ArrayList<>(); @@ -894,7 +883,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { } private void addLimitingResourceQueueElementIfNeeded(LimitingResourceQueue queue, LimitingResourceQueueElement element) { - if ( element.getLimitingResourceQueue() == null ) { queuesState.assignedToQueue(element, queue); } @@ -1045,7 +1033,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { public LimitingResourceQueueElement unschedule(LimitingResourceQueueElement queueElement) { queuesState.unassingFromQueue(queueElement); markAsModified(queueElement); - return queueElement; } @@ -1110,14 +1097,14 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel { @Override public Set appropriativeAllocation( - LimitingResourceQueueElement _element, - LimitingResourceQueue _queue, + LimitingResourceQueueElement limitingResourceQueueElement, + LimitingResourceQueue limitingResourceQueue, DateAndHour allocationTime) { Set result = new HashSet<>(); - LimitingResourceQueue queue = queuesState.getEquivalent(_queue); - LimitingResourceQueueElement element = queuesState.getEquivalent(_element); + LimitingResourceQueue queue = queuesState.getEquivalent(limitingResourceQueue); + LimitingResourceQueueElement element = queuesState.getEquivalent(limitingResourceQueueElement); InsertionRequirements requirements = queuesState.getRequirementsFor(element, allocationTime); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourcesController.java b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourcesController.java index ac70a4933..9064fd304 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourcesController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/LimitingResourcesController.java @@ -108,14 +108,9 @@ public class LimitingResourcesController extends GenericForwardComposer() { @@ -133,7 +133,7 @@ public class LimitingResourcesController extends GenericForwardComposer} */ public List getUnassignedLimitingResourceQueueElements() { - // TODO check it return limitingResourceQueueModel .getUnassignedLimitingResourceQueueElements() .stream() @@ -528,7 +529,6 @@ public class LimitingResourcesController extends GenericForwardComposer children = row.getChildren(); - - return (Checkbox) children.get(0); + return (Checkbox) row.getChildren().get(0); } public void assignAllSelectedElements() { diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/QueueComponent.java b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/QueueComponent.java index b53e81935..e1eda05d5 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/QueueComponent.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/limitingresources/QueueComponent.java @@ -186,6 +186,7 @@ public class QueueComponent extends XulElement implements AfterCompose { if ( each.getEndDate().toDateTimeAtStartOfDay().isAfter(interval.getStart().toDateTimeAtStartOfDay()) && each.getStartDate().toDateTimeAtStartOfDay() .isBefore(interval.getFinish().toDateTimeAtStartOfDay()) ) { + result.add(createQueueTask(datesMapper, each)); } @@ -246,7 +247,7 @@ public class QueueComponent extends XulElement implements AfterCompose { * Returns end date considering % of task completion. * * @param element - * @return + * @return {@link DateAndHour} */ private static DateAndHour getAdvanceEndDate(LimitingResourceQueueElement element) { int hoursWorked = 0; @@ -279,9 +280,8 @@ public class QueueComponent extends XulElement implements AfterCompose { } private static int estimatedWorkedHours(Integer totalHours, BigDecimal percentageWorked) { - boolean bool = totalHours != null && percentageWorked != null; - - return bool ? percentageWorked.multiply(new BigDecimal(totalHours)).intValue() : 0; + boolean condition = totalHours != null && percentageWorked != null; + return condition ? percentageWorked.multiply(new BigDecimal(totalHours)).intValue() : 0; } private static QueueTask createDivForElement(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) { @@ -472,7 +472,6 @@ public class QueueComponent extends XulElement implements AfterCompose { return each; } } - return null; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedHoursToOrderElementModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedHoursToOrderElementModel.java index b6338a093..fb840d594 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedHoursToOrderElementModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/orders/AssignedHoursToOrderElementModel.java @@ -153,18 +153,14 @@ public class AssignedHoursToOrderElementModel implements IAssignedHoursToOrderEl @Override public EffortDuration getAssignedDirectEffort() { - if (orderElement == null) { - return EffortDuration.zero(); - } - return this.assignedDirectEffort; + return orderElement == null ? EffortDuration.zero() : this.assignedDirectEffort; } @Override public EffortDuration getTotalAssignedEffort() { - if (orderElement == null || orderElement.getSumChargedEffort() == null) { - return EffortDuration.zero(); - } - return this.orderElement.getSumChargedEffort().getTotalChargedEffort(); + return orderElement == null || orderElement.getSumChargedEffort() == null + ? EffortDuration.zero() + : this.orderElement.getSumChargedEffort().getTotalChargedEffort(); } @Override @@ -218,52 +214,39 @@ public class AssignedHoursToOrderElementModel implements IAssignedHoursToOrderEl if (orderElement == null) { return EffortDuration.zero(); } - //TODO this must be changed when changing HoursGroup + // TODO this must be changed when changing HoursGroup return EffortDuration.hours(orderElement.getWorkHours()); } @Override @Transactional(readOnly = true) public int getProgressWork() { - if (orderElement == null) { - return 0; - } - return orderElementDAO.getHoursAdvancePercentage(orderElement).multiply(new BigDecimal(100)).intValue(); + return orderElement == null + ? 0 + : orderElementDAO.getHoursAdvancePercentage(orderElement).multiply(new BigDecimal(100)).intValue(); } @Override public BigDecimal getBudget() { - if (orderElement == null) { - return BigDecimal.ZERO; - } - return orderElement.getBudget(); + return orderElement == null ? BigDecimal.ZERO : orderElement.getBudget(); } @Override @Transactional(readOnly = true) public BigDecimal getCalculatedBudget() { - if (orderElement == null) { - return BigDecimal.ZERO; - } - return getBudget().subtract(getResourcesBudget()); + return orderElement == null ? BigDecimal.ZERO : getBudget().subtract(getResourcesBudget()); } @Override @Transactional(readOnly = true) public BigDecimal getResourcesBudget() { - if (orderElement == null) { - return BigDecimal.ZERO; - } - return orderElement.getResourcesBudget(); + return orderElement == null ? BigDecimal.ZERO : orderElement.getResourcesBudget(); } @Override @Transactional(readOnly = true) public BigDecimal getMoneyCost() { - if (orderElement == null) { - return BigDecimal.ZERO; - } - return moneyCostCalculator.getTotalMoneyCost(orderElement); + return orderElement == null ? BigDecimal.ZERO : moneyCostCalculator.getTotalMoneyCost(orderElement); } @Override @@ -285,30 +268,23 @@ public class AssignedHoursToOrderElementModel implements IAssignedHoursToOrderEl @Override public BigDecimal getCostOfExpenses() { - if (orderElement == null) { - return BigDecimal.ZERO.setScale(2); - } - return moneyCostCalculator.getExpensesMoneyCost(orderElement); + return orderElement == null ? BigDecimal.ZERO.setScale(2) : moneyCostCalculator.getExpensesMoneyCost(orderElement); } @Override @Transactional(readOnly = true) public BigDecimal getCostOfHours() { - if (orderElement == null) { - return BigDecimal.ZERO.setScale(2); - } - return moneyCostCalculator.getHoursMoneyCost(orderElement); + return orderElement == null ? BigDecimal.ZERO.setScale(2) : moneyCostCalculator.getHoursMoneyCost(orderElement); } @Override @Transactional(readOnly = true) public BigDecimal getMoneyCostPercentage() { - if (orderElement == null) { - return BigDecimal.ZERO; - } - return MoneyCostCalculator.getMoneyCostProportion( - moneyCostCalculator.getTotalMoneyCost(orderElement), - orderElement.getTotalBudget()).multiply(new BigDecimal(100)); + return orderElement == null + ? BigDecimal.ZERO + : MoneyCostCalculator.getMoneyCostProportion( + moneyCostCalculator.getTotalMoneyCost(orderElement), + orderElement.getTotalBudget()).multiply(new BigDecimal(100)); } @Override diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/AllocationRow.java b/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/AllocationRow.java index 988bf2d65..637b577e3 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/AllocationRow.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/AllocationRow.java @@ -593,11 +593,11 @@ public abstract class AllocationRow { } private Constraint constraintForHoursInput() { - return (effortInput.isDisabled()) ? null : CONSTRAINT_FOR_HOURS_INPUT; + return effortInput.isDisabled() ? null : CONSTRAINT_FOR_HOURS_INPUT; } private Constraint constraintForResourcesPerDayInput() { - return (intendedResourcesPerDayInput.isDisabled()) ? null : CONSTRAINT_FOR_RESOURCES_PER_DAY; + return intendedResourcesPerDayInput.isDisabled() ? null : CONSTRAINT_FOR_RESOURCES_PER_DAY; } private void updateUIWithModificationsDone() { diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java b/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java index c6eeea55b..e1ff55c77 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/planner/allocation/ResourceAllocationController.java @@ -141,8 +141,10 @@ public class ResourceAllocationController extends GenericForwardComposer { private EditTaskController editTaskController; - public ResourceAllocationController(){ - resourceAllocationModel = (IResourceAllocationModel) SpringUtil.getBean("resourceAllocationModel"); + public ResourceAllocationController() { + if ( resourceAllocationModel == null ) { + resourceAllocationModel = (IResourceAllocationModel) SpringUtil.getBean("resourceAllocationModel"); + } } @Override @@ -508,7 +510,6 @@ public class ResourceAllocationController extends GenericForwardComposer { private List plusAggregatingRow(List currentRows) { List result = new ArrayList<>(currentRows); result.add(null); - return result; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/planner/consolidations/AdvanceConsolidationModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/planner/consolidations/AdvanceConsolidationModel.java index 86c3cdadb..fe31525f4 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/planner/consolidations/AdvanceConsolidationModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/planner/consolidations/AdvanceConsolidationModel.java @@ -26,10 +26,9 @@ import static org.libreplan.web.I18nHelper._; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Date; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; +import java.util.SortedSet; import org.joda.time.LocalDate; import org.libreplan.business.advance.entities.AdvanceMeasurement; @@ -158,7 +157,7 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { private void createConsolidationIfNeeded() { if (consolidation == null && task != null) { if (advanceIsCalculated()) { - IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirecAdvanceAssignment(); + IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirectAdvanceAssignment(); consolidation = CalculatedConsolidation.create(task, indirectAdvanceAssignment); } else { consolidation = NonCalculatedConsolidation.create(task, spreadAdvance); @@ -167,7 +166,7 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { } } - private IndirectAdvanceAssignment getIndirecAdvanceAssignment() { + private IndirectAdvanceAssignment getIndirectAdvanceAssignment() { if (orderElement != null) { Set indirects = orderElement.getIndirectAdvanceAssignments(); for (IndirectAdvanceAssignment indirectAdvanceAssignment : indirects) { @@ -277,10 +276,8 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { } else { AdvanceMeasurement measure = dto.getAdvanceMeasurement(); - NonCalculatedConsolidatedValue consolidatedValue = NonCalculatedConsolidatedValue - .create(LocalDate.fromDateFields(dto.getDate()), - dto.getPercentage(), measure, - task.getIntraDayEndDate()); + NonCalculatedConsolidatedValue consolidatedValue = NonCalculatedConsolidatedValue.create( + LocalDate.fromDateFields(dto.getDate()), dto.getPercentage(), measure, task.getIntraDayEndDate()); measure.getNonCalculatedConsolidatedValues().add(consolidatedValue); return consolidatedValue; @@ -331,7 +328,7 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { private void removeConsolidationInAdvance() { if (advanceIsCalculated()) { - IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirecAdvanceAssignment(); + IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirectAdvanceAssignment(); indirectAdvanceAssignment.getCalculatedConsolidation().remove(consolidation); ((CalculatedConsolidation) consolidation).setIndirectAdvanceAssignment(null); } else { @@ -342,7 +339,7 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { private void addConsolidationInAdvance() { if (advanceIsCalculated()) { - IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirecAdvanceAssignment(); + IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirectAdvanceAssignment(); if (!indirectAdvanceAssignment.getCalculatedConsolidation().contains(consolidation)) { indirectAdvanceAssignment.getCalculatedConsolidation().add((CalculatedConsolidation) consolidation); ((CalculatedConsolidation) consolidation).setIndirectAdvanceAssignment(indirectAdvanceAssignment); @@ -368,7 +365,6 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { private void initTask(Task task) { this.task = task; taskElementDAO.reattach(this.task); - orderElement = task.getOrderElement(); orderElementDAO.reattach(orderElement); } @@ -387,7 +383,7 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { private void initAdvanceConsolidationsDTOs() { if (spreadAdvance != null) { - isUnitType = (!spreadAdvance.getAdvanceType().getPercentage()); + isUnitType = !spreadAdvance.getAdvanceType().getPercentage(); createAdvanceConsolidationDTOs(); initConsolidatedDates(); addNonConsolidatedAdvances(); @@ -398,7 +394,7 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { private void initSpreadAdvance() { if (spreadAdvance != null) { if (advanceIsCalculated()) { - IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirecAdvanceAssignment(); + IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirectAdvanceAssignment(); indirectAdvanceAssignment.getCalculatedConsolidation().size(); } else { spreadAdvance.getNonCalculatedConsolidation().size(); @@ -418,20 +414,22 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { if (consolidation != null) { if (!consolidation.isCalculated()) { - /* TODO check it */ - consolidationDTOs - .addAll(((NonCalculatedConsolidation) consolidation) - .getNonCalculatedConsolidatedValues() - .stream() - .map(consolidatedValue -> new AdvanceConsolidationDTO( - consolidatedValue.getAdvanceMeasurement(), consolidatedValue)) - .collect(Collectors.toList())); + SortedSet nonCalculatedConsolidatedValues = + ((NonCalculatedConsolidation) consolidation).getNonCalculatedConsolidatedValues(); + + for (NonCalculatedConsolidatedValue consolidatedValue : nonCalculatedConsolidatedValues) { + + consolidationDTOs.add( + new AdvanceConsolidationDTO(consolidatedValue.getAdvanceMeasurement(), consolidatedValue)); + } } else { - consolidationDTOs - .addAll(((CalculatedConsolidation) consolidation) - .getCalculatedConsolidatedValues() - .stream().map(consolidatedValue -> new AdvanceConsolidationDTO(null, consolidatedValue)) - .collect(Collectors.toList())); + + SortedSet calculatedConsolidatedValuestedValues = + ((CalculatedConsolidation) consolidation).getCalculatedConsolidatedValues(); + + for (CalculatedConsolidatedValue consolidatedValue : calculatedConsolidatedValuestedValues) { + consolidationDTOs.add(new AdvanceConsolidationDTO(null, consolidatedValue)); + } } } } @@ -446,54 +444,42 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { } private boolean canBeConsolidateAndShow(AdvanceMeasurement advanceMeasurement) { - Date date = advanceMeasurement.getDate().toDateTimeAtStartOfDay().toDate(); - return ((AdvanceConsolidationDTO.canBeConsolidateAndShow(date)) && (!containsAdvance(advanceMeasurement))); + return AdvanceConsolidationDTO + .canBeConsolidateAndShow(advanceMeasurement.getDate().toDateTimeAtStartOfDay().toDate()) && + !containsAdvance(advanceMeasurement); } @Override public String getInfoAdvanceAssignment() { - if (this.spreadAdvance == null || this.orderElement == null) { - return ""; - } - return getInfoAdvanceAssignment(this.spreadAdvance); + return this.spreadAdvance == null || this.orderElement == null ? "" : getInfoAdvanceAssignment(this.spreadAdvance); } private String getInfoAdvanceAssignment(DirectAdvanceAssignment assignment) { - if (assignment == null) { - return ""; - } - if (assignment.getMaxValue() == null) { - return ""; - } - return _("( max: {0} )", assignment.getMaxValue()); + return assignment == null || assignment.getMaxValue() == null ? "" : _("( max: {0} )", assignment.getMaxValue()); } private List getAdvances() { - if (spreadAdvance != null) { - return new ArrayList<>(spreadAdvance.getAdvanceMeasurements()); - } - return new ArrayList<>(); + return spreadAdvance != null ? new ArrayList<>(spreadAdvance.getAdvanceMeasurements()) : new ArrayList<>(); } @Override public boolean isVisibleAdvances() { - return (!isVisibleMessages()); + return !isVisibleMessages(); } @Override public boolean isVisibleMessages() { - return ((getAdvances().size() == 0) || (isSubcontracted()) || (!hasResourceAllocation())); + return getAdvances().isEmpty() || isSubcontracted() || !hasResourceAllocation(); } private boolean advanceIsCalculated(){ - return ((spreadAdvance != null) && (spreadAdvance.isFake())); + return spreadAdvance != null && spreadAdvance.isFake(); } public String infoMessages() { - if (getAdvances().size() > 0) { - return _("Progress cannot be consolidated."); - } - return _("There is not any assigned progress to current task"); + return !getAdvances().isEmpty() + ? _("Progress cannot be consolidated.") + : _("There is not any assigned progress to current task"); } public void setConsolidationDTOs(List consolidationDTOs) { @@ -501,22 +487,19 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel { } public List getConsolidationDTOs() { - if (spreadAdvance != null && orderElement != null) { - return consolidationDTOs; - } - return new ArrayList<>(); + return spreadAdvance != null && orderElement != null ? consolidationDTOs : new ArrayList<>(); } private boolean hasResourceAllocation() { - return ((task != null) && (task.hasResourceAllocations())); + return task != null && task.hasResourceAllocations(); } private boolean isSubcontracted() { - return ((task != null) && (task.isSubcontracted())); + return task != null && task.isSubcontracted(); } public boolean hasLimitingResourceAllocation() { - return ((task != null) && (task.hasLimitedResourceAllocation())); + return task != null && task.hasLimitedResourceAllocation(); } @Override diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/planner/taskedition/TaskPropertiesController.java b/libreplan-webapp/src/main/java/org/libreplan/web/planner/taskedition/TaskPropertiesController.java index bebf5e044..ca54f7311 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/planner/taskedition/TaskPropertiesController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/planner/taskedition/TaskPropertiesController.java @@ -89,6 +89,8 @@ import org.zkoss.zul.Tabpanel; @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class TaskPropertiesController extends GenericForwardComposer { + private final String WARNING = "Warning"; + private IScenarioManager scenarioManager; private TaskEditFormComposer taskEditFormComposer = new TaskEditFormComposer(); @@ -140,9 +142,17 @@ public class TaskPropertiesController extends GenericForwardComposer private List listToAdd = new ArrayList<>(); public TaskPropertiesController() { - emailNotificationModel = (IEmailNotificationModel) SpringUtil.getBean("emailNotificationModel"); - workerModel = (IWorkerModel) SpringUtil.getBean("workerModel"); - scenarioManager = (IScenarioManager) SpringUtil.getBean("scenarioManager"); + if ( emailNotificationModel == null ) { + emailNotificationModel = (IEmailNotificationModel) SpringUtil.getBean("emailNotificationModel"); + } + + if ( workerModel == null ) { + workerModel = (IWorkerModel) SpringUtil.getBean("workerModel"); + } + + if ( scenarioManager == null ) { + scenarioManager = (IScenarioManager) SpringUtil.getBean("scenarioManager"); + } } public void init(final EditTaskController editTaskController, @@ -317,8 +327,8 @@ public class TaskPropertiesController extends GenericForwardComposer TaskPositionConstraint taskConstraint = currentTaskElementAsTaskLeafConstraint().getPositionConstraint(); PositionConstraintType type = startConstraintTypes.getSelectedItem().getValue(); - IntraDayDate inputDate = type.isAssociatedDateRequired() ? - IntraDayDate.startOfDay(LocalDate.fromDateFields(startConstraintDate.getValue())) + IntraDayDate inputDate = type.isAssociatedDateRequired() + ? IntraDayDate.startOfDay(LocalDate.fromDateFields(startConstraintDate.getValue())) : null; if ( taskConstraint.isValid(type, inputDate) ) { @@ -466,7 +476,6 @@ public class TaskPropertiesController extends GenericForwardComposer * Enum for showing type of resource assignation option list. * * @author Diego Pino Garcia - * */ enum ResourceAllocationTypeEnum { NON_LIMITING_RESOURCES(_("Normal resource assignment")), @@ -542,7 +551,8 @@ public class TaskPropertiesController extends GenericForwardComposer * * @param resourceAllocation */ - public void setResourceAllocationType(ResourceAllocationTypeEnum resourceAllocation) {} + public void setResourceAllocationType(ResourceAllocationTypeEnum resourceAllocation) { + } ResourceAllocationTypeEnum getResourceAllocationType(TaskElement taskElement) { return taskElement == null || !isTask(taskElement) @@ -604,7 +614,7 @@ public class TaskPropertiesController extends GenericForwardComposer if ( task.hasResourceAllocations() ) { if ( Messagebox.show( _("Assigned resources for this task will be deleted. Are you sure?"), - _("Warning"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) { + _(WARNING), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) { task.removeAllResourceAllocations(); setStateTo(newState); } else { @@ -640,7 +650,7 @@ public class TaskPropertiesController extends GenericForwardComposer if (task.hasResourceAllocations()) { if (Messagebox.show( _("Assigned resources for this task will be deleted. Are you sure?"), - _("Warning"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK ) { + _(WARNING), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK ) { task.removeAllResourceAllocations(); setStateTo(newState); } else { @@ -667,9 +677,11 @@ public class TaskPropertiesController extends GenericForwardComposer // Notification has been sent if ( communicationDate != null ) { - if ( Messagebox.show(_("IMPORTANT: Don't forget to communicate to subcontractor that " + - "his contract has been cancelled"), _("Warning"), - Messagebox.OK, Messagebox.EXCLAMATION) == Messagebox.OK ) { + + if ( Messagebox.show( + _("IMPORTANT: Don't forget to communicate to subcontractor that his contract has been cancelled"), + _(WARNING), Messagebox.OK, Messagebox.EXCLAMATION) == Messagebox.OK ) { + setStateTo(newState); } else { resetStateTo(ResourceAllocationTypeEnum.SUBCONTRACT); @@ -731,14 +743,12 @@ public class TaskPropertiesController extends GenericForwardComposer return Util.getMoneyFormat(); } + /** + * Check if resources in allocation are bound by user and in what ROLE they are. + * setUser method calling manually because, after initialization user will be null. + * Then send valid data to notification_queue table. + */ public void emailNotificationAddNew() { - - /* - * Check if resources in allocation are bound by user and in what ROLE they are. - * setUser method calling manually because, after initialization user will be null. - * Then send valid data to notification_queue table. - */ - proceedList(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE, listToAdd); proceedList(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK, listToDelete); listToAdd.clear(); @@ -764,9 +774,10 @@ public class TaskPropertiesController extends GenericForwardComposer if ( currentUser != null && (currentUser.isInRole(UserRole.ROLE_EMAIL_TASK_ASSIGNED_TO_RESOURCE) || - currentUser.isInRole(UserRole.ROLE_EMAIL_RESOURCE_REMOVED_FROM_TASK)) ) - + currentUser.isInRole(UserRole.ROLE_EMAIL_RESOURCE_REMOVED_FROM_TASK)) ) { setEmailNotificationEntity(enumeration, currentResource); + } + break; } } @@ -777,11 +788,11 @@ public class TaskPropertiesController extends GenericForwardComposer try { emailNotificationModel.setNewObject(); - if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE) ) + if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE) ) { emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE); - - else if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK) ) + } else if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK) ) { emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK); + } emailNotificationModel.setUpdated(new Date()); @@ -792,7 +803,7 @@ public class TaskPropertiesController extends GenericForwardComposer emailNotificationModel.setProject(currentTaskElement.getParent().getTaskSource().getTask()); emailNotificationModel.confirmSave(); - } catch (DataIntegrityViolationException e){ + } catch (DataIntegrityViolationException e) { Messagebox.show( _("You cannot email user twice with the same info"), _("Error"), Messagebox.OK, Messagebox.ERROR); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/qualityforms/QualityFormCRUDController.java b/libreplan-webapp/src/main/java/org/libreplan/web/qualityforms/QualityFormCRUDController.java index 629456438..6ef70239d 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/qualityforms/QualityFormCRUDController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/qualityforms/QualityFormCRUDController.java @@ -35,7 +35,6 @@ import org.libreplan.web.common.BaseCRUDController; import org.libreplan.web.common.Util; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.WrongValueException; -import org.zkoss.zk.ui.event.Event; import org.zkoss.zul.Checkbox; import org.zkoss.zul.Column; import org.zkoss.zul.Constraint; @@ -53,6 +52,8 @@ import org.zkoss.zul.ext.Sortable; */ public class QualityFormCRUDController extends BaseCRUDController { + private final String CANNOT_BE_EMPTY = "cannot be empty"; + private IQualityFormModel qualityFormModel; private Grid gridQualityForms; @@ -64,7 +65,9 @@ public class QualityFormCRUDController extends BaseCRUDController { private Textbox txtFilter; public QualityFormCRUDController() { - qualityFormModel = (IQualityFormModel) SpringUtil.getBean("qualityFormModel"); + if ( qualityFormModel == null ) { + qualityFormModel = (IQualityFormModel) SpringUtil.getBean("qualityFormModel"); + } } @Override @@ -77,38 +80,40 @@ public class QualityFormCRUDController extends BaseCRUDController { } /** - * Return all {@link QualityForm} - * @return + * Return all {@link QualityForm}. + * + * @return {@link List} */ public List getQualityForms() { return qualityFormModel.getQualityForms(predicate); } /** - * Return current {@link QualityForm} - * @return + * Return current {@link QualityForm}. + * + * @return {@link QualityForm} */ public QualityForm getQualityForm() { return qualityFormModel.getQualityForm(); } /** - * Return all {@link QualityFormItem} assigned to the current - * {@link QualityForm} - * @return + * Return all {@link QualityFormItem} assigned to the current {@link QualityForm}. + * + * @return {@link List} */ public List getQualityFormItems() { return qualityFormModel.getQualityFormItems(); } @Override - protected void beforeSaving() throws ValidationException { + protected void beforeSaving() { super.beforeSaving(); validateReportProgress(); } @Override - protected void save() throws ValidationException { + protected void save() { qualityFormModel.confirmSave(); } @@ -122,11 +127,10 @@ public class QualityFormCRUDController extends BaseCRUDController { } /** - * Sorts {@link Grid} model by first column, respecting sort order + * Sorts {@link Grid} model by first column, respecting sort order. * - * FIXME: This is a temporary solution, there should be a better/smarter way - * of preserving order in the Grid every time a new element is added to its - * model + * FIXME: This is a temporary solution + * There should be a better/smarter way Preserving order in the Grid every time a new element is added to its model. */ private void forceSortGridQualityFormItems() { Column column = (Column) gridQualityFormItems.getColumns().getChildren().get(2); @@ -140,19 +144,19 @@ public class QualityFormCRUDController extends BaseCRUDController { } /** - * Pop up confirm remove dialog - * @param QualityFormItem + * Pop up confirm remove dialog. + * + * @param item */ public void confirmDeleteQualityFormItem(QualityFormItem item) { if (qualityFormModel.isTotalPercentage(item)) { - if (Messagebox - .show( - _("Deleting this item will disable the report progress option. Are you sure?"), - _("Confirm"), - Messagebox.OK | Messagebox.CANCEL, - Messagebox.QUESTION) == Messagebox.OK) { + + if (Messagebox.show( + _("Deleting this item will disable the report progress option. Are you sure?"), _("Confirm"), + Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) { + Checkbox reportProgress = (Checkbox) editWindow.getFellowIfAny("checkBoxReportProgress"); - disabledCheckbocReportProgress(reportProgress); + disabledCheckboxReportProgress(reportProgress); } else { return; } @@ -171,7 +175,7 @@ public class QualityFormCRUDController extends BaseCRUDController { } public void onChangeQualityFormItemPercentage() { - // it must update the order of the items if it is necessary. + // It must update the order of the items if it is necessary getQualityForm().updateAndSortQualityFormItem(); Util.reloadBindings(gridQualityFormItems); } @@ -179,8 +183,8 @@ public class QualityFormCRUDController extends BaseCRUDController { public Constraint checkConstraintUniqueQualityFormName() { return (comp, value) -> { getQualityForm().setName((String) value); - if((value == null) || (((String)value)).isEmpty()){ - throw new WrongValueException(comp, _("cannot be empty")); + if ((value == null) || ((String)value).isEmpty()) { + throw new WrongValueException(comp, _(CANNOT_BE_EMPTY)); } else if (!qualityFormModel.checkConstraintUniqueQualityFormName()) { getQualityForm().setName(null); throw new WrongValueException(comp, _("{0} already exists", value)); @@ -192,9 +196,9 @@ public class QualityFormCRUDController extends BaseCRUDController { return (comp, value) -> { QualityFormItem item = ((Row) comp.getParent()).getValue(); item.setName((String)value); - if ((value == null) || (((String) value)).isEmpty()) { + if ((value == null) || ((String) value).isEmpty()) { item.setName(null); - throw new WrongValueException(comp, _("cannot be empty")); + throw new WrongValueException(comp, _(CANNOT_BE_EMPTY)); } else if (!qualityFormModel.checkConstraintUniqueQualityFormItemName()) { item.setName(null); throw new WrongValueException(comp, _("{0} already exists", value)); @@ -211,7 +215,7 @@ public class QualityFormCRUDController extends BaseCRUDController { if (newPercentage == null) { item.setPercentage(null); - throw new WrongValueException(comp, _("cannot be empty")); + throw new WrongValueException(comp, _(CANNOT_BE_EMPTY)); } if (qualityFormModel.checkConstraintOutOfRangeQualityFormItemPercentage(item)) { item.setPercentage(null); @@ -225,8 +229,7 @@ public class QualityFormCRUDController extends BaseCRUDController { } public boolean isByPercentage() { - return this.getQualityForm() != null && - getQualityForm().getQualityFormType().equals(QualityFormType.BY_PERCENTAGE); + return this.getQualityForm() != null && getQualityForm().getQualityFormType().equals(QualityFormType.BY_PERCENTAGE); } public boolean isByItems() { @@ -248,10 +251,9 @@ public class QualityFormCRUDController extends BaseCRUDController { } /** - * Apply filter to quality forms - * @param event + * Apply filter to quality forms. */ - public void onApplyFilter(Event event) { + public void onApplyFilter() { // Filter quality forms by name predicate = getSelectedName(); Util.reloadBindings(gridQualityForms); @@ -261,14 +263,10 @@ public class QualityFormCRUDController extends BaseCRUDController { return txtFilter.getValue(); } - private void clearFilter() { - txtFilter.setValue(""); - predicate = getSelectedName(); - } - public void validateReportProgress() { if ((getQualityForm().isReportAdvance()) && (!hasItemWithTotalPercentage())) { Checkbox checkBoxReportProgress = (Checkbox) editWindow.getFellowIfAny("checkBoxReportProgress"); + throw new WrongValueException( checkBoxReportProgress, _("Quality form should include an item with a value of 100% in order to report progress")); @@ -279,7 +277,7 @@ public class QualityFormCRUDController extends BaseCRUDController { return this.qualityFormModel.hasItemWithTotalPercentage(); } - private void disabledCheckbocReportProgress(Checkbox reportProgress) { + private void disabledCheckboxReportProgress(Checkbox reportProgress) { if (reportProgress != null) { getQualityForm().setReportAdvance(false); reportProgress.setChecked(false); @@ -332,8 +330,7 @@ public class QualityFormCRUDController extends BaseCRUDController { qualityFormModel.checkHasTasks(qualityForm); return false; } catch (ValidationException e) { - showCannotDeleteQualityFormDialog(e.getInvalidValue().getMessage() - ); + showCannotDeleteQualityFormDialog(e.getInvalidValue().getMessage()); } return true; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadDisplayData.java b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadDisplayData.java index 81b6b2c13..5c53bba92 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadDisplayData.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadDisplayData.java @@ -15,6 +15,34 @@ import org.zkoss.ganttz.util.Interval; public class ResourceLoadDisplayData { + private final List timeLines; + + private final Interval viewInterval; + + private final Paginator paginator; + + private final Callable> resourcesConsidered; + + private final Callable> assignmentsConsidered; + + public ResourceLoadDisplayData( + List timeLines, + Paginator paginator, + Callable> resourcesConsidered, + Callable> assignmentsConsidered) { + + Validate.notNull(timeLines); + Validate.notNull(paginator); + Validate.notNull(resourcesConsidered); + Validate.notNull(assignmentsConsidered); + + this.timeLines = timeLines; + this.viewInterval = getViewIntervalFrom(timeLines); + this.paginator = paginator; + this.resourcesConsidered = cached(resourcesConsidered); + this.assignmentsConsidered = cached(assignmentsConsidered); + } + private static Callable cached(Callable callable) { return new CachedCallable<>(callable); } @@ -28,6 +56,7 @@ public class ResourceLoadDisplayData { } private static class CachedCallable implements Callable { + private final Callable callable; private T result; @@ -42,47 +71,14 @@ public class ResourceLoadDisplayData { if (result != null) { return result; } - return result = callable.call(); + + result = callable.call(); + + return result; } } - private final List timeLines; - - private final Interval viewInterval; - - private final Paginator paginator; - - private final Callable> resourcesConsidered; - - private final Callable> assignmentsConsidered; - - private final LocalDate filterStart; - - private final LocalDate filterEnd; - - public ResourceLoadDisplayData( - List timeLines, - LocalDate filterStart, - LocalDate filterEnd, - Paginator paginator, - Callable> resourcesConsidered, - Callable> assignmentsConsidered) { - - Validate.notNull(timeLines); - Validate.notNull(paginator); - Validate.notNull(resourcesConsidered); - Validate.notNull(assignmentsConsidered); - - this.timeLines = timeLines; - this.filterStart = filterStart; - this.filterEnd = filterEnd; - this.viewInterval = getViewIntervalFrom(timeLines); - this.paginator = paginator; - this.resourcesConsidered = cached(resourcesConsidered); - this.assignmentsConsidered = cached(assignmentsConsidered); - } - private static Interval getViewIntervalFrom(List timeLines) { return LoadTimeLine.getIntervalFrom(timeLines); } @@ -115,12 +111,4 @@ public class ResourceLoadDisplayData { return resolve(assignmentsConsidered); } - public LocalDate getFilterStart() { - return filterStart; - } - - public LocalDate getFilterEnd() { - return filterEnd; - } - } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java index 7d554c6cb..1bc752904 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/resourceload/ResourceLoadModel.java @@ -133,8 +133,6 @@ public class ResourceLoadModel implements IResourceLoadModel { return new ResourceLoadDisplayData( loadTimeLines, - parameters.getInitDateFilter(), - parameters.getEndDateFilter(), allocationsFinder.getPaginator(), allocationsFinder.lazilyGetResourcesIncluded(), allocationsFinder.lazilyGetAssignmentsShown()); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/resources/search/NewAllocationSelectorComboController.java b/libreplan-webapp/src/main/java/org/libreplan/web/resources/search/NewAllocationSelectorComboController.java index 52f5ece99..6f2430ef6 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/resources/search/NewAllocationSelectorComboController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/resources/search/NewAllocationSelectorComboController.java @@ -36,40 +36,38 @@ import org.libreplan.web.planner.allocation.INewAllocationsAdder; import org.zkoss.zk.ui.Component; /** - * @author Susana Montes Pedreira + * Controller for searching for {@link Resource}. * - * Controller for searching for {@link Resource} + * @author Susana Montes Pedreira */ -public class NewAllocationSelectorComboController extends - AllocationSelectorController { +public class NewAllocationSelectorComboController extends AllocationSelectorController { - private ResourceAllocationBehaviour behaviour; + private ResourceAllocationBehaviour currentBehaviour; private BandboxMultipleSearch bbMultipleSearch; public NewAllocationSelectorComboController(ResourceAllocationBehaviour behaviour) { - this.behaviour = behaviour; + this.currentBehaviour = behaviour; } @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); - bbMultipleSearch.setFinder(behaviour.getFinder()); + bbMultipleSearch.setFinder(currentBehaviour.getFinder()); } /** - * Does the actual search for workers + * Does the actual search for workers. * * @param criteria */ private List searchResources(List criteria) { - return query(inferType(criteria)).byCriteria(criteria) - .byResourceType(behaviour.getType()).execute(); + return query(inferType(criteria)).byCriteria(criteria).byResourceType(currentBehaviour.getType()).execute(); } private static ResourceEnum inferType(List criteria) { if (criteria.isEmpty()) { - // FIXME resolve the ambiguity. One option is asking the user + // FIXME resolve the ambiguity; one option is asking the user return ResourceEnum.WORKER; } return first(criteria).getType().getResource(); @@ -84,12 +82,12 @@ public class NewAllocationSelectorComboController extends } /** - * Returns list of selected {@link Criterion}, selects only those which are - * leaf nodes - * @return + * Returns list of selected {@link Criterion}, selects only those which are leaf nodes. + * + * @return {@link List} */ public List getSelectedCriterions() { - List criteria = new ArrayList(); + List criteria = new ArrayList<>(); for (FilterPair pair : getSelectedItems()) { if (pair.getType().equals(ResourceAllocationFilterEnum.Criterion)) { criteria.add((Criterion) pair.getValue()); @@ -99,13 +97,11 @@ public class NewAllocationSelectorComboController extends } private List getSelectedItems() { - return ((List) bbMultipleSearch - .getSelectedElements()); + return ((List) bbMultipleSearch.getSelectedElements()); } private boolean isGeneric() { - return ((FilterPair) getSelectedItems().get(0)).getType().equals( - ResourceAllocationFilterEnum.Criterion); + return getSelectedItems().get(0).getType().equals(ResourceAllocationFilterEnum.Criterion); } public void onClose() { @@ -117,7 +113,7 @@ public class NewAllocationSelectorComboController extends } public List getSelectedResources() { - List resources = new ArrayList(); + List resources = new ArrayList<>(); for (FilterPair pair : getSelectedItems()) { if (pair.getType().equals(ResourceAllocationFilterEnum.Resource)) { resources.add((Resource) pair.getValue()); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/security/SecurityUtils.java b/libreplan-webapp/src/main/java/org/libreplan/web/security/SecurityUtils.java index 15f9fee74..96faf7521 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/security/SecurityUtils.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/security/SecurityUtils.java @@ -55,7 +55,6 @@ public final class SecurityUtils { public static boolean isGatheredStatsAlreadySent = false; private SecurityUtils() { - } public static boolean isUserInRole(UserRole role) { diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/subcontract/SubcontractedTasksModel.java b/libreplan-webapp/src/main/java/org/libreplan/web/subcontract/SubcontractedTasksModel.java index 2d5cbf718..2669e7e95 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/subcontract/SubcontractedTasksModel.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/subcontract/SubcontractedTasksModel.java @@ -34,7 +34,6 @@ import javax.xml.bind.Marshaller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.cxf.jaxrs.client.WebClient; -import org.libreplan.business.common.daos.IConfigurationDAO; import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.externalcompanies.entities.ExternalCompany; import org.libreplan.business.orders.daos.IOrderDAO; @@ -89,9 +88,6 @@ public class SubcontractedTasksModel implements ISubcontractedTasksModel { @Autowired private IOrderDAO orderDAO; - @Autowired - private IConfigurationDAO configurationDAO; - @Override @Transactional(readOnly = true) public List getSubcontractedTasks() { diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/tree/TreeComponent.java b/libreplan-webapp/src/main/java/org/libreplan/web/tree/TreeComponent.java index 9d476bde7..a8350a5ae 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/tree/TreeComponent.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/tree/TreeComponent.java @@ -34,7 +34,6 @@ import org.zkoss.zul.Treeitem; /** * Macro component for order elements tree and similar pages. *
- * * @author Óscar González Fernández * @author Lorenzo Tilve Álvaro */ @@ -44,27 +43,21 @@ public abstract class TreeComponent extends HtmlMacroComponent { protected Column codeColumn = new Column(_("Code"), "code") { @Override - public > void doCell( - TreeController.Renderer renderer, Treeitem item, T currentElement) { - + public > void doCell(TreeController.Renderer renderer, Treeitem item, T currentElement) { renderer.addCodeCell(currentElement); } }; protected final Column nameAndDescriptionColumn = new Column(_("Name"), "name") { @Override - public > void doCell( - TreeController.Renderer renderer, Treeitem item, T currentElement) { - + public > void doCell(TreeController.Renderer renderer, Treeitem item, T currentElement) { renderer.addDescriptionCell(currentElement); } }; protected final Column operationsColumn = new Column(_("Op."), "operations", _("Operations")) { @Override - public > void doCell( - TreeController.Renderer renderer, Treeitem item, T currentElement) { - + public > void doCell(TreeController.Renderer renderer, Treeitem item, T currentElement) { renderer.addOperationsCell(item, currentElement); } }; @@ -75,9 +68,7 @@ public abstract class TreeComponent extends HtmlMacroComponent { _("Fully, Partially or Unscheduled. (Drag and drop to move tasks)")) { @Override - public > void doCell( - TreeController.Renderer renderer, Treeitem item, T currentElement) { - + public > void doCell(TreeController.Renderer renderer, Treeitem item, T currentElement) { renderer.addSchedulingStateCell(currentElement); } }; @@ -125,34 +116,27 @@ public abstract class TreeComponent extends HtmlMacroComponent { /* TODO remove me, if ZK Load on demand issue will be resolved */ public String getHflex() { - return cssClass.equals("name") ? "1" : "min"; + return "name".equals(cssClass) ? "1" : "min"; } /* TODO remove me, if ZK Load on demand issue will be resolved */ public String getWidth() { if (cssClass.contains("scheduling_state")) { return "135px"; - } else if (cssClass.equals("code")) { + } else if ("code".equals(cssClass)) { return "106px"; - } else if (cssClass.equals("name")) { + } else if ("name".equals(cssClass)) { return "950px"; - } else if (cssClass.equals("hours")) { + } else if ("hours".equals(cssClass) || "budget".equals(cssClass) || "operations".equals(cssClass)) { return "50px"; - } else if (cssClass.equals("budget")) { - return "50px"; - } else if (cssClass.equals("estimated_init")) { + } else if ("estimated_init".equals(cssClass) || "estimated_end".equals(cssClass)) { return "100px"; - } else if (cssClass.equals("estimated_end")) { - return "100px"; - } else if (cssClass.equals("operations") ) { - return "50px"; } return ""; } - public abstract > void doCell( - TreeController.Renderer renderer, Treeitem item, T currentElement); + public abstract > void doCell(TreeController.Renderer renderer, Treeitem item, T currentElement); } public abstract List getColumns(); diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/users/ProfileCRUDController.java b/libreplan-webapp/src/main/java/org/libreplan/web/users/ProfileCRUDController.java index 5cca300a7..2d4b080bd 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/users/ProfileCRUDController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/users/ProfileCRUDController.java @@ -45,7 +45,7 @@ import java.util.List; import static org.libreplan.web.I18nHelper._; /** - * Controller for CRUD actions over a {@link Profile} + * Controller for CRUD actions over a {@link Profile}. * * @author Jacobo Aragunde Perez * @author Diego Pino García @@ -57,8 +57,10 @@ public class ProfileCRUDController extends BaseCRUDController { private Combobox userRolesCombo; - public ProfileCRUDController(){ - profileModel = (IProfileModel) SpringUtil.getBean("profileModel"); + public ProfileCRUDController() { + if ( profileModel == null ) { + profileModel = (IProfileModel) SpringUtil.getBean("profileModel"); + } } @Override @@ -70,6 +72,7 @@ public class ProfileCRUDController extends BaseCRUDController { /** * Appends the existing UserRoles to the Combobox passed. + * * @param combo */ private void appendAllUserRolesExceptRoleBoundUser(Combobox combo) { @@ -82,7 +85,7 @@ public class ProfileCRUDController extends BaseCRUDController { } } - protected void save() throws ValidationException{ + protected void save() throws ValidationException { profileModel.confirmSave(); } @@ -96,8 +99,8 @@ public class ProfileCRUDController extends BaseCRUDController { public void addSelectedRole() { Comboitem comboItem = userRolesCombo.getSelectedItem(); - if(comboItem != null) { - addRole((UserRole)comboItem.getValue()); + if (comboItem != null) { + addRole(comboItem.getValue()); } } @@ -145,8 +148,7 @@ public class ProfileCRUDController extends BaseCRUDController { profileModel.checkHasUsers(profile); return false; } catch (ValidationException e) { - showCannotDeleteProfileDialog(e.getInvalidValue().getMessage() - ); + showCannotDeleteProfileDialog(e.getInvalidValue().getMessage()); } return true; diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/users/UserCRUDController.java b/libreplan-webapp/src/main/java/org/libreplan/web/users/UserCRUDController.java index 270dac3c3..7cb41cd52 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/users/UserCRUDController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/users/UserCRUDController.java @@ -85,12 +85,9 @@ public class UserCRUDController extends BaseCRUDController implements IUse private Combobox profilesCombo; - private Button showCreateForm; - private IURLHandlerRegistry URLHandlerRegistry; public UserCRUDController() { - } private RowRenderer usersRenderer = (row, data, i) -> { @@ -103,8 +100,8 @@ public class UserCRUDController extends BaseCRUDController implements IUse Util.appendLabel(row, _(user.getUserType().toString())); Util.appendLabel(row, user.isBound() ? user.getWorker().getShortDescription() : ""); - Button[] buttons = Util.appendOperationsAndOnClickEvent(row, - event -> goToEditForm(user), event -> confirmDelete(user)); + Button[] buttons = + Util.appendOperationsAndOnClickEvent(row, event -> goToEditForm(user), event -> confirmDelete(user)); // Disable remove button for default admin as it's mandatory if ( isDefaultAdmin(user) ) { @@ -122,7 +119,10 @@ public class UserCRUDController extends BaseCRUDController implements IUse passwordBox = (Textbox) editWindow.getFellowIfAny("password"); passwordConfirmationBox = (Textbox) editWindow.getFellowIfAny("passwordConfirmation"); profilesCombo = (Combobox) editWindow.getFellowIfAny("profilesCombo"); + userRolesCombo = (Combobox) editWindow.getFellowIfAny("userRolesCombo"); + userRolesCombo.setWidth("320px"); + appendAllUserRolesExceptRoleBoundUser(userRolesCombo); appendAllProfiles(profilesCombo); boundResourceGroupbox = (Groupbox) editWindow.getFellowIfAny("boundResourceGroupbox"); @@ -132,14 +132,26 @@ public class UserCRUDController extends BaseCRUDController implements IUse } private void injectsObjects() { - userModel = (IUserModel) SpringUtil.getBean("userModel"); - limitsModel = (ILimitsModel) SpringUtil.getBean("limitsModel"); - workerCRUD = (IWorkerCRUDControllerEntryPoints) SpringUtil.getBean("workerCRUD"); - URLHandlerRegistry = (IURLHandlerRegistry) SpringUtil.getBean("URLHandlerRegistry"); + if ( userModel == null ) { + userModel = (IUserModel) SpringUtil.getBean("userModel"); + } + + if ( limitsModel == null ) { + limitsModel = (ILimitsModel) SpringUtil.getBean("limitsModel"); + } + + if ( workerCRUD == null ) { + workerCRUD = (IWorkerCRUDControllerEntryPoints) SpringUtil.getBean("workerCRUD"); + } + + if ( URLHandlerRegistry == null ) { + URLHandlerRegistry = (IURLHandlerRegistry) SpringUtil.getBean("URLHandlerRegistry"); + } } /** * Appends the existing UserRoles to the Combobox passed. + * * @param combo */ private void appendAllUserRolesExceptRoleBoundUser(Combobox combo) { @@ -188,7 +200,7 @@ public class UserCRUDController extends BaseCRUDController implements IUse public void addSelectedRole() { Comboitem comboItem = userRolesCombo.getSelectedItem(); - if(comboItem != null) { + if (comboItem != null) { addRole(comboItem.getValue()); } } @@ -210,7 +222,7 @@ public class UserCRUDController extends BaseCRUDController implements IUse public void addSelectedProfile() { Comboitem comboItem = profilesCombo.getSelectedItem(); - if(comboItem != null) { + if (comboItem != null) { addProfile(comboItem.getValue()); } } @@ -226,22 +238,21 @@ public class UserCRUDController extends BaseCRUDController implements IUse } /** - * Tells the XXXModel to set the password attribute of the inner - * {@ link User} object. + * Tells the XXXModel to set the password attribute of the inner {@link User} object. * * @param password String with the unencrypted password. */ public void setPassword(String password) { userModel.setPassword(password); - //update the constraint on the confirmation password box - ((Textbox)editWindow.getFellowIfAny("passwordConfirmation")).clearErrorMessage(true); + // Update the constraint on the confirmation password box + ((Textbox) editWindow.getFellowIfAny("passwordConfirmation")).clearErrorMessage(true); } public Constraint validatePasswordConfirmation() { return (comp, value) -> { - ((Textbox)comp).setRawValue(value); + ((Textbox) comp).setRawValue(value); - if(!value.equals(passwordBox.getValue())) { + if (!value.equals(passwordBox.getValue())) { throw new WrongValueException(comp, _("passwords don't match")); } }; @@ -260,25 +271,29 @@ public class UserCRUDController extends BaseCRUDController implements IUse @Override protected void initCreate() { userModel.initCreate(); - //password is compulsory when creating + + // Password is compulsory when creating passwordBox.setConstraint("no empty:" + _("Password cannot be empty")); - //clean the password boxes, they are not cleared automatically - //because they are not directly associated to an attribute + + // Clean the password boxes, they are not cleared automatically because they are not directly associated to an attribute passwordBox.setRawValue(""); passwordConfirmationBox.setRawValue(""); + prepareAuthenticationTypesCombo(); } @Override protected void initEdit(User user) { userModel.initEdit(user); - //password is not compulsory when editing, so we remove - //the constraint + + // Password is not compulsory when editing, so we remove the constraint passwordBox.setConstraint((Constraint)null); - //cleans the box and forces the check of the new Constraint (null) + + // Cleans the box and forces the check of the new Constraint (null) passwordBox.setValue(""); passwordConfirmationBox.setValue(""); - //setup authentication type combo box + + // Setup authentication type combo box prepareAuthenticationTypesCombo(); } @@ -305,12 +320,11 @@ public class UserCRUDController extends BaseCRUDController implements IUse @Override protected boolean beforeDeleting(User user) { Worker worker = user.getWorker(); + return worker == null || Messagebox.show(_("User is bound to resource \"{0}\" and it will be unbound. " + - "Do you want to continue with user removal?", - worker.getShortDescription()), - _("Confirm remove user"), - Messagebox.YES | Messagebox.NO, Messagebox.QUESTION) == Messagebox.YES; + "Do you want to continue with user removal?", worker.getShortDescription()), + _("Confirm remove user"), Messagebox.YES | Messagebox.NO, Messagebox.QUESTION) == Messagebox.YES; } @Override @@ -320,16 +334,15 @@ public class UserCRUDController extends BaseCRUDController implements IUse public boolean isLdapUser() { User user = userModel.getUser(); - return user != null && !user.isLibrePlanUser(); } public boolean isLdapUserLdapConfiguration() { - return (isLdapUser() && userModel.isLDAPBeingUsed()); + return isLdapUser() && userModel.isLDAPBeingUsed(); } public boolean getLdapUserRolesLdapConfiguration() { - return (isLdapUser() && userModel.isLDAPRolesBeingUsed()); + return isLdapUser() && userModel.isLDAPRolesBeingUsed(); } public RowRenderer getRolesRenderer() { @@ -339,6 +352,7 @@ public class UserCRUDController extends BaseCRUDController implements IUse row.appendChild(new Label(_(role.getDisplayName()))); Button removeButton = Util.createRemoveButton(event -> removeRole(role)); + removeButton.setDisabled(areRolesAndProfilesDisabled() || role.equals(UserRole.ROLE_BOUND_USER) || isUserDefaultAdmin()); @@ -352,25 +366,16 @@ public class UserCRUDController extends BaseCRUDController implements IUse public String hasBoundResource() { User user = getUser(); - if (user != null && user.isBound()) { - return _("Yes"); - } - - return _("No"); + return user != null && user.isBound() ? _("Yes") : _("No"); } public String getBoundResource() { User user = getUser(); - if (user != null && user.isBound()) { - return user.getWorker().getShortDescription(); - } - - return ""; + return user != null && user.isBound() ? user.getWorker().getShortDescription() : ""; } public boolean isBound() { User user = getUser(); - return user != null && user.isBound(); } @@ -383,10 +388,8 @@ public class UserCRUDController extends BaseCRUDController implements IUse } private int showConfirmWorkerEditionDialog() { - return Messagebox - .show(_("Unsaved changes will be lost. Would you like to continue?"), - _("Confirm edit worker"), Messagebox.OK - | Messagebox.CANCEL, Messagebox.QUESTION); + return Messagebox.show(_("Unsaved changes will be lost. Would you like to continue?"), + _("Confirm edit worker"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION); } public void unboundResource() { @@ -399,11 +402,7 @@ public class UserCRUDController extends BaseCRUDController implements IUse } public String getWorkerEditionButtonTooltip() { - if (isNoRoleWorkers()) { - return _("You do not have permissions to go to edit worker window"); - } - - return ""; + return isNoRoleWorkers() ? _("You do not have permissions to go to edit worker window") : ""; } private boolean isDefaultAdmin(final User user) { @@ -412,7 +411,6 @@ public class UserCRUDController extends BaseCRUDController implements IUse private boolean isUserDefaultAdmin() { User user = userModel.getUser(); - return user != null && isDefaultAdmin(user); } @@ -426,18 +424,12 @@ public class UserCRUDController extends BaseCRUDController implements IUse public UserAuthenticationType getAuthenticationType() { User user = getUser(); - if (user != null) { - return user.getUserType(); - } - - return null; + return user != null ? user.getUserType() : null; } public void setAuthenticationType(Comboitem item) { if (item == null) { - throw new WrongValueException( - editWindow.getFellowIfAny("authenticationTypeCombo"), - _("cannot be empty")); + throw new WrongValueException(editWindow.getFellowIfAny("authenticationTypeCombo"), _("cannot be empty")); } UserAuthenticationType authenticationType = item.getValue(); @@ -451,7 +443,6 @@ public class UserCRUDController extends BaseCRUDController implements IUse public boolean isCreateButtonDisabled() { Limits usersTypeLimit = limitsModel.getUsersType(); Integer usersCount = userModel.getRowCount().intValue(); - return usersTypeLimit != null && usersCount >= usersTypeLimit.getValue(); } @@ -464,9 +455,8 @@ public class UserCRUDController extends BaseCRUDController implements IUse Integer usersCount = userModel.getRowCount().intValue(); int usersLeft = usersTypeLimit.getValue() - usersCount; - if ( usersCount >= usersTypeLimit.getValue() ) - return _("User limit reached"); - - return _("Create") + " ( " + usersLeft + " " + _("left") + " )"; + return usersCount >= usersTypeLimit.getValue() + ? _("User limit reached") + : _("Create") + " ( " + usersLeft + " " + _("left") + " )"; } } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/users/dashboard/PersonalTimesheetController.java b/libreplan-webapp/src/main/java/org/libreplan/web/users/dashboard/PersonalTimesheetController.java index bb34eeb2d..682e593d6 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/users/dashboard/PersonalTimesheetController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/users/dashboard/PersonalTimesheetController.java @@ -251,7 +251,10 @@ public class PersonalTimesheetController extends GenericForwardComposer implemen private void openPersonalTimesheetPopup(Textbox textbox, OrderElement orderElement, LocalDate textboxDate) { Textbox toFocus = setupPersonalTimesheetPopup(textbox, orderElement, textboxDate); + personalTimesheetPopup.open(textbox, "after_start"); + ((Column) personalTimesheetPopup.getChildren().get(0).getChildren().get(0).getChildren().get(0)).setWidth("60px"); + toFocus.setFocus(true); } @@ -419,16 +422,16 @@ public class PersonalTimesheetController extends GenericForwardComposer implemen private void renderCapacityRow(Row row) { appendLabelSpaningTwoColumns(row, _("Capacity")); - appendCapcityForDaysAndTotal(row); + appendCapacityForDaysAndTotal(row); } - private void appendCapcityForDaysAndTotal(Row row) { + private void appendCapacityForDaysAndTotal(Row row) { EffortDuration totalCapacity = EffortDuration.zero(); for (LocalDate day = first; day.compareTo(last) <= 0; day = day.plusDays(1)) { EffortDuration capacity = personalTimesheetModel.getResourceCapacity(day); - Cell cell = getCenteredCell(getDisabledTextbox(getCapcityColumnTextboxId(day), capacity)); + Cell cell = getCenteredCell(getDisabledTextbox(getCapacityColumnTextboxId(day), capacity)); if ( personalTimesheetModel.getResourceCapacity(day).isZero() ) { setBackgroundNonCapacityCell(cell); @@ -471,7 +474,7 @@ public class PersonalTimesheetController extends GenericForwardComposer implemen private void updateExtraRow(LocalDate date) { EffortDuration total = getEffortDuration(getTotalColumnTextboxId(date)); - EffortDuration capacity = getEffortDuration(getCapcityColumnTextboxId(date)); + EffortDuration capacity = getEffortDuration(getCapacityColumnTextboxId(date)); EffortDuration extra = EffortDuration.zero(); if ( total.compareTo(capacity) > 0 ) { @@ -837,7 +840,7 @@ public class PersonalTimesheetController extends GenericForwardComposer implemen return "textbox-other-capacity"; } - private static String getCapcityColumnTextboxId(LocalDate date) { + private static String getCapacityColumnTextboxId(LocalDate date) { return "textbox-capacity-column-" + date; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/users/services/LDAPCustomAuthenticationProvider.java b/libreplan-webapp/src/main/java/org/libreplan/web/users/services/LDAPCustomAuthenticationProvider.java index 5094d19ae..7b8e4fdc0 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/users/services/LDAPCustomAuthenticationProvider.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/users/services/LDAPCustomAuthenticationProvider.java @@ -49,7 +49,6 @@ import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; -import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.transaction.annotation.Transactional; @@ -70,7 +69,8 @@ import org.springframework.transaction.annotation.Transactional; */ // TODO resolve deprecated methods -public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider +public class LDAPCustomAuthenticationProvider + extends AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider { @Autowired @@ -84,7 +84,7 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent private LDAPConfiguration configuration; - // Template to search in LDAP + /** Template to search in LDAP */ private LdapTemplate ldapTemplate; private UserDetailsService userDetailsService; @@ -98,21 +98,18 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent private static final Log LOG = LogFactory.getLog(LDAPCustomAuthenticationProvider.class); /** - * LDAP role matching could be configured using an asterix (*) - * to specify all users or groups + * LDAP role matching could be configured using an asterix (*) to specify all users or groups */ private static final String WILDCHAR_ALL = "*"; @Override - protected void additionalAuthenticationChecks(UserDetails arg0, UsernamePasswordAuthenticationToken arg1) - throws AuthenticationException { + protected void additionalAuthenticationChecks(UserDetails arg0, UsernamePasswordAuthenticationToken arg1) { // No needed at this time } @Transactional(readOnly = true) @Override - public UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) - throws AuthenticationException { + public UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) { String clearPassword = authentication.getCredentials().toString(); @@ -130,6 +127,7 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent } // If it's a LDAP or null user, then we must authenticate against LDAP + // Load LDAPConfiguration properties configuration = loadLDAPConfiguration(); @@ -191,12 +189,14 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent User user = User.create(); user.setLoginName(username); + String newEncodedPassword = encodedPassword; + // we must check if it is needed to save LDAP passwords in DB if ( !configuration.isLdapSavePasswordsDB() ) { - encodedPassword = null; + newEncodedPassword = null; } - user.setPassword(encodedPassword); + user.setPassword(newEncodedPassword); user.setLibrePlanUser(false); user.setDisabled(false); setRoles(user); @@ -243,8 +243,7 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent try { context.afterPropertiesSet(); } catch (Exception e) { - // This exception will be never reached if the LDAP - // properties are well-formed. + // This exception will be never reached if the LDAP properties are well-formed. LOG.error("There is a problem in LDAP connection: ", e); } @@ -259,13 +258,12 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent } private void saveUserOnTransaction(User user) { - final User userLibrePlan = user; + final User librePlanUser = user; transactionService.runOnTransaction(new IOnTransaction() { @Override public Void execute() { - userDAO.save(userLibrePlan); - + userDAO.save(librePlanUser); return null; } }); @@ -355,17 +353,14 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent try { if ( !configuration.getLdapGroupStrategy() ) { - // The LDAP has a node strategy for groups, - // we must check the roleProperty in user node. + // The LDAP has a node strategy for groups, we must check the roleProperty in user node return getRolesUsingNodeStrategy(rolesLdap, queryRoles, configuration); } else { - // The LDAP has a branch strategy for groups - // we must check if the user is in one of the groups. + // The LDAP has a branch strategy for groups we must check if the user is in one of the groups return getRolesUsingBranchStrategy(rolesLdap, queryRoles, configuration); } } catch (Exception e) { LOG.error("Configuration of LDAP role-matching is wrong. Please check it.", e); - return Collections.emptyList(); } } @@ -378,7 +373,6 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent this.passwordEncoderService = passwordEncoderService; } - // Getters and setters public LdapTemplate getLdapTemplate() { return ldapTemplate; } diff --git a/libreplan-webapp/src/main/java/org/libreplan/web/workreports/WorkReportCRUDController.java b/libreplan-webapp/src/main/java/org/libreplan/web/workreports/WorkReportCRUDController.java index a20256084..8d3dc49b0 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/web/workreports/WorkReportCRUDController.java +++ b/libreplan-webapp/src/main/java/org/libreplan/web/workreports/WorkReportCRUDController.java @@ -987,6 +987,10 @@ public class WorkReportCRUDController // Create the fields and labels appendFieldsAndLabelsInLines(row); + NewDataSortableGrid grid = (NewDataSortableGrid) row.getParent().getParent(); + NewDataSortableColumn priorityColumn = (NewDataSortableColumn) grid.getChildren().get(1).getChildren().get(2); + priorityColumn.setWidth("110px"); + if (!getWorkReport().getWorkReportType().getHoursManagement().equals(HoursManagementEnum.NUMBER_OF_HOURS)) { appendHoursStartAndFinish(row); } @@ -1374,7 +1378,7 @@ public class WorkReportCRUDController descriptionValue::setValue); } - private Autocomplete createAutocompleteLabels(LabelType labelType,Label selectedLabel) { + private Autocomplete createAutocompleteLabels(LabelType labelType, Label selectedLabel) { Autocomplete comboLabels = new Autocomplete(); comboLabels.setButtonVisible(true); comboLabels.setWidth("100px"); diff --git a/libreplan-webapp/src/main/java/org/libreplan/ws/common/impl/LabelReferenceConverter.java b/libreplan-webapp/src/main/java/org/libreplan/ws/common/impl/LabelReferenceConverter.java index 2d1455df2..0e90dcd2d 100644 --- a/libreplan-webapp/src/main/java/org/libreplan/ws/common/impl/LabelReferenceConverter.java +++ b/libreplan-webapp/src/main/java/org/libreplan/ws/common/impl/LabelReferenceConverter.java @@ -40,35 +40,23 @@ public final class LabelReferenceConverter { } public final static Set toDTO(Set