Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Paul Luchyn 2016-11-08 18:52:11 +02:00
commit cf623623ad
82 changed files with 1576 additions and 1871 deletions

View file

@ -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

View file

@ -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.

View file

@ -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

View file

@ -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<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues = new HashSet<NonCalculatedConsolidatedValue>();
private Set<NonCalculatedConsolidatedValue> 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 <code>null</code>. Otherwise
* keep the old value stored.
* Just set the communication date if it was <code>null</code>.
* 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<DirectAdvanceAssignment> directAdvanceAssignments = orderElement
.getAllDirectAdvanceAssignments(advanceAssignment
.getAdvanceType());
Set<DirectAdvanceAssignment> 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<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues) {
public void setNonCalculatedConsolidatedValues(Set<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues) {
this.nonCalculatedConsolidatedValues = nonCalculatedConsolidatedValues;
}

View file

@ -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. <br />
* It contains the current version of project and implements of singleton pattern.
* <br />
* 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());
}
}

View file

@ -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 <fbellas@udc.es>
*/
public class IntegrationEntityDAO<E extends IntegrationEntity>
extends GenericDAOHibernate<E, Long> implements IIntegrationEntityDAO<E> {
extends GenericDAOHibernate<E, Long>
implements IIntegrationEntityDAO<E> {
@Override
public boolean existsByCode(String code) {
try {
findByCode(code);
return true;
} catch (InstanceNotFoundException e) {
return false;
}
}
@Override
@ -64,17 +62,17 @@ public class IntegrationEntityDAO<E extends IntegrationEntity>
@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<E extends IntegrationEntity>
@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")

View file

@ -80,6 +80,7 @@ import org.springframework.stereotype.Component;
/**
* @author Óscar González Fernández
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
@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<SortedMap<CriterionType, List<Criterion>>> criterionsMap;
private IAutoUpdatedSnapshot<Map<LabelType, List<Label>>> labelsMap;
private IAutoUpdatedSnapshot<List<Worker>> listWorkers;
private IAutoUpdatedSnapshot<List<CostCategory>> listCostCategories;
private IAutoUpdatedSnapshot<List<Criterion>> listCriterion;
private IAutoUpdatedSnapshot<Map<Class<?>, List<Resource>>> mapResources;
private IAutoUpdatedSnapshot<List<ExternalCompany>> externalCompanies;
private IAutoUpdatedSnapshot<List<String>> customerReferences;
private IAutoUpdatedSnapshot<List<String>> ordersCodes;
private IAutoUpdatedSnapshot<ResourceLoadChartData> resourceLoadChartData;
private IAutoUpdatedSnapshot<List<WorkReportLine>> workReportLines;
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>> estimatedCostPerTask;
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>> advanceCostPerTask;
private boolean snapshotsRegistered = false;
public SortedMap<CriterionType, List<Criterion>> snapshotCriterionsMap() {
return criterionsMap.getValue();
}
private IAutoUpdatedSnapshot<Map<LabelType, List<Label>>> labelsMap;
public Map<LabelType, List<Label>> snapshotLabelsMap() {
return labelsMap.getValue();
}
private IAutoUpdatedSnapshot<List<Worker>> listWorkers;
public List<Worker> snapshotListWorkers() {
return listWorkers.getValue();
}
private IAutoUpdatedSnapshot<List<CostCategory>> listCostCategories;
public List<CostCategory> snapshotListCostCategories() {
return listCostCategories.getValue();
}
private IAutoUpdatedSnapshot<List<Criterion>> listCriterion;
public List<Criterion> snapshotListCriterion() {
return listCriterion.getValue();
}
private IAutoUpdatedSnapshot<Map<Class<?>, List<Resource>>> mapResources;
public Map<Class<?>, List<Resource>> snapshotMapResources() {
return mapResources.getValue();
}
private IAutoUpdatedSnapshot<List<ExternalCompany>> externalCompanies;
public List<ExternalCompany> snapshotExternalCompanies() {
return externalCompanies.getValue();
}
private IAutoUpdatedSnapshot<List<String>> customerReferences;
public List<String> snapshotCustomerReferences() {
return customerReferences.getValue();
}
private IAutoUpdatedSnapshot<List<String>> ordersCodes;
public List<String> snapshotOrdersCodes() {
return ordersCodes.getValue();
}
private IAutoUpdatedSnapshot<ResourceLoadChartData>
resourceLoadChartData;
public ResourceLoadChartData snapshotResourceLoadChartData() {
return resourceLoadChartData.getValue();
}
private IAutoUpdatedSnapshot<List<WorkReportLine>> workReportLines;
public List<WorkReportLine> snapshotWorkReportLines() {
return workReportLines.getValue();
}
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>>
estimatedCostPerTask;
public Map<TaskElement,SortedMap<LocalDate, BigDecimal>> snapshotEstimatedCostPerTask() {
return estimatedCostPerTask.getValue();
}
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>>
advanceCostPerTask;
public Map<TaskElement,SortedMap<LocalDate, BigDecimal>> 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<SortedMap<CriterionType, List<Criterion>>> calculateCriterionsMap() {
return () -> {
SortedMap<CriterionType, List<Criterion>> result = new TreeMap<>(getComparatorByName());
@ -262,15 +295,9 @@ public class PredefinedDatabaseSnapshots {
}
private Comparator<CriterionType> 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<Map<LabelType, List<Label>>> calculateLabelsMap() {
return () -> {
Map<LabelType, List<Label>> result = new HashMap<>();
@ -282,15 +309,13 @@ public class PredefinedDatabaseSnapshots {
};
}
@Autowired
private IWorkerDAO workerDAO;
private Callable<List<Worker>> calculateWorkers() {
return () -> workerDAO.getAll();
}
@Autowired
private ICostCategoryDAO costCategoryDAO;
private Callable<List<CostCategory>> calculateListCostCategories() {
return () -> costCategoryDAO.findActive();
@ -300,9 +325,6 @@ public class PredefinedDatabaseSnapshots {
return criterionDAO::getAll;
}
@Autowired
private IResourceDAO resourceDAO;
private Callable<Map<Class<?>, List<Resource>>> calculateMapResources() {
return () -> {
Map<Class<?>, List<Resource>> result = new HashMap<>();
@ -314,25 +336,15 @@ public class PredefinedDatabaseSnapshots {
};
}
@Autowired
private IExternalCompanyDAO externalCompanyDAO;
private Callable<List<ExternalCompany>> calculateExternalCompanies() {
return () -> externalCompanyDAO.getExternalCompaniesAreClient();
}
@Autowired
private IOrderDAO orderDAO;
private Callable<List<String>> calculateCustomerReferences() {
return () -> {
// FIXME replace by a HQL query, for god's sake!
List<String> 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<ResourceLoadChartData> calculateResourceLoadChartData() {
return () -> {
List<DayAssignment> dayAssignments = dayAssignmentDAO.getAllFor(scenarioManager.getCurrent(), null, null);
List<Resource> resources = resourceDAO.list(Resource.class);
return new ResourceLoadChartData(dayAssignments, resources);
};
}
@Autowired
private IWorkReportLineDAO workReportLineDAO;
private Callable<List<WorkReportLine>> calculateWorkReportLines() {
return () -> workReportLineDAO.list(WorkReportLine.class);
}
@Autowired
private ICostCalculator hoursCostCalculator;
@Autowired
private ITaskElementDAO taskElementDAO;
private Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>> calculateEstimatedCostPerTask() {
return () -> {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> 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;

View file

@ -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 <rego@igalia.com>
*/
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) {

View file

@ -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 <ogonzalez@igalia.com>
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
* @author Diego Pino Garcia <dpino@igalia.com>
* @author Jacobo Aragunde Pérez <jaragunde@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
public interface IOrderDAO extends IIntegrationEntityDAO<Order> {
/**
* Gets all the orders.
*
* @return A {@link List} of {@link Order} objects
*/
List<Order> 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<OrderCostsPerResourceDTO> getOrderCostsPerResource(List<Order> orders,
Date startingDate, Date endingDate,
List<Criterion> criterions);
List<OrderCostsPerResourceDTO> getOrderCostsPerResource(
List<Order> orders, Date startingDate, Date endingDate, List<Criterion> 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<Order> 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<Order> getOrdersByWriteAuthorization(User user);
List<Order> getOrdersByReadAuthorizationByScenario(String username,
Scenario scenario);
List<Order> getOrdersByReadAuthorizationByScenario(String username, Scenario scenario);
List<Order> getOrdersByReadAuthorizationBetweenDatesByLabelsCriteriaCustomerAndState(
String username, Scenario scenario, Date startDate, Date endDate,
@ -88,30 +89,35 @@ public interface IOrderDAO extends IIntegrationEntityDAO<Order> {
ExternalCompany customer, OrderStatusEnum state);
/**
* Returns the order filtered by the name. If name is blank (whitespace,
* empty ("") or null, it throws <code>InstanceNotFoundException</code>.
* Returns the order filtered by the name.
* If name is blank (whitespace, empty ("") or null, it throws <code>InstanceNotFoundException</code>.
*
* @param name
* String
* @return order Order
*/
public Order findByNameAnotherTransaction(String name)
throws InstanceNotFoundException;
Order findByNameAnotherTransaction(String name) throws InstanceNotFoundException;
List<Order> getOrdersByScenario(Scenario scenario);
List<Task> getFilteredTask(List<OrderElement> orderElements,
List<Criterion> criterions);
List<Task> getFilteredTask(List<OrderElement> orderElements, List<Criterion> criterions);
public Order loadOrderAvoidingProxyFor(OrderElement orderElement);
Order loadOrderAvoidingProxyFor(OrderElement orderElement);
public List<Order> loadOrdersAvoidingProxyFor(
List<OrderElement> orderElement);
List<Order> loadOrdersAvoidingProxyFor(List<OrderElement> orderElement);
boolean existsByNameAnotherTransaction(String name);
List<Order> getActiveOrders();
List<CostExpenseSheetDTO> getCostExpenseSheet(List<Order> orders, Date startingDate,
Date endingDate, List<Criterion> criterions);
List<CostExpenseSheetDTO> getCostExpenseSheet(
List<Order> orders, Date startingDate, Date endingDate, List<Criterion> criterions);
/**
* Get {@link Order} where {@link Order#getCustomerReference()} is not NULL and not equals empty {@link String}.
*
* @return {@link List<Order>}
*/
List<Order> getOrdersWithNotEmptyCustomersReferences();
}

View file

@ -172,7 +172,7 @@ public class OrderDAO extends IntegrationEntityDAO<Order> 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<Order> implements IOrderDAO {
* Otherwise, it returns the list of orders identifiers for which the user has read permissions.
*/
private List<Long> 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<Order> implements IOrderDAO {
@Override
public List<Order> 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<Order> 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<Order> 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<Order> implements IOrderDAO {
return filteredList;
}
@Override
public List<Order> getOrdersWithNotEmptyCustomersReferences() {
return getSession()
.createCriteria(Order.class)
.add(Restrictions.isNotNull("customerReference"))
.add(Restrictions.ne("customerReference", ""))
.list();
}
}

View file

@ -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<OrderElement> 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) {

View file

@ -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;
}

View file

@ -29,35 +29,49 @@ import java.util.EnumSet;
/**
* @author Susana Montes Pedreiera <smotnes@wirelessgalicia.com>
* @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
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<OrderStatusEnum> 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);

View file

@ -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 <dpino@igalia.com>
* @author Manuel Rego Casasnovas <mrego@igalia.com>
@ -50,12 +50,12 @@ import org.springframework.stereotype.Repository;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
implements IDayAssignmentDAO {
public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long> implements IDayAssignmentDAO {
private final String SCENARIO = "scenario";
@Override
public void removeDerived(
Collection<? extends DerivedDayAssignment> assignments) {
public void removeDerived(Collection<? extends DerivedDayAssignment> assignments) {
for (DerivedDayAssignment each : assignments) {
getSession().delete(each);
}
@ -63,54 +63,53 @@ public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
@Override
public List<DayAssignment> getAllFor(Scenario scenario) {
List<DayAssignment> result = new ArrayList<DayAssignment>();
List<DayAssignment> 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<DayAssignment> getAllFor(Scenario scenario, LocalDate init,
LocalDate end) {
List<DayAssignment> result = new ArrayList<DayAssignment>();
public List<DayAssignment> getAllFor(Scenario scenario, LocalDate init, LocalDate end) {
List<DayAssignment> 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<DayAssignment> getAllFor(Scenario scenario,
LocalDate startDateInclusive, LocalDate endDateInclusive,
Resource resource) {
List<DayAssignment> result = new ArrayList<DayAssignment>();
result.addAll(getSpecific(scenario, startDateInclusive,
endDateInclusive, resource));
result.addAll(getGeneric(scenario, startDateInclusive,
endDateInclusive, resource));
result.addAll(getDerived(scenario, startDateInclusive,
endDateInclusive, resource));
public List<DayAssignment> getAllFor(
Scenario scenario, LocalDate startDateInclusive, LocalDate endDateInclusive, Resource resource) {
List<DayAssignment> 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<DerivedDayAssignment> 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<DerivedDayAssignment> 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<DayAssignment, Long>
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<DayAssignment, Long>
}
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<GenericDayAssignment> 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<GenericDayAssignment> 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<SpecificDayAssignment> 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<SpecificDayAssignment> 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<DayAssignment, Long>
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<DayAssignment> findByResources(Scenario scenario, List<Resource> 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<DayAssignment> findByResources(List<Resource> 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();
}
}

View file

@ -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 <ogonzalez@igalia.com>
*/
public enum CalculatedValue {
NUMBER_OF_HOURS, END_DATE, RESOURCES_PER_DAY;
NUMBER_OF_HOURS, END_DATE, RESOURCES_PER_DAY
}

View file

@ -74,7 +74,8 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
/**
* Constructor for Hibernate. DO NOT USE!
*/
public GenericResourceAllocation() {}
public GenericResourceAllocation() {
}
public static GenericResourceAllocation create() {
return create(new GenericResourceAllocation());
@ -168,9 +169,8 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
}
public List<GenericDayAssignment> getOrderedAssignmentsFor(Resource resource) {
List<GenericDayAssignment> list = getOrderedAssignmentsFor().get(resource);
return list == null ? Collections.emptyList() : Collections.unmodifiableList(list);
List<GenericDayAssignment> assignments = getOrderedAssignmentsFor().get(resource);
return assignments == null ? Collections.emptyList() : Collections.unmodifiableList(assignments);
}
private Map<Resource, List<GenericDayAssignment>> getOrderedAssignmentsFor() {
@ -186,7 +186,6 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
@Override
public boolean isSelectable(Resource resource, LocalDate day) {
ICriterion compoundCriterion = CriterionCompounder.buildAnd(criterions).getResult();
return compoundCriterion.isSatisfiedBy(resource, day);
}
}
@ -268,7 +267,6 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
ResourceAllocation<GenericDayAssignment> createCopy(Scenario scenario) {
GenericResourceAllocation allocation = create();
allocation.criterions = new HashSet<>(criterions);
return allocation;
}

View file

@ -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;
}

View file

@ -37,58 +37,50 @@ import org.libreplan.business.util.deepcopy.Strategy;
public class CalculatedConsolidation extends Consolidation {
private SortedSet<CalculatedConsolidatedValue> consolidatedValues = new TreeSet<CalculatedConsolidatedValue>(
new ConsolidatedValueComparator());
@AfterCopy
private void instantiateConsolidatedValuesWithComparator() {
SortedSet<CalculatedConsolidatedValue> previous = consolidatedValues;
consolidatedValues = new TreeSet<CalculatedConsolidatedValue>(
new ConsolidatedValueComparator());
consolidatedValues.addAll(previous);
}
private SortedSet<CalculatedConsolidatedValue> 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<CalculatedConsolidatedValue> consolidatedValues) {
return create(new CalculatedConsolidation(task,
indirectAdvanceAssignment,
consolidatedValues));
}
/**
* Constructor for {@link DeepCopy}. DO NOT USE!
*/
public CalculatedConsolidation() {
}
protected CalculatedConsolidation(Task task,
IndirectAdvanceAssignment indirectAdvanceAssignment,
SortedSet<CalculatedConsolidatedValue> 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<CalculatedConsolidatedValue> consolidatedValues) {
this(task, indirectAdvanceAssignment);
this.setConsolidatedValues(consolidatedValues);
}
@AfterCopy
private void instantiateConsolidatedValuesWithComparator() {
SortedSet<CalculatedConsolidatedValue> 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<CalculatedConsolidatedValue> consolidatedValues) {
return create(new CalculatedConsolidation(task, indirectAdvanceAssignment, consolidatedValues));
}
@Override
public SortedSet<ConsolidatedValue> getConsolidatedValues() {
SortedSet<ConsolidatedValue> result = new TreeSet<ConsolidatedValue>(
new ConsolidatedValueComparator());
SortedSet<ConsolidatedValue> 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<CalculatedConsolidatedValue> consolidatedValues) {
public void setConsolidatedValues(SortedSet<CalculatedConsolidatedValue> consolidatedValues) {
this.consolidatedValues = consolidatedValues;
}
public void setIndirectAdvanceAssignment(
IndirectAdvanceAssignment indirectAdvanceAssignment) {
public void setIndirectAdvanceAssignment(IndirectAdvanceAssignment indirectAdvanceAssignment) {
this.indirectAdvanceAssignment = indirectAdvanceAssignment;
}

View file

@ -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 <nacho@igalia.com>
*/
import java.util.ArrayList;
@ -40,39 +39,32 @@ public class CalculateFinishedTasksEstimationDeviationVisitor extends TaskElemen
private List<Double> deviations;
public CalculateFinishedTasksEstimationDeviationVisitor() {
this.deviations = new ArrayList<Double>();
this.deviations = new ArrayList<>();
}
public List<Double> 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);

View file

@ -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 <dpino@igalia.com>
*
*/
public class Gap implements Comparable<Gap> {
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<GapOnQueue> onQueue(LimitingResourceQueue queue,
Collection<? extends Gap> gaps) {
List<GapOnQueue> result = new ArrayList<GapOnQueue>();
for (Gap each : gaps) {
result.add(each.onQueue(queue));
}
return result;
}
public static List<GapOnQueue> 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<Gap> {
this.gap = gap;
}
public static List<GapOnQueue> onQueue(LimitingResourceQueue queue, Collection<? extends Gap> gaps) {
List<GapOnQueue> result = new ArrayList<>();
for (Gap each : gaps) {
result.add(each.onQueue(queue));
}
return result;
}
public static List<GapOnQueue> 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<Gap> {
return gap;
}
public List<GapOnQueue> splitIntoGapsSatisfyingCriteria(
Set<Criterion> criteria) {
return GapOnQueue.onQueue(originQueue, gap
.splitIntoGapsSatisfyingCriteria(originQueue.getResource(),
criteria));
public List<GapOnQueue> splitIntoGapsSatisfyingCriteria(Set<Criterion> 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<Gap> {
}
/**
* @author Diego Pino García <dpino@igalia.com>
* Stores a {@link GapOnQueue} plus its adjacent {@link LimitingResourceQueueElement}.
*
* Stores a {@link GapOnQueue} plus its adjacent
* {@link LimitingResourceQueueElement}
* @author Diego Pino García <dpino@igalia.com>
*/
public static class GapOnQueueWithQueueElement {
@ -120,16 +125,15 @@ public class Gap implements Comparable<Gap> {
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<Gap> {
}
/**
* 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<Gap> {
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<PartialDay> days = start.daysUntil(end);
EffortDuration result = zero();
@ -228,14 +206,12 @@ public class Gap implements Comparable<Gap> {
}
public List<Integer> 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<Integer> result = new ArrayList<Integer>();
List<Integer> 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<Gap> {
endDate = DateAndHour.TEN_YEARS_FROM(realStart);
}
Iterator<PartialDay> 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<Gap> {
}
/**
* 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<Gap> {
return endTime == null || endsAfter.compareTo(endTime.getDate()) <= 0;
}
@Override
public String toString() {
String result = "";
@ -322,10 +289,13 @@ public class Gap implements Comparable<Gap> {
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<Gap> {
}
public boolean isBefore(Gap gap) {
return (compareTo(gap) < 0);
return compareTo(gap) < 0;
}
public List<Gap> splitIntoGapsSatisfyingCriteria(Resource resource,
Set<Criterion> criteria) {
return splitIntoGapsSatisfyingCriteria(resource, criteria,
getStartTime(), getEndTime());
public List<Gap> splitIntoGapsSatisfyingCriteria(Resource resource, Set<Criterion> criteria) {
return splitIntoGapsSatisfyingCriteria(resource, criteria, getStartTime(), getEndTime());
}
/**
* Returns a set of {@link Gap} composed by those gaps which satisfy
* <em>criteria</em> within the period: <em>gapStartTime</em> till
* <em>gapEndTime</em>
* Returns a set of {@link Gap} composed by those gaps which satisfy <em>criteria</em> within the period:
* <em>gapStartTime</em> till <em>gapEndTime</em>.
*
* @param resource
* @param criteria
* criteria to be satisfied by resource
@ -353,42 +321,45 @@ public class Gap implements Comparable<Gap> {
* start time of gap
* @param gapEndTime
* end time of gap
* @return
* @return {@link List<Gap>}
*/
private static List<Gap> splitIntoGapsSatisfyingCriteria(Resource resource,
Set<Criterion> criteria, DateAndHour gapStartTime,
DateAndHour gapEndTime) {
AvailabilityTimeLine criterionsAvailability = AvailabilityCalculator
.getCriterionsAvailabilityFor(criteria, resource);
private static List<Gap> splitIntoGapsSatisfyingCriteria(
Resource resource, Set<Criterion> 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<Interval> validPeriods = criterionsAvailability.getValidPeriods();
List<Gap> result = new ArrayList<Gap>();
List<Gap> 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());

View file

@ -33,6 +33,7 @@ import org.libreplan.business.scenarios.entities.Scenario;
* Contract for {@link ScenarioDAO}.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
public interface IScenarioDAO extends IGenericDAO<Scenario, Long> {
@ -44,6 +45,14 @@ public interface IScenarioDAO extends IGenericDAO<Scenario, Long> {
List<Scenario> getAll();
/**
* Gets all {@link Scenario}s except chosen.
*
* @param scenario Selected {@link Scenario} that you want to exclude
* @return {@link List<Scenario>}
*/
List<Scenario> getAllExcept(Scenario scenario);
boolean thereIsOtherWithSameName(Scenario scenario);
List<Scenario> findByPredecessor(Scenario scenario);
@ -51,7 +60,6 @@ public interface IScenarioDAO extends IGenericDAO<Scenario, Long> {
List<Scenario> getDerivedScenarios(Scenario scenario);
void updateDerivedScenariosWithNewVersion(
OrderVersion previousOrderVersion, Order order,
Scenario currentScenario, OrderVersion newOrderVersion);
OrderVersion previousOrderVersion, Order order, Scenario currentScenario, OrderVersion newOrderVersion);
}

View file

@ -45,6 +45,7 @@ import org.springframework.transaction.annotation.Transactional;
* DAO implementation for {@link Scenario}.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
@ -118,6 +119,14 @@ public class ScenarioDAO extends GenericDAOHibernate<Scenario, Long> implements
return list(Scenario.class);
}
@Override
public List<Scenario> 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<Scenario, Long> implements
@Override
public List<Scenario> 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

View file

@ -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 <nacho@igalia.com>
*/
@ -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

View file

@ -28,11 +28,9 @@ import java.lang.annotation.Target;
/**
* @author Óscar González Fernández <ogonzalez@igalia.com>
*
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AfterCopy {
}

View file

@ -47,18 +47,22 @@ import org.libreplan.business.workingday.EffortDuration;
/**
* @author Óscar González Fernández <ogonzalez@igalia.com>
*
*/
public class DeepCopy {
private static Set<Class<?>> inmmutableTypes = new HashSet<Class<?>>(Arrays
.<Class<?>> 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<Class<?>> inmmutableTypes = new HashSet<>(Arrays.<Class<?>>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<ICustomCopy> DEFAULT_CUSTOM_COPIERS =
Arrays.asList(new DateCopy(), new SetCopy(), new MapCopy(), new ListCopy());
private Map<ByIdentity, Object> 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<Object> 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<Object>) result);
}
private void copy(DeepCopy deepCopy, Object origin, Strategy strategy,
Collection<Object> destination) {
private void copy(DeepCopy deepCopy, Object origin, Strategy strategy, Collection<Object> 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<Object> 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<Object>();
}
return new HashSet<Object>();
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<Object, Object>();
return new HashMap<>();
}
}.instantiate(klass);
}
@Override
public void copyDataToResult(DeepCopy deepCopy, Object origin,
Strategy strategy, Object result) {
doCopy(deepCopy, (Map<?, ?>) ((Map<?, ?>) origin), strategy, ((Map<Object, Object>) result));
public void copyDataToResult(DeepCopy deepCopy, Object origin, Strategy strategy, Object result) {
doCopy(deepCopy, (Map<?, ?>) origin, strategy, ((Map<Object, Object>) result));
}
private void doCopy(DeepCopy deepCopy, Map<?, ?> origin,
Strategy strategy, Map<Object, Object> resultMap) {
private void doCopy(DeepCopy deepCopy, Map<?, ?> origin, Strategy strategy, Map<Object, Object> 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<Object>();
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> T instantiate(Class<?> type) {
if (!isVetoed(type)) {
try {
Constructor<? extends Object> constructor = type
.getConstructor();
Constructor<? extends Object> 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<ICustomCopy> DEFAULT_CUSTOM_COPIERS = Arrays
.<ICustomCopy> asList(new DateCopy(), new SetCopy(), new MapCopy(),
new ListCopy());
private Map<ByIdentity, Object> alreadyCopiedObjects = new HashMap<ByIdentity, Object>();
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> 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<Field> getAllFieldsFor(Object source) {
List<Field> result = new ArrayList<Field>();
List<Field> result = new ArrayList<>();
Class<? extends Object> 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<Method> getAfterCopyHooks(Class<?> klass) {
Class<?> current = klass;
List<Method> result = new ArrayList<Method>();
List<Method> result = new ArrayList<>();
while (current != null) {
result.addAll(getAfterCopyDeclaredAt(current));
current = current.getSuperclass();
@ -470,7 +455,7 @@ public class DeepCopy {
}
private List<Method> getAfterCopyDeclaredAt(Class<?> klass) {
List<Method> result = new ArrayList<Method>();
List<Method> result = new ArrayList<>();
for (Method each : klass.getDeclaredMethods()) {
if (isAfterCopyHook(each)) {
result.add(each);

View file

@ -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;

View file

@ -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}.
* <br />

View file

@ -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

View file

@ -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 <ogonzalez@igalia.com>
*
*/
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<Class<?>> immutableTypes = Arrays.<Class<?>> asList(
Iterable<Class<?>> 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<Object> originalSet = new HashSet<Object>(asList("test",
2, 3, new Date()));
HashSet<Object> 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<Object> originalSet = new LinkedHashSet<Object>(asList("test", 2,
3, new Date()));
Set<Object> 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<Object> innerSet = new HashSet<Object>(asList("bla", 3));
HashSet<Object> originalSet = new HashSet<Object>(asList("test", 2, 3,
new Date(), innerSet));
HashSet<Object> innerSet = new HashSet<>(asList("bla", 3));
HashSet<Object> 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<Object, Object> originalMap = new HashMap<Object, Object>();
HashMap<Object, Object> 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<Object, Object> mapProperty = new LinkedHashMap<Object, Object>();
LinkedHashMap<Object, Object> 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<Object> originalList = new ArrayList<Object>();
ArrayList<Object> 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<Object> originalList = new LinkedList<Object>();
LinkedList<Object> 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<String> originalList = Arrays.asList("bla");
List<String> 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<Object> originalSet = new HashSet<Object>();
HashSet<Object> 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<Object, Object> originalMap = new HashMap<Object, Object>();
Map<Object, Object> 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<Object, Object> sharedKeysMapProperty = copy
.getSharedKeysMapProperty();
assertSame(originalKey, sharedKeysMapProperty.keySet().iterator()
.next());
assertNotSame(originalValue, sharedKeysMapProperty.values().iterator()
.next());
Map<Object, Object> sharedKeysMapProperty = copy.getSharedKeysMapProperty();
assertSame(originalKey, sharedKeysMapProperty.keySet().iterator().next());
assertNotSame(originalValue, sharedKeysMapProperty.values().iterator().next());
}
@Test
public void sharedValueElementsKeepTheSameReferencesForTheValues() {
EntityA entityA = new EntityA();
Map<Object, Object> originalMap = new HashMap<Object, Object>();
Map<Object, Object> 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<Object, Object> copiedMap = copy
.getSharedValuesMapProperty();
assertNotSame(originalKey, copiedMap.keySet().iterator()
.next());
assertSame(originalValue, copiedMap.values().iterator()
.next());
Map<Object, Object> copiedMap = copy.getSharedValuesMapProperty();
assertNotSame(originalKey, copiedMap.keySet().iterator().next());
assertSame(originalValue, copiedMap.values().iterator().next());
}
@Test
public void aSharedCollectionElementsMapKeepTheSameReferencesForTheKeysAndTheValues() {
EntityA entityA = new EntityA();
Map<Object, Object> originalMap = new HashMap<Object, Object>();
Map<Object, Object> 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<Object, Object> copiedMap = copy
.getSharedCollectionElementsMapProperty();
assertSame(originalKey, copiedMap.keySet().iterator()
.next());
assertSame(originalValue, copiedMap.values().iterator()
.next());
Map<Object, Object> 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<Object> originalSet = new HashSet<Object>();
HashSet<Object> 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<Object>());
entityA.setSet2(new HashSet<Object>());
entityA.setSet1(new HashSet<>());
entityA.setSet2(new HashSet<>());
EntityA copied = deepCopy.copy(entityA);
assertNotSame(copied.getSet1(), copied.getSet2());
}

View file

@ -30,7 +30,6 @@ import java.util.Set;
/**
* @author Óscar González Fernández <ogonzalez@igalia.com>
*
*/
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<Object> setProperty = new HashSet<Object>();
private Set<Object> 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<Object> setProperty;
private Map<Object, Object> mapProperty = new HashMap<Object, Object>();
private Map<Object, Object> mapProperty = new HashMap<>();
private List<Object> listProperty;
@ -314,9 +311,6 @@ public class EntityExamples {
}
public static class SubClassExample extends SuperclassExample {
private int intProperty;
}
}

View file

@ -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 <m.ghiorghis@antoniusziekenhuis.nl>
*/
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<String> getAllJiraLabels() throws ConnectorException;
/**
* Get all jira issues based on the specified <code>label</code> parameter
* from jira RESTFul web service
* Get all JIRA issues based on the specified <code>label</code> 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 <code>issues</code> and check if an
* {@link OrderElement} of the given <code>order</code> 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 <code>order</code> and start synchronization of
* {@link DirectAdvanceAssignment} and {@link AdvanceMeasurement}
* Loops through all JIRA <code>issues</code> and check if an {@link OrderElement} of the given <code>order</code> 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 <code>order</code> 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<IssueDTO> 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}
*

View file

@ -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. <br />
*
* Class that represents no persistent imported tasks.
* <br />
* At these moment it only represent the tasks that can have any subtasks.
*
* @author Alba Carro Pérez <alba.carro@gmail.com>
@ -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;
}
}

View file

@ -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<ConnectorProperty> getEmailConnectorProperties() {
Connector connector = connectorDAO.findUniqueByName("E-mail");
return connector.getProperties();
return connectorDAO.findUniqueByName("E-mail").getProperties();
}
public boolean isConnectionActivated() {
List<ConnectorProperty> 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;
}

View file

@ -49,7 +49,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 <vova@libreplan-enterprise.com> on 21.01.2016.
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
@Component
@ -87,9 +87,11 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
List<EmailNotification> 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));
}
}
}
}
}
@ -122,11 +124,10 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
private void sendEmailNotificationAboutTaskShouldFinish(TaskElement item){
List<ResourceAllocation<?>> list = new ArrayList<>();
list.addAll(item.getAllResourceAllocations());
List<ResourceAllocation<?>> resourceAllocations = new ArrayList<>(item.getAllResourceAllocations());
List<Resource> resources = new ArrayList<>();
for (ResourceAllocation<?> allocation : list)
for (ResourceAllocation<?> allocation : resourceAllocations)
resources.add(allocation.getAssociatedResources().get(0));
for (Resource resourceItem : resources){

View file

@ -49,7 +49,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 <vova@libreplan-enterprise.com> on 20.01.2016.
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
@Component
@ -89,8 +89,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);
}
}
}
}
@ -122,11 +123,10 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob {
}
private void sendEmailNotificationAboutTaskShouldStart(TaskElement item) {
List<ResourceAllocation<?>> list = new ArrayList<>();
list.addAll(item.getAllResourceAllocations());
List<ResourceAllocation<?>> resourceAllocations = new ArrayList<>(item.getAllResourceAllocations());
List<Resource> resources = new ArrayList<>();
for (ResourceAllocation<?> allocation : list)
for (ResourceAllocation<?> allocation : resourceAllocations)
resources.add(allocation.getAssociatedResources().get(0));
for (Resource resourceItem : resources) {

View file

@ -42,6 +42,9 @@ public class I18nHelper {
private static HashMap<Locale, I18n> 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

View file

@ -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) {
}
}
}

View file

@ -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();

View file

@ -91,11 +91,7 @@ public class TemplateController extends GenericForwardComposer {
}
public List<Scenario> 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:");
}
}

View file

@ -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<String> 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<Comboitem> 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<Comboitem> 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<Boolean> 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<Boolean> 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<String> 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} <code>###.##</code> plus currency
* symbol
* @return Format for a {@link Decimalbox} <code>###.##</code> 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 <code>time</code> using the {@link DateFormat#SHORT}
* format and showing only the time.
* Format specific <code>time</code> 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) {
}
}
}

View file

@ -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
}
}
}

View file

@ -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 <dpino@igalia.com>
*

View file

@ -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 <jaragunde@igalia.com>
*/
@ -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<Date>() {
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<Date>() {
@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<Date>() {
@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<Date>() {
@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<Date>() {
@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<Date>() {
@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<Date>() {
@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<Date>() {
@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() {

View file

@ -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 <ltilve@igalia.com>
*
* 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

View file

@ -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 <vova@libreplan-enterprise.com>
*/
@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<Order> currentList, int index) {
private void processList(List<Order> 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();
}

View file

@ -142,8 +142,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
private Scenario master;
private Map<LimitingResourceQueueElement, HashSet<LimitingResourceQueueDependency>> toBeSavedDependencies =
new HashMap<>();
private Map<LimitingResourceQueueElement, HashSet<LimitingResourceQueueDependency>> 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<LimitingResourceQueueElement> 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<Criterion> 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<? extends LimitingResourceQueueElement>}
*/
private Collection<? extends LimitingResourceQueueElement> rescheduleAffectedElementsToSatisfyDependencies(
AllocationSpec allocation, List<LimitingResourceQueueElement> 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 <code>null</code> if no suitable gap found; the allocation found
* otherwise
* @return <code>null</code> 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<GapOnQueue> 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<LimitingResourceQueueElement> appropriativeAllocation(
LimitingResourceQueueElement _element,
LimitingResourceQueue _queue,
LimitingResourceQueueElement limitingResourceQueueElement,
LimitingResourceQueue limitingResourceQueue,
DateAndHour allocationTime) {
Set<LimitingResourceQueueElement> 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);

View file

@ -108,14 +108,9 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
private Window editTaskWindow;
private final LimitingResourceQueueElementsRenderer limitingResourceQueueElementsRenderer =
new LimitingResourceQueueElementsRenderer();
new LimitingResourceQueueElementsRenderer();
public LimitingResourcesController()
{}
public void add(IToolbarCommand... commands) {
Validate.noNullElements(commands);
this.commands.addAll(Arrays.asList(commands));
public LimitingResourcesController() {
}
@Override
@ -123,6 +118,11 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
super.doAfterCompose(comp);
}
public void add(IToolbarCommand... commands) {
Validate.noNullElements(commands);
this.commands.addAll(Arrays.asList(commands));
}
public void reload() {
transactionService.runOnReadOnlyTransaction(new IOnTransaction<Void>() {
@ -133,7 +133,7 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
}
private void reloadInTransaction() {
// FIXME: Temporary fix.
// FIXME: Temporary fix
// It seems the page was already rendered, so clear it all as it's going to be rendered again
self.getChildren().clear();
@ -196,12 +196,14 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
}
private TimeTracker buildTimeTracker() {
return timeTracker = new TimeTracker(
timeTracker = new TimeTracker(
limitingResourceQueueModel.getViewInterval(),
ZoomLevel.DETAIL_THREE,
SeveralModifiers.create(),
SeveralModifiers.create(BankHolidaysMarker.create(getDefaultCalendar())),
self);
return timeTracker;
}
private BaseCalendar getDefaultCalendar() {
@ -222,7 +224,6 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
* @return {@link List<LimitingResourceQueueElementDTO>}
*/
public List<LimitingResourceQueueElementDTO> getUnassignedLimitingResourceQueueElements() {
// TODO check it
return limitingResourceQueueModel
.getUnassignedLimitingResourceQueueElements()
.stream()
@ -528,7 +529,6 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
public boolean moveTask(LimitingResourceQueueElement element) {
showManualAllocationWindow(element);
return getManualAllocationWindowStatus() == Messagebox.OK;
}
@ -560,9 +560,7 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
@SuppressWarnings("unchecked")
private Checkbox getAutoQueueing(Row row) {
List<org.zkoss.zk.ui.Component> children = row.getChildren();
return (Checkbox) children.get(0);
return (Checkbox) row.getChildren().get(0);
}
public void assignAllSelectedElements() {

View file

@ -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;
}

View file

@ -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

View file

@ -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() {

View file

@ -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<Object> plusAggregatingRow(List<AllocationRow> currentRows) {
List<Object> result = new ArrayList<>(currentRows);
result.add(null);
return result;
}

View file

@ -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<IndirectAdvanceAssignment> 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<NonCalculatedConsolidatedValue> 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<CalculatedConsolidatedValue> 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<AdvanceMeasurement> 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<AdvanceConsolidationDTO> consolidationDTOs) {
@ -501,22 +487,19 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel {
}
public List<AdvanceConsolidationDTO> 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

View file

@ -89,6 +89,8 @@ import org.zkoss.zul.Tabpanel;
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class TaskPropertiesController extends GenericForwardComposer<Component> {
private final String WARNING = "Warning";
private IScenarioManager scenarioManager;
private TaskEditFormComposer taskEditFormComposer = new TaskEditFormComposer();
@ -140,9 +142,17 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
private List<Resource> 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<Component>
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<Component>
* Enum for showing type of resource assignation option list.
*
* @author Diego Pino Garcia <dpino@igalia.com>
*
*/
enum ResourceAllocationTypeEnum {
NON_LIMITING_RESOURCES(_("Normal resource assignment")),
@ -542,7 +551,8 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
*
* @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<Component>
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<Component>
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<Component>
// 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<Component>
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<Component>
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<Component>
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<Component>
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);

View file

@ -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<QualityForm> {
private final String CANNOT_BE_EMPTY = "cannot be empty";
private IQualityFormModel qualityFormModel;
private Grid gridQualityForms;
@ -64,7 +65,9 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
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<QualityForm> {
}
/**
* Return all {@link QualityForm}
* @return
* Return all {@link QualityForm}.
*
* @return {@link List<QualityForm>}
*/
public List<QualityForm> 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<QualityFormItem>}
*/
public List<QualityFormItem> 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<QualityForm> {
}
/**
* 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<QualityForm> {
}
/**
* 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<QualityForm> {
}
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<QualityForm> {
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<QualityForm> {
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<QualityForm> {
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<QualityForm> {
}
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<QualityForm> {
}
/**
* 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<QualityForm> {
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<QualityForm> {
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<QualityForm> {
qualityFormModel.checkHasTasks(qualityForm);
return false;
} catch (ValidationException e) {
showCannotDeleteQualityFormDialog(e.getInvalidValue().getMessage()
);
showCannotDeleteQualityFormDialog(e.getInvalidValue().getMessage());
}
return true;
}

View file

@ -15,6 +15,34 @@ import org.zkoss.ganttz.util.Interval;
public class ResourceLoadDisplayData {
private final List<LoadTimeLine> timeLines;
private final Interval viewInterval;
private final Paginator<? extends BaseEntity> paginator;
private final Callable<List<Resource>> resourcesConsidered;
private final Callable<List<DayAssignment>> assignmentsConsidered;
public ResourceLoadDisplayData(
List<LoadTimeLine> timeLines,
Paginator<? extends BaseEntity> paginator,
Callable<List<Resource>> resourcesConsidered,
Callable<List<DayAssignment>> 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 <T> Callable<T> cached(Callable<T> callable) {
return new CachedCallable<>(callable);
}
@ -28,6 +56,7 @@ public class ResourceLoadDisplayData {
}
private static class CachedCallable<T> implements Callable<T> {
private final Callable<T> 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<LoadTimeLine> timeLines;
private final Interval viewInterval;
private final Paginator<? extends BaseEntity> paginator;
private final Callable<List<Resource>> resourcesConsidered;
private final Callable<List<DayAssignment>> assignmentsConsidered;
private final LocalDate filterStart;
private final LocalDate filterEnd;
public ResourceLoadDisplayData(
List<LoadTimeLine> timeLines,
LocalDate filterStart,
LocalDate filterEnd,
Paginator<? extends BaseEntity> paginator,
Callable<List<Resource>> resourcesConsidered,
Callable<List<DayAssignment>> 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<LoadTimeLine> 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;
}
}

View file

@ -133,8 +133,6 @@ public class ResourceLoadModel implements IResourceLoadModel {
return new ResourceLoadDisplayData(
loadTimeLines,
parameters.getInitDateFilter(),
parameters.getEndDateFilter(),
allocationsFinder.getPaginator(),
allocationsFinder.lazilyGetResourcesIncluded(),
allocationsFinder.lazilyGetAssignmentsShown());

View file

@ -36,40 +36,38 @@ import org.libreplan.web.planner.allocation.INewAllocationsAdder;
import org.zkoss.zk.ui.Component;
/**
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
* Controller for searching for {@link Resource}.
*
* Controller for searching for {@link Resource}
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
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<? extends Resource> searchResources(List<Criterion> 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<Criterion> 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<Criterion>}
*/
public List<Criterion> getSelectedCriterions() {
List<Criterion> criteria = new ArrayList<Criterion>();
List<Criterion> 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<FilterPair> getSelectedItems() {
return ((List<FilterPair>) bbMultipleSearch
.getSelectedElements());
return ((List<FilterPair>) 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<Resource> getSelectedResources() {
List<Resource> resources = new ArrayList<Resource>();
List<Resource> resources = new ArrayList<>();
for (FilterPair pair : getSelectedItems()) {
if (pair.getType().equals(ResourceAllocationFilterEnum.Resource)) {
resources.add((Resource) pair.getValue());

View file

@ -55,7 +55,6 @@ public final class SecurityUtils {
public static boolean isGatheredStatsAlreadySent = false;
private SecurityUtils() {
}
public static boolean isUserInRole(UserRole role) {

View file

@ -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<SubcontractedTaskData> getSubcontractedTasks() {

View file

@ -34,7 +34,6 @@ import org.zkoss.zul.Treeitem;
/**
* Macro component for order elements tree and similar pages.
* <br />
*
* @author Óscar González Fernández <ogonzalez@igalia.com>
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
*/
@ -44,27 +43,21 @@ public abstract class TreeComponent extends HtmlMacroComponent {
protected Column codeColumn = new Column(_("Code"), "code") {
@Override
public <T extends ITreeNode<T>> void doCell(
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
public <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
renderer.addCodeCell(currentElement);
}
};
protected final Column nameAndDescriptionColumn = new Column(_("Name"), "name") {
@Override
public <T extends ITreeNode<T>> void doCell(
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
public <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
renderer.addDescriptionCell(currentElement);
}
};
protected final Column operationsColumn = new Column(_("Op."), "operations", _("Operations")) {
@Override
public <T extends ITreeNode<T>> void doCell(
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
public <T extends ITreeNode<T>> void doCell(TreeController<T>.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 <T extends ITreeNode<T>> void doCell(
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
public <T extends ITreeNode<T>> void doCell(TreeController<T>.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 <T extends ITreeNode<T>> void doCell(
TreeController<T>.Renderer renderer, Treeitem item, T currentElement);
public abstract <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement);
}
public abstract List<Column> getColumns();

View file

@ -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 <jaragunde@igalia.com>
* @author Diego Pino García <dpino@igalia.com>
@ -57,8 +57,10 @@ public class ProfileCRUDController extends BaseCRUDController<Profile> {
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<Profile> {
/**
* Appends the existing UserRoles to the Combobox passed.
*
* @param combo
*/
private void appendAllUserRolesExceptRoleBoundUser(Combobox combo) {
@ -82,7 +85,7 @@ public class ProfileCRUDController extends BaseCRUDController<Profile> {
}
}
protected void save() throws ValidationException{
protected void save() throws ValidationException {
profileModel.confirmSave();
}
@ -96,8 +99,8 @@ public class ProfileCRUDController extends BaseCRUDController<Profile> {
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<Profile> {
profileModel.checkHasUsers(profile);
return false;
} catch (ValidationException e) {
showCannotDeleteProfileDialog(e.getInvalidValue().getMessage()
);
showCannotDeleteProfileDialog(e.getInvalidValue().getMessage());
}
return true;

View file

@ -85,12 +85,9 @@ public class UserCRUDController extends BaseCRUDController<User> 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<User> 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<User> 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<User> 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<User> 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<User> 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<User> 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 <b>unencrypted</b> 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<User> 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<User> 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<User> 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<User> 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<User> 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<User> 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<User> 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<User> implements IUse
private boolean isUserDefaultAdmin() {
User user = userModel.getUser();
return user != null && isDefaultAdmin(user);
}
@ -426,18 +424,12 @@ public class UserCRUDController extends BaseCRUDController<User> 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<User> 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<User> 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") + " )";
}
}

View file

@ -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;
}

View file

@ -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<Void>() {
@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;
}

View file

@ -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");

View file

@ -40,35 +40,23 @@ public final class LabelReferenceConverter {
}
public final static Set<LabelReferenceDTO> toDTO(Set<Label> labels) {
Set<LabelReferenceDTO> labelDTOs = new HashSet<LabelReferenceDTO>();
Set<LabelReferenceDTO> labelDTOs = new HashSet<>();
for (Label label : labels) {
labelDTOs.add(toDTO(label));
}
return labelDTOs;
}
public final static LabelReferenceDTO toDTO(Label label) {
public static final LabelReferenceDTO toDTO(Label label) {
return new LabelReferenceDTO(label.getCode());
}
public static Set<Label> toEntity(Set<LabelReferenceDTO> labels)
throws InstanceNotFoundException {
Set<Label> result = new HashSet<Label>();
public static Set<Label> toEntity(Set<LabelReferenceDTO> labels) throws InstanceNotFoundException {
Set<Label> result = new HashSet<>();
for (LabelReferenceDTO labelReferenceDTO : labels) {
result.add(toEntity(labelReferenceDTO));
result.add(Registry.getLabelDAO().findByCode(labelReferenceDTO.code));
}
return result;
}
public final static Label toEntity(LabelReferenceDTO labelReferenceDTO)
throws InstanceNotFoundException {
// FIXME review if this check could be moved to findByCode at
// IntegrationEntityDAO
if (labelReferenceDTO.code == null) {
throw new InstanceNotFoundException(null, Label.class.getName());
}
return Registry.getLabelDAO().findByCode(labelReferenceDTO.code);
}
}

View file

@ -87,116 +87,116 @@ public final class OrderElementConverter {
private OrderElementConverter() {
}
public final static OrderElementDTO toDTO(OrderElement orderElement,
ConfigurationOrderElementConverter configuration) {
public static final OrderElementDTO toDTO(OrderElement orderElement, ConfigurationOrderElementConverter configuration) {
String name = orderElement.getName();
String code = orderElement.getCode();
XMLGregorianCalendar initDate = DateConverter
.toXMLGregorianCalendar(orderElement.getInitDate());
XMLGregorianCalendar deadline = DateConverter
.toXMLGregorianCalendar(orderElement.getDeadline());
XMLGregorianCalendar initDate = DateConverter.toXMLGregorianCalendar(orderElement.getInitDate());
XMLGregorianCalendar deadline = DateConverter.toXMLGregorianCalendar(orderElement.getDeadline());
String description = orderElement.getDescription();
Set<LabelReferenceDTO> labels = new HashSet<LabelReferenceDTO>();
Set<LabelReferenceDTO> labels = new HashSet<>();
if (configuration.isLabels()) {
for (Label label : orderElement.getLabels()) {
labels.add(LabelReferenceConverter.toDTO(label));
}
}
Set<MaterialAssignmentDTO> materialAssignments = new HashSet<MaterialAssignmentDTO>();
Set<MaterialAssignmentDTO> materialAssignments = new HashSet<>();
if (configuration.isMaterialAssignments()) {
for (MaterialAssignment materialAssignment : orderElement
.getMaterialAssignments()) {
for (MaterialAssignment materialAssignment : orderElement.getMaterialAssignments()) {
materialAssignments.add(toDTO(materialAssignment));
}
}
Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<AdvanceMeasurementDTO>();
Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<>();
if (configuration.isAdvanceMeasurements()) {
advanceMeasurements = toDTO(orderElement
.getReportGlobalAdvanceAssignment());
advanceMeasurements = toDTO(orderElement.getReportGlobalAdvanceAssignment());
}
Set<CriterionRequirementDTO> criterionRequirements = new HashSet<CriterionRequirementDTO>();
Set<CriterionRequirementDTO> criterionRequirements = new HashSet<>();
if (configuration.isCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : orderElement
.getCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : orderElement.getCriterionRequirements()) {
criterionRequirements.add(toDTO(criterionRequirement));
}
}
if (orderElement instanceof OrderLine) {
Set<HoursGroupDTO> hoursGroups = new HashSet<HoursGroupDTO>();
Set<HoursGroupDTO> hoursGroups = new HashSet<>();
if (configuration.isHoursGroups()) {
for (HoursGroup hoursGroup : ((OrderLine) orderElement)
.getHoursGroups()) {
for (HoursGroup hoursGroup : orderElement.getHoursGroups()) {
hoursGroups.add(toDTO(hoursGroup, configuration));
}
}
return new OrderLineDTO(name, code, initDate, deadline,
description, labels, materialAssignments,
advanceMeasurements, criterionRequirements, hoursGroups);
return new OrderLineDTO(
name, code, initDate,
deadline, description, labels,
materialAssignments, advanceMeasurements, criterionRequirements,
hoursGroups);
} else { // orderElement instanceof OrderLineGroup
List<OrderElementDTO> children = new ArrayList<OrderElementDTO>();
List<OrderElementDTO> children = new ArrayList<>();
for (OrderElement element : orderElement.getChildren()) {
children.add(toDTO(element, configuration));
}
if (orderElement instanceof Order) {
Boolean dependenciesConstraintsHavePriority = ((Order) orderElement)
.getDependenciesConstraintsHavePriority();
Boolean dependenciesConstraintsHavePriority =
((Order) orderElement).getDependenciesConstraintsHavePriority();
BaseCalendar calendar = ((Order) orderElement).getCalendar();
String calendarName = null;
if (calendar != null) {
calendarName = calendar.getName();
}
return new OrderDTO(name, code, initDate, deadline,
description, labels, materialAssignments,
advanceMeasurements, criterionRequirements, children,
dependenciesConstraintsHavePriority, calendarName);
return new OrderDTO(
name, code, initDate, deadline,
description, labels, materialAssignments, advanceMeasurements,
criterionRequirements, children, dependenciesConstraintsHavePriority, calendarName);
} else { // orderElement instanceof OrderLineGroup
return new OrderLineGroupDTO(name, code, initDate, deadline,
description, labels, materialAssignments,
advanceMeasurements, criterionRequirements, children);
return new OrderLineGroupDTO(
name, code,
initDate, deadline,
description, labels,
materialAssignments, advanceMeasurements,
criterionRequirements, children);
}
}
}
public static CriterionRequirementDTO toDTO(
CriterionRequirement criterionRequirement) {
public static CriterionRequirementDTO toDTO(CriterionRequirement criterionRequirement) {
String name = criterionRequirement.getCriterion().getName();
String type = criterionRequirement.getCriterion().getType().getName();
if (criterionRequirement instanceof IndirectCriterionRequirement) {
boolean isValid = ((IndirectCriterionRequirement) criterionRequirement)
.isValid();
boolean isValid = criterionRequirement.isValid();
return new IndirectCriterionRequirementDTO(name, type, isValid);
} else { // criterionRequirement instanceof DirectCriterionRequirement
return new DirectCriterionRequirementDTO(name, type);
}
}
public final static Set<AdvanceMeasurementDTO> toDTO(
DirectAdvanceAssignment advanceAssignment) {
Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<AdvanceMeasurementDTO>();
public static final Set<AdvanceMeasurementDTO> toDTO(DirectAdvanceAssignment advanceAssignment) {
Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<>();
if (advanceAssignment != null) {
BigDecimal maxValue = advanceAssignment.getMaxValue();
for (AdvanceMeasurement advanceMeasurement : advanceAssignment
.getAdvanceMeasurements()) {
advanceMeasurements.add(toDTO(maxValue, advanceAssignment
.getAdvanceType().getPercentage(), advanceMeasurement));
for (AdvanceMeasurement advanceMeasurement : advanceAssignment.getAdvanceMeasurements()) {
advanceMeasurements.add(
toDTO(maxValue, advanceAssignment.getAdvanceType().getPercentage(), advanceMeasurement));
}
}
return advanceMeasurements;
}
public final static AdvanceMeasurementDTO toDTO(BigDecimal maxValue,
boolean isPercentage, AdvanceMeasurement advanceMeasurement) {
public static final AdvanceMeasurementDTO toDTO(
BigDecimal maxValue, boolean isPercentage, AdvanceMeasurement advanceMeasurement) {
BigDecimal value;
if (isPercentage) {
value = advanceMeasurement.getValue();
@ -204,59 +204,54 @@ public final class OrderElementConverter {
value = advanceMeasurement.getValue().divide(maxValue,
RoundingMode.DOWN);
}
XMLGregorianCalendar date = DateConverter
.toXMLGregorianCalendar(advanceMeasurement.getDate());
return new AdvanceMeasurementDTO(date, value);
return new AdvanceMeasurementDTO(DateConverter.toXMLGregorianCalendar(advanceMeasurement.getDate()), value);
}
public final static MaterialAssignmentDTO toDTO(
MaterialAssignment materialAssignment) {
public final static MaterialAssignmentDTO toDTO(MaterialAssignment materialAssignment) {
XMLGregorianCalendar estimatedAvailability = DateConverter
.toXMLGregorianCalendar(materialAssignment
.getEstimatedAvailability());
XMLGregorianCalendar estimatedAvailability =
DateConverter.toXMLGregorianCalendar(materialAssignment.getEstimatedAvailability());
return new MaterialAssignmentDTO(materialAssignment.getMaterial()
.getCode(), materialAssignment.getUnits(), materialAssignment
.getUnitPrice(), estimatedAvailability);
return new MaterialAssignmentDTO(
materialAssignment.getMaterial().getCode(),
materialAssignment.getUnits(),
materialAssignment.getUnitPrice(),
estimatedAvailability);
}
public final static HoursGroupDTO toDTO(HoursGroup hoursGroup,
ConfigurationOrderElementConverter configuration) {
ResourceEnumDTO resourceType = ResourceEnumConverter.toDTO(hoursGroup
.getResourceType());
public final static HoursGroupDTO toDTO(HoursGroup hoursGroup, ConfigurationOrderElementConverter configuration) {
ResourceEnumDTO resourceType = ResourceEnumConverter.toDTO(hoursGroup.getResourceType());
Set<CriterionRequirementDTO> criterionRequirements = new HashSet<CriterionRequirementDTO>();
Set<CriterionRequirementDTO> criterionRequirements = new HashSet<>();
if (configuration.isCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : hoursGroup
.getCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : hoursGroup.getCriterionRequirements()) {
criterionRequirements.add(toDTO(criterionRequirement));
}
}
return new HoursGroupDTO(hoursGroup.getCode(), resourceType, hoursGroup
.getWorkingHours(), criterionRequirements);
return new HoursGroupDTO(hoursGroup.getCode(), resourceType, hoursGroup.getWorkingHours(), criterionRequirements);
}
public final static OrderElement toEntity(OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
public final static OrderElement toEntity(OrderElementDTO orderElementDTO, ConfigurationOrderElementConverter configuration)
throws ValidationException {
return toEntity(null, orderElementDTO, configuration);
}
public final static OrderElement toEntity(OrderVersion orderVersion,
OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration) {
public static final OrderElement toEntity(
OrderVersion orderVersion, OrderElementDTO orderElementDTO, ConfigurationOrderElementConverter configuration) {
OrderVersion newOrderVersion = orderVersion;
if (orderVersion == null) {
Scenario current = Registry.getScenarioManager().getCurrent();
orderVersion = OrderVersion.createInitialVersion(current);
newOrderVersion = OrderVersion.createInitialVersion(current);
}
OrderElement orderElement = toEntityExceptCriterionRequirements(
orderVersion, orderElementDTO, configuration);
OrderElement orderElement = toEntityExceptCriterionRequirements(newOrderVersion, orderElementDTO, configuration);
// FIXME Review why this validation is needed here, it breaks the
// subcontract service. This was introduced at commit 341145a5
// FIXME Review why this validation is needed here, it breaks the subcontract service.
// This was introduced in commit 341145a5
// Validate OrderElement.code and HoursGroup.code must be unique
// Order.checkConstraintOrderUniqueCode(orderElement);
// HoursGroup.checkConstraintHoursGroupUniqueCode(orderElement);
@ -268,34 +263,26 @@ public final class OrderElementConverter {
return orderElement;
}
private static void checkOrderElementDTOCode(
OrderElementDTO orderElementDTO,
String instance) {
private static void checkOrderElementDTOCode(OrderElementDTO orderElementDTO, String instance) {
if (orderElementDTO.code == null) {
throw new ValidationException(MessageFormat.format(
"{0}: code not found", instance));
throw new ValidationException(MessageFormat.format("{0}: code not found", instance));
}
}
private static void addOrCriterionRequirements(OrderElement orderElement,
OrderElementDTO orderElementDTO) {
addOrCriterionRequirementsEntities(orderElement,
orderElementDTO.criterionRequirements);
private static void addOrCriterionRequirements(OrderElement orderElement, OrderElementDTO orderElementDTO) {
addOrCriterionRequirementsEntities(orderElement, orderElementDTO.criterionRequirements);
if (orderElement != null) {
if (orderElementDTO instanceof OrderLineDTO) {
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
HoursGroup hoursGroup = ((OrderLine) orderElement)
.getHoursGroup(hoursGroupDTO.code);
HoursGroup hoursGroup = ((OrderLine) orderElement).getHoursGroup(hoursGroupDTO.code);
if (hoursGroup != null) {
addOrCriterionRequirementsEntities(hoursGroup,
hoursGroupDTO.criterionRequirements);
addOrCriterionRequirementsEntities(hoursGroup, hoursGroupDTO.criterionRequirements);
}
}
} else { // orderElementDTO instanceof OrderLineGroupDTO
for (OrderElementDTO childDTO : ((OrderLineGroupDTO) orderElementDTO).children) {
OrderElement child = ((OrderLineGroup) orderElement)
.getOrderElement(childDTO.code);
OrderElement child = orderElement.getOrderElement(childDTO.code);
addOrCriterionRequirements(child, childDTO);
}
}
@ -303,42 +290,38 @@ public final class OrderElementConverter {
}
private static void addOrCriterionRequirementsEntities(
ICriterionRequirable criterionRequirable,
Set<CriterionRequirementDTO> criterionRequirements) {
ICriterionRequirable criterionRequirable, Set<CriterionRequirementDTO> criterionRequirements) {
for (CriterionRequirementDTO criterionRequirementDTO : criterionRequirements) {
Criterion criterion = getCriterion(criterionRequirementDTO.name,
criterionRequirementDTO.type);
Criterion criterion = getCriterion(criterionRequirementDTO.name, criterionRequirementDTO.type);
if (criterion != null) {
if (criterionRequirementDTO instanceof DirectCriterionRequirementDTO) {
DirectCriterionRequirement directCriterionRequirement = getDirectCriterionRequirementByCriterion(
criterionRequirable, criterion);
DirectCriterionRequirement directCriterionRequirement =
getDirectCriterionRequirementByCriterion(criterionRequirable, criterion);
if (directCriterionRequirement == null) {
try {
criterionRequirable
.addCriterionRequirement(DirectCriterionRequirement
.create(criterion));
criterionRequirable.addCriterionRequirement(DirectCriterionRequirement.create(criterion));
} catch (IllegalStateException e) {
throw new ValidationException(e.getMessage());
}
}
} else { // criterionRequirementDTO instanceof
// IndirectCriterionRequirementDTO
IndirectCriterionRequirement indirectCriterionRequirement = getIndirectCriterionRequirementByCriterion(
criterionRequirable, criterion);
} else { // criterionRequirementDTO instanceof IndirectCriterionRequirementDTO
IndirectCriterionRequirement indirectCriterionRequirement =
getIndirectCriterionRequirementByCriterion(criterionRequirable, criterion);
if (indirectCriterionRequirement != null) {
indirectCriterionRequirement
.setValid(((IndirectCriterionRequirementDTO) criterionRequirementDTO).valid);
indirectCriterionRequirement.setValid(((IndirectCriterionRequirementDTO) criterionRequirementDTO).valid);
}
}
} else {
if (criterionRequirementDTO.name == null
|| criterionRequirementDTO.type == null) {
throw new ValidationException(
"the criterion format is incorrect");
if (criterionRequirementDTO.name == null || criterionRequirementDTO.type == null) {
throw new ValidationException("the criterion format is incorrect");
} else {
throw new ValidationException("the criterion "
+ criterionRequirementDTO.name + " which type is "
+ criterionRequirementDTO.type + " not found");
throw new ValidationException("the criterion " +
criterionRequirementDTO.name + " which type is " +
criterionRequirementDTO.type + " not found");
}
}
}
@ -346,8 +329,8 @@ public final class OrderElementConverter {
private static DirectCriterionRequirement getDirectCriterionRequirementByCriterion(
ICriterionRequirable criterionRequirable, Criterion criterion) {
for (CriterionRequirement criterionRequirement : criterionRequirable
.getCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : criterionRequirable.getCriterionRequirements()) {
if (criterionRequirement instanceof DirectCriterionRequirement) {
if (criterionRequirement.getCriterion().isEquivalent(criterion)) {
return (DirectCriterionRequirement) criterionRequirement;
@ -359,8 +342,8 @@ public final class OrderElementConverter {
private static IndirectCriterionRequirement getIndirectCriterionRequirementByCriterion(
ICriterionRequirable criterionRequirable, Criterion criterion) {
for (CriterionRequirement criterionRequirement : criterionRequirable
.getCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : criterionRequirable.getCriterionRequirements()) {
if (criterionRequirement instanceof IndirectCriterionRequirement) {
if (criterionRequirement.getCriterion().isEquivalent(criterion)) {
return (IndirectCriterionRequirement) criterionRequirement;
@ -370,30 +353,28 @@ public final class OrderElementConverter {
return null;
}
private final static OrderElement toEntityExceptCriterionRequirements(
private static final OrderElement toEntityExceptCriterionRequirements(
OrderVersion parentOrderVersion,
OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws ValidationException {
ConfigurationOrderElementConverter configuration) {
Validate.notNull(parentOrderVersion);
OrderElement orderElement;
if (orderElementDTO instanceof OrderLineDTO) {
checkOrderElementDTOCode(orderElementDTO, "OrderLineDTO");
if ((configuration.isHoursGroups())
&& (!((OrderLineDTO) orderElementDTO).hoursGroups.isEmpty())) {
if ((configuration.isHoursGroups()) && (!((OrderLineDTO) orderElementDTO).hoursGroups.isEmpty())) {
orderElement = OrderLine.createUnvalidated(orderElementDTO.code);
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
HoursGroup hoursGroup = toEntity(hoursGroupDTO,
configuration);
HoursGroup hoursGroup = toEntity(hoursGroupDTO);
((OrderLine) orderElement).addHoursGroup(hoursGroup);
}
} else {
orderElement = OrderLine.createUnvalidatedWithUnfixedPercentage(orderElementDTO.code, 0);
if (!orderElement.getHoursGroups().isEmpty()) {
orderElement.getHoursGroups().get(0).setCode(
UUID.randomUUID().toString());
orderElement.getHoursGroups().get(0).setCode(UUID.randomUUID().toString());
}
}
} else { // orderElementDTO instanceof OrderLineGroupDTO
@ -402,30 +383,30 @@ public final class OrderElementConverter {
checkOrderElementDTOCode(orderElementDTO, "OrderDTO");
orderElement = Order.createUnvalidated(orderElementDTO.code);
Scenario current = Registry.getScenarioManager().getCurrent();
((Order) orderElement).setVersionForScenario(current,
parentOrderVersion);
((Order) orderElement)
.setDependenciesConstraintsHavePriority(((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority);
List<BaseCalendar> calendars = Registry.getBaseCalendarDAO()
.findByName(((OrderDTO) orderElementDTO).calendarName);
((Order) orderElement).setVersionForScenario(current, parentOrderVersion);
((Order) orderElement).setDependenciesConstraintsHavePriority(
((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority);
List<BaseCalendar> calendars =
Registry.getBaseCalendarDAO().findByName(((OrderDTO) orderElementDTO).calendarName);
BaseCalendar calendar;
if ((calendars != null) && (calendars.size() == 1)) {
calendar = calendars.get(0);
} else {
calendar = Registry.getConfigurationDAO()
.getConfiguration().getDefaultCalendar();
calendar = Registry.getConfigurationDAO().getConfiguration().getDefaultCalendar();
}
((Order) orderElement).setCalendar(calendar);
} else { // orderElementDTO instanceof OrderLineGroupDTO
checkOrderElementDTOCode(orderElementDTO, "OrderLineGroupDTO");
orderElement = OrderLineGroup
.createUnvalidated(orderElementDTO.code);
orderElement = OrderLineGroup.createUnvalidated(orderElementDTO.code);
}
orderElement.useSchedulingDataFor(parentOrderVersion);
List<OrderElement> children = new ArrayList<OrderElement>();
List<OrderElement> children = new ArrayList<>();
for (OrderElementDTO element : ((OrderLineGroupDTO) orderElementDTO).children) {
children.add(toEntity(parentOrderVersion, element,
configuration));
children.add(toEntity(parentOrderVersion, element, configuration));
}
for (OrderElement child : children) {
@ -435,27 +416,23 @@ public final class OrderElementConverter {
orderElement.setName(orderElementDTO.name);
orderElement.setCode(orderElementDTO.code);
orderElement
.setInitDate(DateConverter.toDate(orderElementDTO.initDate));
orderElement
.setDeadline(DateConverter.toDate(orderElementDTO.deadline));
orderElement.setInitDate(DateConverter.toDate(orderElementDTO.initDate));
orderElement.setDeadline(DateConverter.toDate(orderElementDTO.deadline));
orderElement.setDescription(orderElementDTO.description);
if (configuration.isLabels()) {
for (LabelReferenceDTO labelDTO : orderElementDTO.labels) {
try {
orderElement.addLabel(LabelReferenceConverter.toEntity(labelDTO));
orderElement.addLabel(Registry.getLabelDAO().findByCode(labelDTO.code));
} catch (InstanceNotFoundException e) {
throw new ValidationException("Label " + labelDTO.code
+ " not found.");
throw new ValidationException("Label " + labelDTO.code + " not found.");
}
}
}
if (configuration.isMaterialAssignments()) {
for (MaterialAssignmentDTO materialAssignmentDTO : orderElementDTO.materialAssignments) {
orderElement
.addMaterialAssignment(toEntity(materialAssignmentDTO));
orderElement.addMaterialAssignment(toEntity(materialAssignmentDTO));
}
}
@ -467,113 +444,87 @@ public final class OrderElementConverter {
}
private static Criterion getCriterion(String name, String type) {
List<Criterion> criterions = Registry.getCriterionDAO()
.findByNameAndType(name, type);
if (criterions.size() != 1) {
return null;
}
return criterions.get(0);
List<Criterion> criterions = Registry.getCriterionDAO().findByNameAndType(name, type);
return criterions.size() != 1 ? null : criterions.get(0);
}
public static DirectCriterionRequirement toEntity(
DirectCriterionRequirementDTO criterionRequirementDTO) {
Criterion criterion = getCriterion(criterionRequirementDTO.name,
criterionRequirementDTO.type);
if (criterion == null) {
return null;
}
return DirectCriterionRequirement.create(criterion);
public static DirectCriterionRequirement toEntity(DirectCriterionRequirementDTO criterionRequirementDTO) {
Criterion criterion = getCriterion(criterionRequirementDTO.name, criterionRequirementDTO.type);
return criterion == null ? null : DirectCriterionRequirement.create(criterion);
}
public final static MaterialAssignment toEntity(
MaterialAssignmentDTO materialAssignmentDTO) {
Material material = null;
public static final MaterialAssignment toEntity(MaterialAssignmentDTO materialAssignmentDTO) {
Material material;
try {
material = Registry.getMaterialDAO()
.findUniqueByCodeInAnotherTransaction(
materialAssignmentDTO.materialCode);
material = Registry.getMaterialDAO().findUniqueByCodeInAnotherTransaction(materialAssignmentDTO.materialCode);
} catch (InstanceNotFoundException e) {
material = Material.create(materialAssignmentDTO.materialCode);
material.setDescription("material-"
+ materialAssignmentDTO.materialCode);
material.setDescription("material-" + materialAssignmentDTO.materialCode);
MaterialCategory defaultMaterialCategory =
PredefinedMaterialCategories.IMPORTED_MATERIALS_WITHOUT_CATEGORY.getMaterialCategory();
MaterialCategory defaultMaterialCategory = PredefinedMaterialCategories.IMPORTED_MATERIALS_WITHOUT_CATEGORY
.getMaterialCategory();
material.setCategory(defaultMaterialCategory);
/*
* "validate" method avoids that "material" goes to the Hibernate's
* session if "material" is not valid.
*/
/* "validate" method avoids that "material" goes to the Hibernate's session if "material" is not valid */
material.validate();
Registry.getMaterialDAO().save(material);
material.dontPoseAsTransientObjectAnymore();
}
MaterialAssignment materialAssignment = MaterialAssignment
.create(material);
materialAssignment
.setUnitsWithoutNullCheck(materialAssignmentDTO.units);
materialAssignment
.setUnitPriceWithoutNullCheck(materialAssignmentDTO.unitPrice);
MaterialAssignment materialAssignment = MaterialAssignment.create(material);
materialAssignment.setUnitsWithoutNullCheck(materialAssignmentDTO.units);
materialAssignment.setUnitPriceWithoutNullCheck(materialAssignmentDTO.unitPrice);
Date estimatedAvailability = DateConverter
.toDate(materialAssignmentDTO.estimatedAvailability);
Date estimatedAvailability = DateConverter.toDate(materialAssignmentDTO.estimatedAvailability);
materialAssignment.setEstimatedAvailability(estimatedAvailability);
return materialAssignment;
}
public final static HoursGroup toEntity(HoursGroupDTO hoursGroupDTO,
ConfigurationOrderElementConverter configuration) {
ResourceEnum resourceType = ResourceEnumConverter
.fromDTO(hoursGroupDTO.resourceType);
HoursGroup hoursGroup = HoursGroup.createUnvalidated(
hoursGroupDTO.code, resourceType, hoursGroupDTO.workingHours);
return hoursGroup;
public static final HoursGroup toEntity(HoursGroupDTO hoursGroupDTO) {
ResourceEnum resourceType = ResourceEnumConverter.fromDTO(hoursGroupDTO.resourceType);
return HoursGroup.createUnvalidated(hoursGroupDTO.code, resourceType, hoursGroupDTO.workingHours);
}
public final static void update(OrderElement orderElement,
OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws ValidationException {
public static final void update(
OrderElement orderElement, OrderElementDTO orderElementDTO, ConfigurationOrderElementConverter configuration) {
update(null, orderElement, orderElementDTO, configuration);
}
private final static void update(OrderVersion orderVersion,
OrderElement orderElement, OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws ValidationException {
updateExceptCriterionRequirements(orderVersion, orderElement,
orderElementDTO, configuration);
private static final void update(
OrderVersion orderVersion, OrderElement orderElement, OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration) {
updateExceptCriterionRequirements(orderVersion, orderElement, orderElementDTO, configuration);
if (configuration.isCriterionRequirements()) {
addOrCriterionRequirements(orderElement, orderElementDTO);
}
}
private final static void updateExceptCriterionRequirements(
private static final void updateExceptCriterionRequirements(
OrderVersion orderVersion,
OrderElement orderElement, OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws ValidationException {
OrderElement orderElement,
OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration) {
OrderVersion newOrderVersion = orderVersion;
if (orderElementDTO instanceof OrderLineDTO) {
if (!(orderElement instanceof OrderLine)) {
throw new ValidationException(MessageFormat.format(
"Task {0}: Task group is incompatible type with {1}",
orderElement.getCode(), orderElement.getClass()
.getName()));
orderElement.getCode(), orderElement.getClass().getName()));
}
if (configuration.isHoursGroups()) {
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
if ( ((OrderLine) orderElement).containsHoursGroup(hoursGroupDTO.code) ) {
update( ((OrderLine) orderElement)
.getHoursGroup(hoursGroupDTO.code), hoursGroupDTO, configuration);
update( ((OrderLine) orderElement).getHoursGroup(hoursGroupDTO.code), hoursGroupDTO);
} else {
((OrderLine) orderElement).addHoursGroup(toEntity(hoursGroupDTO, configuration));
((OrderLine) orderElement).addHoursGroup(toEntity(hoursGroupDTO));
}
}
}
@ -582,64 +533,51 @@ public final class OrderElementConverter {
if (!(orderElement instanceof Order)) {
throw new ValidationException(MessageFormat.format(
"Task {0}: Project is incompatible type with {1}",
orderElement.getCode(), orderElement.getClass()
.getName()));
orderElement.getCode(), orderElement.getClass().getName()));
}
Order order = (Order) orderElement;
orderVersion = order.getOrderVersionFor(Registry
.getScenarioManager()
.getCurrent());
order.useSchedulingDataFor(orderVersion);
newOrderVersion = order.getOrderVersionFor(Registry.getScenarioManager().getCurrent());
order.useSchedulingDataFor(newOrderVersion);
Boolean dependenciesConstraintsHavePriority = ((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority;
if (dependenciesConstraintsHavePriority != null) {
((Order) orderElement)
.setDependenciesConstraintsHavePriority(dependenciesConstraintsHavePriority);
((Order) orderElement).setDependenciesConstraintsHavePriority(dependenciesConstraintsHavePriority);
}
String calendarName = ((OrderDTO) orderElementDTO).calendarName;
if (calendarName != null) {
if (!((Order) orderElement).getCalendar().getName().equals(
calendarName)) {
List<BaseCalendar> calendars = Registry
.getBaseCalendarDAO()
.findByName(
((OrderDTO) orderElementDTO).calendarName);
if (calendars.size() == 1) {
((Order) orderElement)
.setCalendar(calendars.get(0));
}
if (calendarName != null && !((Order) orderElement).getCalendar().getName().equals(calendarName)) {
List<BaseCalendar> calendars =
Registry.getBaseCalendarDAO().findByName(((OrderDTO) orderElementDTO).calendarName);
if (calendars.size() == 1) {
((Order) orderElement).setCalendar(calendars.get(0));
}
}
} else { // orderElementDTO instanceof OrderLineGroupDTO
if (!(orderElement instanceof OrderLineGroup)) {
throw new ValidationException(
MessageFormat
.format("Task {0}: Task group is incompatible type with {1}",
orderElement.getCode(),
orderElement.getClass().getName()));
throw new ValidationException(MessageFormat.format(
"Task {0}: Task group is incompatible type with {1}",
orderElement.getCode(), orderElement.getClass().getName()));
}
}
for (OrderElementDTO childDTO : ((OrderLineGroupDTO) orderElementDTO).children) {
if (orderElement.containsOrderElement(childDTO.code)) {
update(orderVersion,
orderElement.getOrderElement(childDTO.code),
childDTO, configuration);
update(newOrderVersion, orderElement.getOrderElement(childDTO.code), childDTO, configuration);
} else {
if (checkConstraintUniqueOrderCode(childDTO)) {
throw new ValidationException(
MessageFormat.format(
"Task {0}: Duplicate code in DB",
childDTO.code));
throw new ValidationException(MessageFormat.format(
"Task {0}: Duplicate code in DB", childDTO.code));
}
if (checkConstraintUniqueHoursGroupCode(childDTO)) {
throw new ValidationException(MessageFormat.format(
"Hours Group {0}: Duplicate code in DB",
childDTO.code));
"Hours Group {0}: Duplicate code in DB", childDTO.code));
}
((OrderLineGroup) orderElement).add(toEntity(orderVersion,
childDTO, configuration));
((OrderLineGroup) orderElement).add(toEntity(newOrderVersion, childDTO, configuration));
}
}
@ -649,11 +587,9 @@ public final class OrderElementConverter {
for (LabelReferenceDTO labelDTO : orderElementDTO.labels) {
if (!orderElement.containsLabel(labelDTO.code)) {
try {
orderElement.addLabel(LabelReferenceConverter
.toEntity(labelDTO));
orderElement.addLabel(Registry.getLabelDAO().findByCode(labelDTO.code));
} catch (InstanceNotFoundException e) {
throw new ValidationException("Label " + labelDTO.code
+ " not found");
throw new ValidationException("Label " + labelDTO.code + " not found");
} catch (IllegalArgumentException e) {
throw new ValidationException(e.getMessage());
}
@ -663,15 +599,10 @@ public final class OrderElementConverter {
if (configuration.isMaterialAssignments()) {
for (MaterialAssignmentDTO materialAssignmentDTO : orderElementDTO.materialAssignments) {
if (orderElement
.containsMaterialAssignment(materialAssignmentDTO.materialCode)) {
update(
orderElement
.getMaterialAssignment(materialAssignmentDTO.materialCode),
materialAssignmentDTO);
if (orderElement.containsMaterialAssignment(materialAssignmentDTO.materialCode)) {
update(orderElement.getMaterialAssignment(materialAssignmentDTO.materialCode), materialAssignmentDTO);
} else {
orderElement
.addMaterialAssignment(toEntity(materialAssignmentDTO));
orderElement.addMaterialAssignment(toEntity(materialAssignmentDTO));
}
}
}
@ -685,13 +616,11 @@ public final class OrderElementConverter {
}
if (orderElementDTO.initDate != null) {
orderElement.setInitDate(DateConverter
.toDate(orderElementDTO.initDate));
orderElement.setInitDate(DateConverter.toDate(orderElementDTO.initDate));
}
if (orderElementDTO.deadline != null) {
orderElement.setDeadline(DateConverter
.toDate(orderElementDTO.deadline));
orderElement.setDeadline(DateConverter.toDate(orderElementDTO.deadline));
}
if (orderElementDTO.description != null) {
@ -701,15 +630,14 @@ public final class OrderElementConverter {
}
/**
* Returns true is there's another {@link OrderElement} in DB with the same code
* Returns true is there's another {@link OrderElement} in DB with the same code.
*
* @param orderElement
* @return
* @return boolean
*/
private static boolean checkConstraintUniqueOrderCode(OrderElementDTO orderElement) {
try {
OrderElement existsByCode = Registry.getOrderElementDAO()
.findByCode(orderElement.code);
OrderElement existsByCode = Registry.getOrderElementDAO().findByCode(orderElement.code);
return existsByCode != null;
} catch (InstanceNotFoundException e) {
return false;
@ -717,16 +645,13 @@ public final class OrderElementConverter {
}
/**
* Returns true if there's another {@link HoursGroup} in DB with the same code
* Returns true if there's another {@link HoursGroup} in DB with the same code.
*
* @param orderElement
* @return
* @return boolean
*/
private static boolean checkConstraintUniqueHoursGroupCode(OrderElementDTO orderElement) {
if (orderElement instanceof OrderLineDTO) {
return checkConstraintUniqueHoursGroupCode((OrderLineDTO) orderElement);
}
return false;
return orderElement instanceof OrderLineDTO && checkConstraintUniqueHoursGroupCode((OrderLineDTO) orderElement);
}
private static boolean checkConstraintUniqueHoursGroupCode(OrderLineDTO orderLine) {
@ -739,18 +664,15 @@ public final class OrderElementConverter {
return true;
}
}
} catch (InstanceNotFoundException e) {
} catch (InstanceNotFoundException ignored) {
// Do nothing
}
return false;
}
public final static void update(HoursGroup hoursGroup,
HoursGroupDTO hoursGroupDTO,
ConfigurationOrderElementConverter configuration) {
public final static void update(HoursGroup hoursGroup, HoursGroupDTO hoursGroupDTO) {
if (!hoursGroup.getCode().equals(hoursGroupDTO.code)) {
throw new ValidationException(
"Not the same hours group, impossible to update");
throw new ValidationException("Not the same hours group, impossible to update");
}
if (hoursGroupDTO.workingHours != null) {
@ -758,34 +680,30 @@ public final class OrderElementConverter {
}
if (hoursGroupDTO.resourceType != null) {
hoursGroup.setResourceType(ResourceEnumConverter
.fromDTO(hoursGroupDTO.resourceType));
hoursGroup.setResourceType(ResourceEnumConverter.fromDTO(hoursGroupDTO.resourceType));
}
}
public final static void update(MaterialAssignment materialAssignment,
MaterialAssignmentDTO materialAssignmentDTO) {
if (!materialAssignment.getMaterial().getCode().equals(
materialAssignmentDTO.materialCode)) {
throw new ValidationException(
"Not the same material, impossible to update");
public static final void update(MaterialAssignment materialAssignment, MaterialAssignmentDTO materialAssignmentDTO) {
if (!materialAssignment.getMaterial().getCode().equals(materialAssignmentDTO.materialCode)) {
throw new ValidationException("Not the same material, impossible to update");
}
if (materialAssignmentDTO.units != null) {
materialAssignment.setUnits(materialAssignmentDTO.units);
}
if (materialAssignmentDTO.unitPrice != null) {
materialAssignment.setUnitPrice(materialAssignmentDTO.unitPrice);
}
if (materialAssignmentDTO.estimatedAvailability != null) {
Date estimatedAvailability = DateConverter
.toDate(materialAssignmentDTO.estimatedAvailability);
Date estimatedAvailability = DateConverter.toDate(materialAssignmentDTO.estimatedAvailability);
materialAssignment.setEstimatedAvailability(estimatedAvailability);
}
}
private static void addAdvanceMeasurements(OrderElement orderElement,
OrderElementDTO orderElementDTO) {
private static void addAdvanceMeasurements(OrderElement orderElement, OrderElementDTO orderElementDTO) {
if (!orderElementDTO.advanceMeasurements.isEmpty()) {
DirectAdvanceAssignment directAdvanceAssignment = getDirectAdvanceAssignmentSubcontractor(orderElement);
@ -793,17 +711,13 @@ public final class OrderElementConverter {
AdvanceMeasurement advanceMeasurement = null;
LocalDate date = null;
if (advanceMeasurementDTO.date != null) {
date = new LocalDate(DateConverter
.toLocalDate(advanceMeasurementDTO.date));
advanceMeasurement = directAdvanceAssignment
.getAdvanceMeasurementAtExactDate(date);
date = new LocalDate(DateConverter.toLocalDate(advanceMeasurementDTO.date));
advanceMeasurement = directAdvanceAssignment.getAdvanceMeasurementAtExactDate(date);
}
if (advanceMeasurement == null) {
advanceMeasurement = AdvanceMeasurement.create(date,
advanceMeasurementDTO.value);
directAdvanceAssignment
.addAdvanceMeasurements(advanceMeasurement);
advanceMeasurement = AdvanceMeasurement.create(date, advanceMeasurementDTO.value);
directAdvanceAssignment.addAdvanceMeasurements(advanceMeasurement);
} else {
advanceMeasurement.setValue(advanceMeasurementDTO.value);
}
@ -811,63 +725,49 @@ public final class OrderElementConverter {
}
}
private static DirectAdvanceAssignment getDirectAdvanceAssignmentSubcontractor(
OrderElement orderElement) {
DirectAdvanceAssignment directAdvanceAssignment = orderElement
.getDirectAdvanceAssignmentSubcontractor();
private static DirectAdvanceAssignment getDirectAdvanceAssignmentSubcontractor(OrderElement orderElement) {
DirectAdvanceAssignment directAdvanceAssignment = orderElement.getDirectAdvanceAssignmentSubcontractor();
if (directAdvanceAssignment == null) {
try {
directAdvanceAssignment = orderElement
.addSubcontractorAdvanceAssignment();
directAdvanceAssignment = orderElement.addSubcontractorAdvanceAssignment();
} catch (DuplicateValueTrueReportGlobalAdvanceException e) {
throw new ValidationException(
MessageFormat
.format("More than one progress marked as report global for task {0}",
orderElement.getCode()));
throw new ValidationException(MessageFormat.format(
"More than one progress marked as report global for task {0}", orderElement.getCode()));
} catch (DuplicateAdvanceAssignmentForOrderElementException e) {
throw new ValidationException(MessageFormat.format(
"Duplicate progress assignment for task {0}",
orderElement.getCode()));
"Duplicate progress assignment for task {0}", orderElement.getCode()));
}
}
return directAdvanceAssignment;
}
public static AdvanceMeasurement toEntity(
AdvanceMeasurementDTO advanceMeasurementDTO) {
LocalDate date = DateConverter.toLocalDate(advanceMeasurementDTO.date);
AdvanceMeasurement advanceMeasurement = AdvanceMeasurement.create(date,
advanceMeasurementDTO.value);
return advanceMeasurement;
public static AdvanceMeasurement toEntity(AdvanceMeasurementDTO advanceMeasurementDTO) {
return AdvanceMeasurement.create(DateConverter.toLocalDate(advanceMeasurementDTO.date), advanceMeasurementDTO.value);
}
public static AdvanceMeasurementDTO toDTO(
AdvanceMeasurement advanceMeasurement) {
XMLGregorianCalendar date = DateConverter
.toXMLGregorianCalendar(advanceMeasurement.getDate());
return new AdvanceMeasurementDTO(date, advanceMeasurement
.getValue());
public static AdvanceMeasurementDTO toDTO(AdvanceMeasurement advanceMeasurement) {
return new AdvanceMeasurementDTO(
DateConverter.toXMLGregorianCalendar(advanceMeasurement.getDate()),
advanceMeasurement.getValue());
}
public static EndDateCommunication toEntity(
EndDateCommunicationToCustomerDTO endDateCommunicationToCustomerDTO) {
public static EndDateCommunication toEntity(EndDateCommunicationToCustomerDTO endDateCommunicationToCustomerDTO) {
Date endDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.endDate);
Date communicationDate = DateConverter
.toDate(endDateCommunicationToCustomerDTO.communicationDate);
Date communicationDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.communicationDate);
Date saveDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.saveDate);
EndDateCommunication endDateCommunicationToCustomer = EndDateCommunication
.create(saveDate, endDate, communicationDate);
return endDateCommunicationToCustomer;
return EndDateCommunication.create(saveDate, endDate, communicationDate);
}
public static EndDateCommunicationToCustomerDTO toDTO(
EndDateCommunication endDateCommunicationToCustomer) {
XMLGregorianCalendar endDate = DateConverter
.toXMLGregorianCalendar(endDateCommunicationToCustomer.getEndDate());
XMLGregorianCalendar saveDate = DateConverter
.toXMLGregorianCalendar(endDateCommunicationToCustomer.getSaveDate());
XMLGregorianCalendar communicationDate = DateConverter
.toXMLGregorianCalendar(endDateCommunicationToCustomer.getCommunicationDate());
public static EndDateCommunicationToCustomerDTO toDTO(EndDateCommunication endDateCommunicationToCustomer) {
XMLGregorianCalendar endDate = DateConverter.toXMLGregorianCalendar(endDateCommunicationToCustomer.getEndDate());
XMLGregorianCalendar saveDate = DateConverter.toXMLGregorianCalendar(endDateCommunicationToCustomer.getSaveDate());
XMLGregorianCalendar communicationDate =
DateConverter.toXMLGregorianCalendar(endDateCommunicationToCustomer.getCommunicationDate());
return new EndDateCommunicationToCustomerDTO(saveDate, endDate, communicationDate);
}

View file

@ -42,7 +42,7 @@ import org.libreplan.ws.calendars.api.BaseCalendarDTO;
import org.libreplan.ws.calendars.impl.CalendarConverter;
import org.libreplan.ws.common.impl.DateConverter;
import org.libreplan.ws.common.impl.InstanceNotFoundRecoverableErrorException;
import org.libreplan.ws.common.impl.RecoverableErrorException;
import org.libreplan.ws.costcategories.api.CostCategoryDTO;
import org.libreplan.ws.resources.api.CalendarAvailabilityDTO;
import org.libreplan.ws.resources.api.CriterionSatisfactionDTO;
import org.libreplan.ws.resources.api.MachineDTO;
@ -55,23 +55,16 @@ import org.libreplan.ws.resources.criterion.api.CriterionTypeDTO;
/**
* Converter from/to resource-related entities to/from DTOs.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class ResourceConverter {
/*
* These constants should probably be moved to XxxDTO.ENTITY_TYPE
* if the corresponding DTOs are created in the future.
*/
private final static String RESOURCE_CALENDAR_ENTITY_TYPE =
"resource-calendar";
private final static String COST_CATEGORY_ENTITY_TYPE = "cost-category";
private ResourceConverter() {
}
private ResourceConverter() {}
public final static Resource toEntity(ResourceDTO resourceDTO)
throws ValidationException, RecoverableErrorException {
public static final Resource toEntity(ResourceDTO resourceDTO) {
checkResourceDTOType(resourceDTO);
@ -83,19 +76,14 @@ public class ResourceConverter {
resource = createResourceWithBasicData((WorkerDTO) resourceDTO);
}
addCriterionSatisfactions(resource,
resourceDTO.criterionSatisfactions);
addCriterionSatisfactions(resource, resourceDTO.criterionSatisfactions);
setResourceCalendar(resource, resourceDTO.calendar);
addResourcesCostCategoryAssignments(resource,
resourceDTO.resourcesCostCategoryAssignments);
addResourcesCostCategoryAssignments(resource, resourceDTO.resourcesCostCategoryAssignments);
return resource;
}
public final static void updateResource(Resource resource,
ResourceDTO resourceDTO)
throws ValidationException, RecoverableErrorException {
public static final void updateResource(Resource resource, ResourceDTO resourceDTO) {
checkResourceDTOType(resourceDTO);
@ -103,26 +91,22 @@ public class ResourceConverter {
updateResourceCalendar(resource, resourceDTO.calendar);
updateCriterionSatisfactions(resource,
resourceDTO.criterionSatisfactions);
updateCriterionSatisfactions(resource, resourceDTO.criterionSatisfactions);
updateResourcesCostCategoryAssignments(resource,
resourceDTO.resourcesCostCategoryAssignments);
updateResourcesCostCategoryAssignments(resource, resourceDTO.resourcesCostCategoryAssignments);
}
private final static Machine createResourceWithBasicData(
MachineDTO machineDTO) {
private static final Machine createResourceWithBasicData(MachineDTO machineDTO) {
return Machine.createUnvalidated
(StringUtils.trim(machineDTO.code),
StringUtils.trim(machineDTO.name),
StringUtils.trim(machineDTO.description));
return Machine.createUnvalidated(
StringUtils.trim(machineDTO.code),
StringUtils.trim(machineDTO.name),
StringUtils.trim(machineDTO.description));
}
private final static Worker createResourceWithBasicData(
WorkerDTO workerDTO) {
private static final Worker createResourceWithBasicData(WorkerDTO workerDTO) {
return Worker.createUnvalidated(
StringUtils.trim(workerDTO.code),
@ -132,23 +116,17 @@ public class ResourceConverter {
}
private static void addCriterionSatisfactions(Resource resource,
List<CriterionSatisfactionDTO> criterionSatisfactions) {
private static void addCriterionSatisfactions(Resource resource, List<CriterionSatisfactionDTO> criterionSatisfactions) {
for (CriterionSatisfactionDTO criterionSatisfactionDTO :
criterionSatisfactions) {
for (CriterionSatisfactionDTO criterionSatisfactionDTO : criterionSatisfactions) {
CriterionSatisfaction criterionSatisfaction =
toEntity(criterionSatisfactionDTO, resource);
CriterionSatisfaction criterionSatisfaction = toEntity(criterionSatisfactionDTO, resource);
resource.addUnvalidatedSatisfaction(criterionSatisfaction);
}
}
private static CriterionSatisfaction toEntity(
CriterionSatisfactionDTO criterionSatisfactionDTO, Resource resource) {
private static CriterionSatisfaction toEntity(CriterionSatisfactionDTO criterionSatisfactionDTO, Resource resource) {
if (StringUtils.isBlank(criterionSatisfactionDTO.criterionTypeName)) {
throw new ValidationException("criterion type name not specified");
@ -171,19 +149,16 @@ public class ResourceConverter {
} catch (InstanceNotFoundException e) {
if (e.getClassName().equals(CriterionType.class.getName())) {
throw new InstanceNotFoundRecoverableErrorException(
CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
} else {
throw new InstanceNotFoundRecoverableErrorException(
CriterionDTO.ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(CriterionDTO.ENTITY_TYPE, e.getKey().toString());
}
}
}
private static void setResourceCalendar(Resource resource,
ResourceCalendarDTO calendar) {
private static void setResourceCalendar(Resource resource, ResourceCalendarDTO calendar) {
String calendarCode = null;
if (calendar != null) {
calendarCode = calendar.parent;
@ -193,21 +168,17 @@ public class ResourceConverter {
resource.setResourceCalendar(StringUtils.trim(calendarCode));
// Copy the data of the resource calendar DTO
updateBasicPropertiesResourceCalendar(calendar, resource
.getCalendar());
updateBasicPropertiesResourceCalendar(calendar, resource.getCalendar());
} catch (InstanceNotFoundException e) {
throw new InstanceNotFoundRecoverableErrorException(
RESOURCE_CALENDAR_ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(ResourceCalendarDTO.ENTITY_TYPE, e.getKey().toString());
} catch (MultipleInstancesException e) {
throw new ValidationException(MessageFormat.format(
"there exist multiple resource calendars with name {0}",
calendarCode));
"there exist multiple resource calendars with name {0}", calendarCode));
}
}
private static void updateBasicPropertiesResourceCalendar(
ResourceCalendarDTO calendarDTO, ResourceCalendar calendar) {
private static void updateBasicPropertiesResourceCalendar(ResourceCalendarDTO calendarDTO, ResourceCalendar calendar) {
if (calendarDTO != null) {
if (!StringUtils.isBlank(calendarDTO.name)) {
@ -217,8 +188,7 @@ public class ResourceConverter {
if (!StringUtils.isBlank(calendarDTO.code)) {
calendar.setCode(calendarDTO.code);
} else {
throw new ValidationException(
"missing code in the resource calendar");
throw new ValidationException("missing code in the resource calendar");
}
if (calendarDTO.capacity != null) {
@ -229,18 +199,12 @@ public class ResourceConverter {
}
private static void addResourcesCostCategoryAssignments(
Resource resource, List<ResourcesCostCategoryAssignmentDTO>
resourcesCostCategoryAssignments) {
Resource resource, List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignments) {
for (ResourcesCostCategoryAssignmentDTO assignmentDTO :
resourcesCostCategoryAssignments) {
ResourcesCostCategoryAssignment assignment = toEntity(assignmentDTO,
resource);
for (ResourcesCostCategoryAssignmentDTO assignmentDTO : resourcesCostCategoryAssignments) {
ResourcesCostCategoryAssignment assignment = toEntity(assignmentDTO, resource);
resource.addUnvalidatedResourcesCostCategoryAssignment(assignment);
}
}
private static ResourcesCostCategoryAssignment toEntity(
@ -256,9 +220,9 @@ public class ResourceConverter {
StringUtils.trim(assignmentDTO.costCategoryName), resource,
DateConverter.toLocalDate(assignmentDTO.startDate),
DateConverter.toLocalDate(assignmentDTO.endDate));
} catch (InstanceNotFoundException e) {
throw new InstanceNotFoundRecoverableErrorException(
COST_CATEGORY_ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(CostCategoryDTO.ENTITY_TYPE, e.getKey().toString());
}
}
@ -271,12 +235,9 @@ public class ResourceConverter {
Machine machine = (Machine) resource;
MachineDTO machineDTO = (MachineDTO) resourceDTO;
machine.updateUnvalidated(
StringUtils.trim(machineDTO.name),
StringUtils.trim(machineDTO.description));
machine.updateUnvalidated(StringUtils.trim(machineDTO.name), StringUtils.trim(machineDTO.description));
} else if (resource instanceof Worker &&
resourceDTO instanceof WorkerDTO) {
} else if (resource instanceof Worker && resourceDTO instanceof WorkerDTO) {
Worker worker = (Worker) resource;
WorkerDTO workerDTO = (WorkerDTO) resourceDTO;
@ -289,38 +250,28 @@ public class ResourceConverter {
} else {
throw new ValidationException(MessageFormat.format(
"Incompatible update: stored resource is not of type: {0}",
resourceDTO.getEntityType()));
"Incompatible update: stored resource is not of type: {0}", resourceDTO.getEntityType()));
}
}
private static void updateResourceCalendar(Resource resource,
ResourceCalendarDTO calendarDTO) {
// TODO. Decide policy to update calendar (e.g. previous calendar must
// be removed?, if new calendar is the same as previous, must be
// reinitialized again?, etc.)
/** Do not remove parameters */
private static void updateResourceCalendar(Resource resource, ResourceCalendarDTO calendarDTO) {
// TODO Decide policy to update calendar
// (e.g. previous calendar must be removed?, if new calendar is the same as previous, must be reinitialized again?, etc.)
}
private static void updateCriterionSatisfactions(Resource resource,
List<CriterionSatisfactionDTO> criterionSatisfactions) {
private static void updateCriterionSatisfactions(
Resource resource, List<CriterionSatisfactionDTO> criterionSatisfactions) {
for (CriterionSatisfactionDTO i : criterionSatisfactions) {
try {
CriterionSatisfaction criterionSatisfaction =
resource.getCriterionSatisfactionByCode(i.code);
CriterionSatisfaction criterionSatisfaction = resource.getCriterionSatisfactionByCode(i.code);
updateCriterionSatisfaction(criterionSatisfaction, i);
} catch (InstanceNotFoundException e) {
CriterionSatisfaction criterionSatisfaction =
toEntity(i, resource);
CriterionSatisfaction criterionSatisfaction = toEntity(i, resource);
resource.addUnvalidatedSatisfaction(criterionSatisfaction);
}
@ -329,8 +280,7 @@ public class ResourceConverter {
}
private static void updateCriterionSatisfaction(
CriterionSatisfaction criterionSatisfaction,
CriterionSatisfactionDTO criterionSatisfactionDTO) {
CriterionSatisfaction criterionSatisfaction, CriterionSatisfactionDTO criterionSatisfactionDTO) {
try {
@ -343,11 +293,9 @@ public class ResourceConverter {
} catch (InstanceNotFoundException e) {
if (e.getClassName().equals(CriterionType.class.getName())) {
throw new InstanceNotFoundRecoverableErrorException(
CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
} else {
throw new InstanceNotFoundRecoverableErrorException(
CriterionDTO.ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(CriterionDTO.ENTITY_TYPE, e.getKey().toString());
}
}
@ -355,35 +303,27 @@ public class ResourceConverter {
}
private static void updateResourcesCostCategoryAssignments(
Resource resource,
List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignments) {
Resource resource, List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignments) {
for (ResourcesCostCategoryAssignmentDTO i :
resourcesCostCategoryAssignments) {
for (ResourcesCostCategoryAssignmentDTO i : resourcesCostCategoryAssignments) {
try {
ResourcesCostCategoryAssignment assignment =
resource.getResourcesCostCategoryAssignmentByCode(i.code);
ResourcesCostCategoryAssignment assignment = resource.getResourcesCostCategoryAssignmentByCode(i.code);
updateResourcesCostCategoryAssignment(assignment, i);
} catch (InstanceNotFoundException e) {
ResourcesCostCategoryAssignment assignment =
toEntity(i, resource);
ResourcesCostCategoryAssignment assignment = toEntity(i, resource);
resource.addUnvalidatedResourcesCostCategoryAssignment(
assignment);
resource.addUnvalidatedResourcesCostCategoryAssignment(assignment);
}
}
}
private static void updateResourcesCostCategoryAssignment(
ResourcesCostCategoryAssignment assignment,
ResourcesCostCategoryAssignmentDTO i) {
ResourcesCostCategoryAssignment assignment, ResourcesCostCategoryAssignmentDTO i) {
try {
assignment.updateUnvalidated(
@ -391,23 +331,16 @@ public class ResourceConverter {
DateConverter.toLocalDate(i.startDate),
DateConverter.toLocalDate(i.endDate));
} catch (InstanceNotFoundException e) {
throw new InstanceNotFoundRecoverableErrorException(
COST_CATEGORY_ENTITY_TYPE, e.getKey().toString());
throw new InstanceNotFoundRecoverableErrorException(CostCategoryDTO.ENTITY_TYPE, e.getKey().toString());
}
}
private static void checkResourceDTOType(ResourceDTO resourceDTO) {
if (!(resourceDTO instanceof MachineDTO) &&
!(resourceDTO instanceof WorkerDTO)) {
if (!(resourceDTO instanceof MachineDTO) && !(resourceDTO instanceof WorkerDTO)) {
throw new ValidationException(MessageFormat.format(
"Service does not manage resource of type: {0}",
resourceDTO.getEntityType()));
"Service does not manage resource of type: {0}", resourceDTO.getEntityType()));
}
}
public static ResourceDTO toDTO(Resource resource) {
@ -420,94 +353,81 @@ public class ResourceConverter {
return null;
}
List<CriterionSatisfactionDTO> criterionSatisfactionDTOs = new ArrayList<CriterionSatisfactionDTO>();
for (CriterionSatisfaction criterionSatisfaction : resource
.getCriterionSatisfactions()) {
List<CriterionSatisfactionDTO> criterionSatisfactionDTOs = new ArrayList<>();
for (CriterionSatisfaction criterionSatisfaction : resource.getCriterionSatisfactions()) {
criterionSatisfactionDTOs.add(toDTO(criterionSatisfaction));
}
resourceDTO.criterionSatisfactions = criterionSatisfactionDTOs;
List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignmentDTOs = new ArrayList<ResourcesCostCategoryAssignmentDTO>();
for (ResourcesCostCategoryAssignment resourcesCostCategoryAssignment : resource
.getResourcesCostCategoryAssignments()) {
resourcesCostCategoryAssignmentDTOs
.add(toDTO(resourcesCostCategoryAssignment));
List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignmentDTOs = new ArrayList<>();
for (ResourcesCostCategoryAssignment resourcesCostCategoryAssignment : resource.getResourcesCostCategoryAssignments()) {
resourcesCostCategoryAssignmentDTOs.add(toDTO(resourcesCostCategoryAssignment));
}
resourceDTO.resourcesCostCategoryAssignments = resourcesCostCategoryAssignmentDTOs;
ResourceCalendarDTO resourceCalendarDTO = toDTO(resource.getCalendar());
resourceDTO.calendar = resourceCalendarDTO;
resourceDTO.calendar = toDTO(resource.getCalendar());
return resourceDTO;
}
private static WorkerDTO toDTO(Worker worker) {
return new WorkerDTO(worker.getCode(), worker.getFirstName(), worker
.getSurname(), worker.getNif());
return new WorkerDTO(worker.getCode(), worker.getFirstName(), worker.getSurname(), worker.getNif());
}
private static MachineDTO toDTO(Machine machine) {
return new MachineDTO(machine.getCode(), machine.getName(), machine
.getDescription());
return new MachineDTO(machine.getCode(), machine.getName(), machine.getDescription());
}
private static CriterionSatisfactionDTO toDTO(
CriterionSatisfaction criterionSatisfaction) {
return new CriterionSatisfactionDTO(criterionSatisfaction.getCode(),
private static CriterionSatisfactionDTO toDTO(CriterionSatisfaction criterionSatisfaction) {
return new CriterionSatisfactionDTO(
criterionSatisfaction.getCode(),
criterionSatisfaction.getCriterion().getType().getName(),
criterionSatisfaction.getCriterion().getName(), DateConverter
.toXMLGregorianCalendar(criterionSatisfaction
.getStartDate()), DateConverter
.toXMLGregorianCalendar(criterionSatisfaction
.getEndDate()));
criterionSatisfaction.getCriterion().getName(),
DateConverter.toXMLGregorianCalendar(criterionSatisfaction.getStartDate()),
DateConverter.toXMLGregorianCalendar(criterionSatisfaction.getEndDate()));
}
private static ResourcesCostCategoryAssignmentDTO toDTO(
ResourcesCostCategoryAssignment resourcesCostCategoryAssignment) {
Date initDate = (resourcesCostCategoryAssignment.getInitDate() == null) ? null
: resourcesCostCategoryAssignment.getInitDate()
.toDateTimeAtStartOfDay().toDate();
Date endDate = (resourcesCostCategoryAssignment.getEndDate() == null) ? null
: resourcesCostCategoryAssignment.getEndDate()
.toDateTimeAtStartOfDay().toDate();
private static ResourcesCostCategoryAssignmentDTO toDTO(ResourcesCostCategoryAssignment resourcesCostCategoryAssignment) {
Date initDate = (resourcesCostCategoryAssignment.getInitDate() == null)
? null
: resourcesCostCategoryAssignment.getInitDate().toDateTimeAtStartOfDay().toDate();
Date endDate = (resourcesCostCategoryAssignment.getEndDate() == null)
? null
: resourcesCostCategoryAssignment.getEndDate().toDateTimeAtStartOfDay().toDate();
return new ResourcesCostCategoryAssignmentDTO(
resourcesCostCategoryAssignment.getCode(),
resourcesCostCategoryAssignment.getCostCategory().getName(),
DateConverter.toXMLGregorianCalendar(initDate), DateConverter
.toXMLGregorianCalendar(endDate));
DateConverter.toXMLGregorianCalendar(initDate),
DateConverter.toXMLGregorianCalendar(endDate));
}
public static ResourceCalendarDTO toDTO(ResourceCalendar calendar) {
BaseCalendarDTO baseCalendarDTO = CalendarConverter.toDTO(calendar);
List<CalendarAvailabilityDTO> calendarAvailabilityDTOs = new ArrayList<CalendarAvailabilityDTO>();
for (CalendarAvailability calendarAvailability : calendar
.getCalendarAvailabilities()) {
List<CalendarAvailabilityDTO> calendarAvailabilityDTOs = new ArrayList<>();
for (CalendarAvailability calendarAvailability : calendar.getCalendarAvailabilities()) {
calendarAvailabilityDTOs.add(toDTO(calendarAvailability));
}
return new ResourceCalendarDTO(baseCalendarDTO.code,
baseCalendarDTO.name, baseCalendarDTO.parent, calendar
.getCapacity(), baseCalendarDTO.calendarExceptions,
baseCalendarDTO.calendarData, calendarAvailabilityDTOs);
return new ResourceCalendarDTO(
baseCalendarDTO.code, baseCalendarDTO.name, baseCalendarDTO.parent,
calendar.getCapacity(), baseCalendarDTO.calendarExceptions, baseCalendarDTO.calendarData,
calendarAvailabilityDTOs);
}
private static CalendarAvailabilityDTO toDTO(
CalendarAvailability calendarAvailability) {
private static CalendarAvailabilityDTO toDTO(CalendarAvailability calendarAvailability) {
Date startDate = calendarAvailability.getStartDate()
.toDateTimeAtStartOfDay().toDate();
Date startDate = calendarAvailability.getStartDate().toDateTimeAtStartOfDay().toDate();
Date endDate = null;
if (calendarAvailability.getEndDate() != null) {
endDate = calendarAvailability.getEndDate()
.toDateTimeAtStartOfDay().toDate();
endDate = calendarAvailability.getEndDate().toDateTimeAtStartOfDay().toDate();
}
return new CalendarAvailabilityDTO(calendarAvailability.getCode(),
startDate, endDate);
return new CalendarAvailabilityDTO(calendarAvailability.getCode(), startDate, endDate);
}
}

View file

@ -44,6 +44,10 @@ public class OrderElementWithAdvanceMeasurementsOrEndDateListDTO {
@XmlElement(name = "order-element")
public List<OrderElementWithAdvanceMeasurementsOrEndDateDTO> orderElements = new ArrayList<>();
/** Do not remove default constructor */
public OrderElementWithAdvanceMeasurementsOrEndDateListDTO() {
}
public OrderElementWithAdvanceMeasurementsOrEndDateListDTO(
String externalCompanyNif, List<OrderElementWithAdvanceMeasurementsOrEndDateDTO> orderElements) {

View file

@ -9432,4 +9432,16 @@ msgstr ""
#: libreplan-webapp/src/main/webapp/orders/_listOrderElementFiles.zul:32
msgid "No files"
msgstr ""
#: libreplan-webapp/src/main/webapp/common/pageNotFound.zul:57
msgid "Help/Info pages are not generated"
msgstr ""
#: libreplan-webapp/src/main/webapp/common/pageNotFound.zul:59
msgid "If you want to see help/info page then"
msgstr ""
#: libreplan-webapp/src/main/webapp/common/pageNotFound.zul:61
msgid "Open file HACKING.rst in project directory and read Part LibrePlan documentation generation, how to generate help/info pages"
msgstr ""

View file

@ -17,14 +17,16 @@
<http auto-config="false" realm="LibrePlan Web Application" >
<!-- In Spring 4.1.0 it is useless to use hasRole() for single role because Spring calling hasAnyRole() anyway -->
<!-- Web services -->
<intercept-url pattern="/ws/rest/bounduser/**" access="ROLE_BOUND_USER" method="GET" />
<intercept-url pattern="/ws/rest/bounduser/**" access="ROLE_BOUND_USER" method="POST" />
<intercept-url pattern="/ws/rest/subcontracting/**" access="ROLE_WS_SUBCONTRACTING" method="GET" />
<intercept-url pattern="/ws/rest/subcontracting/**" access="ROLE_WS_SUBCONTRACTING" method="POST" />
<intercept-url pattern="/ws/rest/**" access="ROLE_WS_READER" method="GET" />
<intercept-url pattern="/ws/rest/**" access="ROLE_WS_WRITER" method="POST" />
<intercept-url pattern="/ws/rest/**" access="ROLE_WS_WRITER" method="DELETE" />
<intercept-url pattern="/ws/rest/bounduser/**" access="hasAnyRole('ROLE_BOUND_USER')" method="GET" />
<intercept-url pattern="/ws/rest/bounduser/**" access="hasAnyRole('ROLE_BOUND_USER')" method="POST" />
<intercept-url pattern="/ws/rest/subcontracting/**" access="hasAnyRole('ROLE_WS_SUBCONTRACTING')" method="GET" />
<intercept-url pattern="/ws/rest/subcontracting/**" access="hasAnyRole('ROLE_WS_SUBCONTRACTING')" method="POST" />
<intercept-url pattern="/ws/rest/**" access="hasAnyRole('ROLE_WS_READER')" method="GET" />
<intercept-url pattern="/ws/rest/**" access="hasAnyRole('ROLE_WS_WRITER')" method="POST" />
<intercept-url pattern="/ws/rest/**" access="hasAnyRole('ROLE_WS_WRITER')" method="DELETE" />
<!-- Web application -->
<intercept-url pattern="/common/img/**" access="permitAll" />
@ -116,7 +118,7 @@
<intercept-url pattern="/reports/projectStatusReport.zul"
access="hasAnyRole('ROLE_SUPERUSER', 'ROLE_PROJECT_STATUS_REPORT')" />
<intercept-url pattern="/myaccount/userDashboard.zul" access="ROLE_BOUND_USER" />
<intercept-url pattern="/myaccount/userDashboard.zul" access="hasAnyRole('ROLE_BOUND_USER')" />
<intercept-url pattern="/myaccount/monthlyTimesheet.zul"
access="hasAnyRole('ROLE_SUPERUSER', 'ROLE_TIMESHEETS', 'ROLE_BOUND_USER')" />

View file

@ -1094,11 +1094,11 @@ span.z-dottree-line {
background-position: 18px 10px;
}
.label-highlight:hover{
.label-highlight:hover {
background-color: #aacbff;
}
.global-dashboard-grid{
.global-dashboard-grid {
margin-top: 5px;
}

View file

@ -132,13 +132,13 @@
<n:td width="450" height="165" valign="top">
<html if="${loginError == 'true' and SPRING_SECURITY_LAST_EXCEPTION.class.name == 'org.springframework.security.DisabledException'}">
<html if="${loginError == 'true' and SPRING_SECURITY_LAST_EXCEPTION.class.name == 'org.springframework.security.authentication.DisabledException'}">
<![CDATA[
<div class="login_ERROR">${i18n:_('User disabled')}</div>
]]>
</html>
<html if="${loginError == 'true' and SPRING_SECURITY_LAST_EXCEPTION.class.name == 'org.springframework.security.BadCredentialsException'}">
<html if="${loginError == 'true' and SPRING_SECURITY_LAST_EXCEPTION.class.name == 'org.springframework.security.authentication.BadCredentialsException'}">
<![CDATA[
<div class="login_ERROR">${i18n:_('Incorrect authentication')}</div>
]]>

View file

@ -54,11 +54,11 @@
<separator height="5px"/>
<label value="Help/Info pages are not generated!"/>
<label value="${i18n:_('Help/Info pages are not generated')}!"/>
<label value="If you want to see help/info page then:"/>
<label value="${i18n:_('If you want to see help/info page then')}:"/>
<label value="Open file HACKING.rst in project directory and read Part 'LibrePlan documentation generation', how to generate help/info pages."/>
<label value="${i18n:_('Open file HACKING.rst in project directory and read Part LibrePlan documentation generation, how to generate help/info pages')}."/>
</vbox>
</vbox>
</window>

View file

@ -1,4 +1,5 @@
<window apply="org.libreplan.web.dashboard.DashboardControllerGlobal" contentStyle="overflow:auto;">
<checkbox id="storedColumnVisible" label="${i18n:_('Show archived column data')}"
checked="true" onCheck="dashboardControllerGlobal.showStoredColumn()"/>

View file

@ -137,14 +137,6 @@
<button onClick="emailTemplateController.cancel()"
label="${i18n:_('Cancel')}" sclass="cancel-button global-action"/>
<button upload="true, maxsize=999">
<attribute name="onUpload">
<![CDATA[
System.out.println(event.getMedia());
]]>
</attribute>
</button>
<script>
<!-- Hack for removing unnecessary border of grid column -->
zk.afterMount(function() {

View file

@ -63,7 +63,7 @@
value="@{criterionRequirementWrapper.criterionAndType}">
<bandpopup>
<listbox width="500px" height="150px" sizedByContent="true"
model="@{assignedCriterionRequirementController.criterionWithItsTypesMachine}"
forEach="@{assignedCriterionRequirementController.criterionWithItsTypesMachine}"
onSelect="assignedCriterionRequirementController.selectCriterionToHoursGroup(self.selectedItem, self.parent.parent,self.parent.parent.parent.parent.value);">
<listhead>
<listheader label="Type" />

View file

@ -51,9 +51,8 @@
<groupbox closable="false">
<caption label="${i18n:_('Association with roles')}" />
<hbox align="center" sclass="report-margin">
<combobox id="userRolesCombo" autodrop="true" />
<button label="${i18n:_('Add role')}" sclass="add-button"
onClick="controller.addSelectedRole()"/>
<combobox id="userRolesCombo" autodrop="true"/>
<button label="${i18n:_('Add role')}" sclass="add-button" onClick="controller.addSelectedRole()"/>
</hbox>
<grid id="listing" model="@{controller.roles}"
rowRenderer="@{controller.rolesRenderer}">
@ -68,13 +67,10 @@
</tabbox>
<button onClick="controller.saveAndExit();" autodisable="self"
label="${i18n:_('Save')}"
sclass="save-button global-action" />
label="${i18n:_('Save')}" sclass="save-button global-action" />
<button onClick="controller.saveAndContinue();"
label="${i18n:_('Save &amp; Continue')}"
sclass="saveandcontinue-button global-action" />
label="${i18n:_('Save &amp; Continue')}" sclass="saveandcontinue-button global-action" />
<button onClick="controller.cancelForm();"
label="${i18n:_('Cancel')}"
sclass="cancel-button global-action" />
label="${i18n:_('Cancel')}" sclass="cancel-button global-action" />
</window>

View file

@ -166,7 +166,7 @@
visible="@{controller.areRolesAndProfilesDisabled}" />
</vbox>
<hbox align="center" style="margin: 2px 0 2px 0">
<combobox id="profilesCombo" autodrop="true" />
<combobox id="profilesCombo" autodrop="true" width="250px" />
<button label="${i18n:_('Add profile')}" sclass="add-button"
onClick="controller.addSelectedProfile()"
disabled="@{controller.areRolesAndProfilesDisabled}" />

View file

@ -30,8 +30,6 @@ import static org.libreplan.web.test.WebappGlobalNames.WEBAPP_SPRING_CONFIG_TEST
import static org.libreplan.web.test.WebappGlobalNames.WEBAPP_SPRING_SECURITY_CONFIG_TEST_FILE;
import static org.libreplan.web.test.ws.common.Util.getUniqueName;
import java.util.*;
import javax.xml.datatype.XMLGregorianCalendar;
import org.hibernate.Query;
@ -70,6 +68,12 @@ import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Collections;
/**
* Tests for <code>ICalendarService</code>.
*

View file

@ -172,6 +172,7 @@ public class SubcontractServiceTest {
@Test
@Transactional
/** FIXME Test could fail sometimes */
public void validSubcontractedTaskData() {
int previous = orderDAO.getOrders().size();

View file

@ -160,12 +160,11 @@
</profiles>
<!-- TODO make changes to http://nexus.libreplan.org/nexus/content/repositories/thirdparty -->
<repositories>
<!-- LibrePlan repository -->
<repository>
<id>thirdparty</id>
<url>http://nexus.libreplan.org/nexus/content/repositories/test/</url>
<url>http://nexus.libreplan.org/nexus/content/repositories/thirdparty-libreplan16/</url>
</repository>
</repositories>