Update Hibernate stack.

Update Hibernate ID generator.
Changes to Hibernate mappings.
Changes to OrderFileTest.
Code refactoring.
This commit is contained in:
Vova Perebykivskyi 2016-05-24 16:55:13 +03:00 committed by Dgray16
parent a2b46039cc
commit 455c0f53b0
117 changed files with 6119 additions and 6418 deletions

View file

@ -58,6 +58,10 @@ Changes
* Update Spring Security Web
* Update Spring Security Config
* Update Hibernate Core
* Update Hibernate Ehcache
* Update Hibernate Validator
* Update MPXJ
* Update Bonecp
* Update Guava
@ -75,7 +79,9 @@ Changes
* Update JAX-RS API
* Update BeanShell
* Update Quartz Framework
* Update Hibernate
* Update Usertype.Core
* Add Javax EL
* Update LibrePlan version to 1.6.0

View file

@ -2,9 +2,9 @@
<Context antiJARLocking="true" path="">
<Resource name="jdbc/libreplan-ds" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="libreplan" password="libreplan"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost/libreplan" />
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="libreplan" password="libreplan"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost/libreplan" />
</Context>

View file

@ -21,7 +21,6 @@
package org.zkoss.ganttz;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.Date;
@ -35,8 +34,6 @@ import org.joda.time.Duration;
import org.joda.time.LocalDate;
import org.zkoss.ganttz.adapters.IDisabilityConfiguration;
import org.zkoss.ganttz.data.GanttDate;
import org.zkoss.ganttz.data.ITaskFundamentalProperties.IModifications;
import org.zkoss.ganttz.data.ITaskFundamentalProperties.IUpdatablePosition;
import org.zkoss.ganttz.data.Milestone;
import org.zkoss.ganttz.data.Task;
import org.zkoss.ganttz.data.Task.IReloadResourcesTextRequested;
@ -111,7 +108,9 @@ public class TaskComponent extends Div implements AfterCompose {
setClass(calculateCSSClass());
setId(UUID.randomUUID().toString());
this.disabilityConfiguration = disabilityConfiguration;
taskViolationListener = Constraint.onlyOnZKExecution(new IConstraintViolationListener<GanttDate>() {
IConstraintViolationListener<GanttDate> taskViolationListener =
Constraint.onlyOnZKExecution(new IConstraintViolationListener<GanttDate>() {
@Override
public void constraintViolated(Constraint<GanttDate> constraint, GanttDate value) {
@ -125,23 +124,18 @@ public class TaskComponent extends Div implements AfterCompose {
});
this.task.addConstraintViolationListener(taskViolationListener, Mode.RECEIVE_PENDING);
reloadResourcesTextRequested = new IReloadResourcesTextRequested() {
@Override
public void reloadResourcesTextRequested() {
if ( canShowResourcesText() ) {
smartUpdate("resourcesText", getResourcesText());
}
String cssClass = calculateCSSClass();
response("setClass", new AuInvoke(TaskComponent.this, "setClass", cssClass));
// FIXME: Refactor to another listener
updateDeadline();
invalidate();
reloadResourcesTextRequested = () -> {
if ( canShowResourcesText() ) {
smartUpdate("resourcesText", getResourcesText());
}
String cssClass = calculateCSSClass();
response("setClass", new AuInvoke(TaskComponent.this, "setClass", cssClass));
// FIXME: Refactor to another listener
updateDeadline();
invalidate();
};
this.task.addReloadListener(reloadResourcesTextRequested);
@ -155,9 +149,7 @@ public class TaskComponent extends Div implements AfterCompose {
if ( command.equals("onUpdatePosition") ){
ta = retrieveTaskComponent(request);
ta.doUpdatePosition(
toInteger(retrieveData(request, "left"))
);
ta.doUpdatePosition(toInteger(retrieveData(request, "left")));
Events.postEvent(new Event(getId(), ta, request.getData()));
@ -248,25 +240,15 @@ public class TaskComponent extends Div implements AfterCompose {
public final void afterCompose() {
updateProperties();
if ( propertiesListener == null ) {
propertiesListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateProperties();
}
};
propertiesListener = evt -> updateProperties();
}
this.task.addFundamentalPropertiesChangeListener(propertiesListener);
if ( showingAdvancePropertyListener == null ) {
showingAdvancePropertyListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ( isInPage() && !(task instanceof Milestone) ) {
updateCompletionAdvance();
}
showingAdvancePropertyListener = evt -> {
if ( isInPage() && !(task instanceof Milestone) ) {
updateCompletionAdvance();
}
};
}
@ -274,13 +256,9 @@ public class TaskComponent extends Div implements AfterCompose {
this.task.addAdvancesPropertyChangeListener(showingAdvancePropertyListener);
if ( showingReportedHoursPropertyListener == null ) {
showingReportedHoursPropertyListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ( isInPage() && !(task instanceof Milestone) ) {
updateCompletionReportedHours();
}
showingReportedHoursPropertyListener = evt -> {
if ( isInPage() && !(task instanceof Milestone) ) {
updateCompletionReportedHours();
}
};
}
@ -288,13 +266,9 @@ public class TaskComponent extends Div implements AfterCompose {
this.task.addReportedHoursPropertyChangeListener(showingReportedHoursPropertyListener);
if ( showingMoneyCostBarPropertyListener == null ) {
showingMoneyCostBarPropertyListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ( isInPage() && !(task instanceof Milestone) ) {
updateCompletionMoneyCostBar();
}
showingMoneyCostBarPropertyListener = evt -> {
if ( isInPage() && !(task instanceof Milestone) ) {
updateCompletionMoneyCostBar();
}
};
}
@ -302,14 +276,7 @@ public class TaskComponent extends Div implements AfterCompose {
this.task.addMoneyCostBarPropertyChangeListener(showingMoneyCostBarPropertyListener);
if ( criticalPathPropertyListener == null ) {
criticalPathPropertyListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateClass();
}
};
criticalPathPropertyListener = evt -> updateClass();
}
this.task.addCriticalPathPropertyChangeListener(criticalPathPropertyListener);
@ -330,7 +297,6 @@ public class TaskComponent extends Div implements AfterCompose {
private final Task task;
private transient PropertyChangeListener propertiesListener;
private IConstraintViolationListener<GanttDate> taskViolationListener;
private String progressType;
@ -371,13 +337,7 @@ public class TaskComponent extends Div implements AfterCompose {
void doUpdatePosition(int leftX) {
GanttDate startBeforeMoving = this.task.getBeginDate();
final LocalDate newPosition = getMapper().toDate(leftX);
this.task.doPositionModifications(new IModifications() {
@Override
public void doIt(IUpdatablePosition position) {
position.moveTo(GanttDate.createFrom(newPosition));
}
});
this.task.doPositionModifications(position -> position.moveTo(GanttDate.createFrom(newPosition)));
boolean remainsInOriginalPosition = this.task.getBeginDate().equals(startBeforeMoving);
if ( remainsInOriginalPosition ) {
@ -417,7 +377,8 @@ public class TaskComponent extends Div implements AfterCompose {
* of the style
*/
protected void renderProperties(ContentRenderer renderer) throws IOException{
if( getColor() != null ) setStyle("background-color : " + getColor());
if ( getColor() != null )
setStyle("background-color : " + getColor());
setWidgetAttribute("movingTasksEnabled", ((Boolean)isMovingTasksEnabled()).toString());
setWidgetAttribute("resizingTasksEnabled", ((Boolean)isResizingTasksEnabled()).toString());

View file

@ -69,8 +69,6 @@ public class OnColumnsRowRendererTest {
private OnColumnsRowRenderer<DetailItem, Data> rowRenderer;
private DateTime start;
private List<Data> data;
private void givenOnDetailItemsRowRenderer(ICellForDetailItemRenderer<DetailItem, Data> cellRenderer) {
@ -82,7 +80,7 @@ public class OnColumnsRowRendererTest {
private void givenDetailItems() {
detailItems = new ArrayList<>();
start = new LocalDate(2010, 1, 1).toDateTimeAtStartOfDay().toDateTime();
DateTime start = new LocalDate(2010, 1, 1).toDateTimeAtStartOfDay().toDateTime();
DateTime current = start;
Period period = Period.months(2);
@ -107,32 +105,32 @@ public class OnColumnsRowRendererTest {
@Test(expected = NullPointerException.class)
public void itNeedsNotNullCellRenderer() {
OnColumnsRowRenderer.create(Data.class, null, new ArrayList<DetailItem>());
OnColumnsRowRenderer.create(Data.class, null, new ArrayList<>());
}
@Test(expected = NullPointerException.class)
public void itNeedsTheTypeAsClass() {
OnColumnsRowRenderer.create(null, createStub(), new ArrayList<DetailItem>());
OnColumnsRowRenderer.create(null, createStub(), new ArrayList<>());
}
@Test
public void itCanHaveEmptyDetailItems() {
OnColumnsRowRenderer.create(Data.class, createStub(), new ArrayList<DetailItem>());
OnColumnsRowRenderer.create(Data.class, createStub(), new ArrayList<>());
}
@Test
public void itCanInferTheGenericType() {
OnColumnsRowRenderer.create(new CellRenderer(), new ArrayList<DetailItem>());
OnColumnsRowRenderer.create(new CellRenderer(), new ArrayList<>());
}
@Test(expected = IllegalArgumentException.class)
public void ifComesFromRawTypeIsNotInferrable() {
OnColumnsRowRenderer.create(createStub(), new ArrayList<DetailItem>());
OnColumnsRowRenderer.create(createStub(), new ArrayList<>());
}
@Test(expected = IllegalArgumentException.class)
public void ifItNotShowsTheActualTypeIsNotInferrable() {
OnColumnsRowRenderer.create(new CellRendererNotInferable<Data>(), new ArrayList<DetailItem>());
OnColumnsRowRenderer.create(new CellRendererNotInferable<>(), new ArrayList<>());
}
@SuppressWarnings("serial")

View file

@ -38,7 +38,6 @@ import org.junit.Test;
import org.zkoss.ganttz.util.MutableTreeModel.IChildrenExtractor;
import org.zkoss.zul.TreeModel;
import org.zkoss.zul.event.TreeDataEvent;
import org.zkoss.zul.event.TreeDataListener;
/**
* @author Óscar González Fernández <ogonzalez@igalia.com>
@ -215,12 +214,7 @@ public class MutableTreeModelTest {
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class);
final ArrayList<TreeDataEvent> eventsFired = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
eventsFired.add(event);
}
});
model.addTreeDataListener(event -> eventsFired.add(event));
Prueba child1 = new Prueba();
Prueba child2 = new Prueba();
@ -240,12 +234,7 @@ public class MutableTreeModelTest {
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class);
final ArrayList<TreeDataEvent> eventsFired = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
eventsFired.add(event);
}
});
model.addTreeDataListener(event -> eventsFired.add(event));
Prueba child1 = new Prueba();
Prueba child2 = new Prueba();
@ -278,12 +267,7 @@ public class MutableTreeModelTest {
model.add(model.getRoot(), p1);
final ArrayList<TreeDataEvent> eventsFired = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
eventsFired.add(event);
}
});
model.addTreeDataListener(event -> eventsFired.add(event));
model.add(model.getRoot(), 0, Arrays.asList(new Prueba(), new Prueba()));
TreeDataEvent event = getLast(eventsFired);
@ -305,14 +289,9 @@ public class MutableTreeModelTest {
MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class);
final List<TreeDataEvent> events = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
events.add(event);
}
});
model.addTreeDataListener(event -> events.add(event));
model.add(model.getRoot(), new ArrayList<Prueba>());
model.add(model.getRoot(), new ArrayList<>());
assertThat(events.size(), equalTo(0));
}
@ -330,14 +309,11 @@ public class MutableTreeModelTest {
}
private IChildrenExtractor<Prueba> childrenFor(final Prueba parent, final Prueba... children) {
return new IChildrenExtractor<Prueba>() {
@Override
public List<Prueba> getChildren(Prueba p) {
if ( parent == p ) {
return Arrays.asList(children);
} else {
return Collections.emptyList();
}
return p -> {
if ( parent == p ) {
return Arrays.asList(children);
} else {
return Collections.emptyList();
}
};
}
@ -350,12 +326,7 @@ public class MutableTreeModelTest {
final Prueba child2 = new Prueba();
final List<TreeDataEvent> eventsFired = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
eventsFired.add(event);
}
});
model.addTreeDataListener(event -> eventsFired.add(event));
model.add(model.getRoot(), Collections.singletonList(newlyAdded), childrenFor(newlyAdded, child1, child2));
@ -396,12 +367,9 @@ public class MutableTreeModelTest {
final MutableTreeModel<Prueba> model = MutableTreeModel.create(Prueba.class);
final List<TreeDataEvent> removeEventsFired = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
if ( event.getType() == TreeDataEvent.INTERVAL_REMOVED ) {
removeEventsFired.add(event);
}
model.addTreeDataListener(event -> {
if ( event.getType() == TreeDataEvent.INTERVAL_REMOVED ) {
removeEventsFired.add(event);
}
});
@ -506,12 +474,7 @@ public class MutableTreeModelTest {
model.addToRoot(prueba3);
final ArrayList<TreeDataEvent> eventsFired = new ArrayList<>();
model.addTreeDataListener(new TreeDataListener() {
@Override
public void onChange(TreeDataEvent event) {
eventsFired.add(event);
}
});
model.addTreeDataListener(event -> eventsFired.add(event));
model.up(prueba2);
checkIsValid(getPreviousToLast(eventsFired), TreeDataEvent.INTERVAL_REMOVED, model.getRoot(), 0, 1);

View file

@ -38,6 +38,12 @@
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- Javax EL -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
</dependency>
<!-- Usertype.Core -->
<dependency>
<groupId>org.jadira.usertype</groupId>
@ -103,6 +109,12 @@
<artifactId>commons-math3</artifactId>
</dependency>
<!-- Commons Lang -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- Log4j -->
<dependency>
<groupId>org.slf4j</groupId>
@ -130,25 +142,22 @@
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
<profiles>
<profile>
<profile>
<!-- LiquiBase liquibase:update -->
<id>liquibase-update</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<id>liquibase-update</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>3.5.1</version>
<executions>
<execution>
@ -162,22 +171,22 @@
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- LiquiBase liquibase:updateSQL -->
<id>liquibase-updatesql</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<id>liquibase-updatesql</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>3.5.1</version>
<executions>
<execution>
@ -191,14 +200,14 @@
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<!-- Filtering -->
<resources>
<resource>
@ -206,6 +215,5 @@
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View file

@ -29,12 +29,11 @@ import java.lang.annotation.Target;
/**
* <p>
* It can be applied to a {@link IDataBootstrap} to indicate the order in which
* it will be executed. It's ensured that if a data bootstrap has a priority
* value greater than another one it will be executed before. If two data
* bootstraps have the same priority value the order is unspecified. If a data
* bootstrap doesn't have this annotation it's like it would have a value of
* zero.
* It can be applied to a {@link IDataBootstrap} to indicate the order in which it will be executed.
* It's ensured that if a data bootstrap has a priority value greater than another one it will be executed before.
*
* If two data bootstraps have the same priority value the order is unspecified.
* If a data bootstrap doesn't have this annotation it's like it would have a value of zero.
* </p>
*
* It accepts negative values.
@ -46,5 +45,5 @@ import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BootstrapOrder {
public int value();
int value();
}

View file

@ -29,11 +29,11 @@ import org.springframework.stereotype.Repository;
/**
* Dao for {@link AdvanceAssignment}
*
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class AdvanceAssignmentDAO extends
GenericDAOHibernate<AdvanceAssignment, Long> implements
IAdvanceAssignmentDAO {
public class AdvanceAssignmentDAO extends GenericDAOHibernate<AdvanceAssignment, Long>
implements IAdvanceAssignmentDAO {
}

View file

@ -44,7 +44,8 @@ public abstract class AdvanceAssignment extends BaseEntity {
public void setReportGlobalAdvance(boolean reportGlobalAdvance) {
this.reportGlobalAdvance = reportGlobalAdvance;
if (this.orderElement != null) {
if ( this.orderElement != null ) {
this.orderElement.markAsDirtyLastAdvanceMeasurementForSpreading();
}
}
@ -63,12 +64,12 @@ public abstract class AdvanceAssignment extends BaseEntity {
public void setAdvanceType(AdvanceType advanceType) {
AdvanceType oldType = this.advanceType;
if (advanceType != null) {
if ( advanceType != null ) {
this.advanceType = advanceType;
}
if (oldType != null && advanceType != null) {
changeAdvanceTypeInParents(oldType, this.advanceType, this);
if ( oldType != null && advanceType != null ) {
changeAdvanceTypeInParents(oldType, this);
}
}
@ -77,17 +78,16 @@ public abstract class AdvanceAssignment extends BaseEntity {
return this.advanceType;
}
public void changeAdvanceTypeInParents(final AdvanceType oldType,
AdvanceType newType, AdvanceAssignment advance) {
if (getOrderElement() != null) {
public void changeAdvanceTypeInParents(final AdvanceType oldType, AdvanceAssignment advance) {
if ( getOrderElement() != null ) {
OrderLineGroup parent = getOrderElement().getParent();
if (parent != null) {
IndirectAdvanceAssignment oldIndirect = parent
.getIndirectAdvanceAssignment(oldType);
if (oldIndirect != null) {
if ( parent != null ) {
IndirectAdvanceAssignment oldIndirect = parent.getIndirectAdvanceAssignment(oldType);
if ( oldIndirect != null ) {
parent.removeIndirectAdvanceAssignment(oldType);
IndirectAdvanceAssignment newIndirect = advance
.createIndirectAdvanceFor(parent);
IndirectAdvanceAssignment newIndirect = advance.createIndirectAdvanceFor(parent);
parent.addIndirectAdvanceAssignment(newIndirect);
}
}
@ -99,6 +99,7 @@ public abstract class AdvanceAssignment extends BaseEntity {
result.setAdvanceType(getAdvanceType());
result.setOrderElement(parent);
result.setReportGlobalAdvance(noOtherGlobalReportingAdvance(parent));
return create(result);
}

View file

@ -35,7 +35,6 @@ import org.libreplan.business.common.BaseEntity;
import org.libreplan.business.common.IHumanIdentifiable;
import org.libreplan.business.common.Registry;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.orders.entities.OrderElement;
/**
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
@ -92,7 +91,7 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
private Boolean qualityForm = false;
private IAdvanceTypeDAO avanceTypeDAO = Registry.getAdvanceTypeDao();
private IAdvanceTypeDAO avancedTypeDAO = Registry.getAdvanceTypeDao();
private boolean readOnly = false;
@ -100,12 +99,16 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
* Constructor for hibernate. Do not use!
*/
public AdvanceType() {
}
private AdvanceType(String unitName, BigDecimal defaultMaxValue,
boolean updatable, BigDecimal unitPrecision, boolean active,
boolean percentage, boolean qualityForm) {
private AdvanceType(String unitName,
BigDecimal defaultMaxValue,
boolean updatable,
BigDecimal unitPrecision,
boolean active,
boolean percentage,
boolean qualityForm) {
this.unitName = unitName;
this.percentage = percentage;
setDefaultMaxValue(defaultMaxValue);
@ -127,16 +130,16 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
}
public void setDefaultMaxValue(BigDecimal defaultMaxValue) {
if (defaultMaxValue.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException(
"The maximum value must be greater than 0");
if ( defaultMaxValue.compareTo(BigDecimal.ZERO) <= 0 ) {
throw new IllegalArgumentException("The maximum value must be greater than 0");
}
if (percentage) {
if (defaultMaxValue.compareTo(new BigDecimal(100)) > 0) {
throw new IllegalArgumentException(
"The maximum value for percentage is 100");
if ( percentage ) {
if ( defaultMaxValue.compareTo(new BigDecimal(100)) > 0 ) {
throw new IllegalArgumentException("The maximum value for percentage is 100");
}
}
this.defaultMaxValue = defaultMaxValue;
this.defaultMaxValue.setScale(2, BigDecimal.ROUND_HALF_UP);
}
@ -171,45 +174,37 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
}
public String getType() {
if (isUpdatable()) {
if ( isUpdatable() ) {
return _("User");
}
if (isQualityForm()) {
if ( isQualityForm() ) {
return _("Quality form");
}
return _("Predefined");
}
public void doPropagateAdvaceToParent(OrderElement orderElement) {
}
public boolean isPrecisionValid(BigDecimal precision) {
if ((this.defaultMaxValue == null) || (precision == null)) {
return true;
}
return this.defaultMaxValue.compareTo(precision) >= 0;
return (this.defaultMaxValue == null) || (precision == null) || this.defaultMaxValue.compareTo(precision) >= 0;
}
public boolean isDefaultMaxValueValid(BigDecimal defaultMaxValue) {
if ((this.unitPrecision == null) || (defaultMaxValue == null)) {
return true;
}
return this.unitPrecision.compareTo(defaultMaxValue) <= 0;
return (this.unitPrecision == null) ||
(defaultMaxValue == null) ||
this.unitPrecision.compareTo(defaultMaxValue) <= 0;
}
public static boolean equivalentInDB(AdvanceType type, AdvanceType otherType) {
if (type == null || type.getId() == null || otherType == null
|| otherType.getId() == null) {
return false;
}
return type.getId().equals(otherType.getId());
return !(type == null || type.getId() == null || otherType == null || otherType.getId() == null) &&
type.getId().equals(otherType.getId());
}
public void setPercentage(boolean percentage) {
if (percentage) {
if ( percentage ) {
defaultMaxValue = new BigDecimal(100);
}
this.percentage = percentage;
}
@ -228,21 +223,23 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
@AssertTrue(message = "progress type marked as quality form but is updatable")
public boolean isIfIsQualityFormIsNotUpdatableConstraint() {
if (isQualityForm()) {
if (isUpdatable()) {
if ( isQualityForm() ) {
if ( isUpdatable() ) {
return false;
}
}
return true;
}
@AssertTrue(message = "default maximum value of percentage progress type must be 100")
public boolean isDefaultMaxValueMustBe100ForPercentageConstraint() {
if (percentage) {
if (defaultMaxValue.compareTo(new BigDecimal(100)) != 0) {
if ( percentage ) {
if ( defaultMaxValue.compareTo(new BigDecimal(100)) != 0 ) {
return false;
}
}
return true;
}
@ -253,11 +250,12 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
@AssertTrue(message = "progress type name is already in use")
public boolean isUniqueNameConstraint() {
if (StringUtils.isBlank(unitName)) {
if ( StringUtils.isBlank(unitName) ) {
return true;
}
if (isNewObject()) {
return !avanceTypeDAO.existsByNameInAnotherTransaction(unitName);
if ( isNewObject() ) {
return !avancedTypeDAO.existsByNameInAnotherTransaction(unitName);
} else {
return checkNotExistsOrIsTheSame();
}
@ -265,8 +263,8 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
private boolean checkNotExistsOrIsTheSame() {
try {
AdvanceType advanceType = avanceTypeDAO
.findUniqueByNameInAnotherTransaction(unitName);
AdvanceType advanceType = avancedTypeDAO.findUniqueByNameInAnotherTransaction(unitName);
return advanceType.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -275,10 +273,7 @@ public class AdvanceType extends BaseEntity implements IHumanIdentifiable{
@AssertTrue(message = "default maximum value must be greater than precision value")
public boolean isDefaultMaxValueGreaterThanPrecisionConstraint() {
if (defaultMaxValue.compareTo(unitPrecision) == -1) {
return false;
}
return true;
return defaultMaxValue.compareTo(unitPrecision) != -1;
}
public void setReadOnly(boolean readOnly) {

View file

@ -44,9 +44,8 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class CalendarExceptionTypeDAO extends
IntegrationEntityDAO<CalendarExceptionType> implements
ICalendarExceptionTypeDAO {
public class CalendarExceptionTypeDAO extends IntegrationEntityDAO<CalendarExceptionType>
implements ICalendarExceptionTypeDAO {
@Override
public boolean existsByName(CalendarExceptionType type) {
@ -54,6 +53,7 @@ public class CalendarExceptionTypeDAO extends
c.add(Restrictions.eq("name", type.getName()));
List list = c.list();
return (list.size() == 1);
}
@ -70,6 +70,7 @@ public class CalendarExceptionTypeDAO extends
private List<CalendarException> getCalendarExceptions(CalendarExceptionType type) {
Criteria c = getSession().createCriteria(CalendarException.class);
c.add(Restrictions.eq("type.id", type.getId()));
return c.list();
}
@ -92,16 +93,15 @@ public class CalendarExceptionTypeDAO extends
@Override
@Transactional(readOnly = true)
public CalendarExceptionType findUniqueByName(String name) throws InstanceNotFoundException {
if (StringUtils.isBlank(name)) {
if ( StringUtils.isBlank(name) ) {
throw new InstanceNotFoundException(null, CalendarExceptionType.class.getName());
}
CalendarExceptionType calendarExceptionType = (CalendarExceptionType) getSession().createCriteria(
CalendarExceptionType.class).add(
Restrictions.eq("name", name.trim()).ignoreCase())
.uniqueResult();
CalendarExceptionType calendarExceptionType = (CalendarExceptionType) getSession()
.createCriteria(CalendarExceptionType.class)
.add(Restrictions.eq("name", name.trim()).ignoreCase()).uniqueResult();
if (calendarExceptionType == null) {
if ( calendarExceptionType == null ) {
throw new InstanceNotFoundException(name, CalendarExceptionType.class.getName());
} else {
return calendarExceptionType;
@ -111,8 +111,7 @@ public class CalendarExceptionTypeDAO extends
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public CalendarExceptionType findUniqueByNameAnotherTransaction(String name)
throws InstanceNotFoundException {
public CalendarExceptionType findUniqueByNameAnotherTransaction(String name) throws InstanceNotFoundException {
return findUniqueByName(name);
}

View file

@ -47,35 +47,44 @@ public class CalendarBootstrap implements ICalendarBootstrap {
@Override
@Transactional
public void loadRequiredData() {
if (calendarExceptionTypeDAO.getAll().size() == 0) {
for (PredefinedCalendarExceptionTypes type : PredefinedCalendarExceptionTypes
.values()) {
CalendarExceptionType calendarExceptionType = type
.getCalendarExceptionType();
calendarExceptionType
.setCode(entitySequenceDAO
.getNextEntityCodeWithoutTransaction(EntityNameEnum.CALENDAR_EXCEPTION_TYPE));
if ( calendarExceptionTypeDAO.getAll().size() == 0 ) {
for (PredefinedCalendarExceptionTypes type : PredefinedCalendarExceptionTypes.values()) {
CalendarExceptionType calendarExceptionType = type.getCalendarExceptionType();
calendarExceptionType.setCode(
entitySequenceDAO.getNextEntityCodeWithoutTransaction(EntityNameEnum.CALENDAR_EXCEPTION_TYPE));
calendarExceptionType.setCodeAutogenerated(true);
calendarExceptionTypeDAO.save(calendarExceptionType);
}
}
if (!calendarExceptionTypeDAO.existsByName(PredefinedCalendarExceptionTypes.NOT_WORKING_DAY
.getCalendarExceptionType())) {
CalendarExceptionType calendarExceptionType = PredefinedCalendarExceptionTypes.NOT_WORKING_DAY
.getCalendarExceptionType();
calendarExceptionType
.setCode(entitySequenceDAO
.getNextEntityCodeWithoutTransaction(EntityNameEnum.CALENDAR_EXCEPTION_TYPE));
boolean condition = calendarExceptionTypeDAO
.existsByName(PredefinedCalendarExceptionTypes.NOT_WORKING_DAY.getCalendarExceptionType());
if ( !condition ) {
CalendarExceptionType calendarExceptionType =
PredefinedCalendarExceptionTypes.NOT_WORKING_DAY.getCalendarExceptionType();
calendarExceptionType.setCode(
entitySequenceDAO.getNextEntityCodeWithoutTransaction(EntityNameEnum.CALENDAR_EXCEPTION_TYPE));
calendarExceptionType.setCodeAutogenerated(true);
calendarExceptionTypeDAO.save(calendarExceptionType);
}
if (!calendarExceptionTypeDAO.existsByName(PredefinedCalendarExceptionTypes.WORKING_DAY
.getCalendarExceptionType())) {
CalendarExceptionType calendarExceptionType = PredefinedCalendarExceptionTypes.WORKING_DAY
.getCalendarExceptionType();
calendarExceptionType
.setCode(entitySequenceDAO
.getNextEntityCodeWithoutTransaction(EntityNameEnum.CALENDAR_EXCEPTION_TYPE));
condition = calendarExceptionTypeDAO
.existsByName(PredefinedCalendarExceptionTypes.WORKING_DAY.getCalendarExceptionType());
if ( !condition ) {
CalendarExceptionType calendarExceptionType =
PredefinedCalendarExceptionTypes.WORKING_DAY.getCalendarExceptionType();
calendarExceptionType.setCode(
entitySequenceDAO.getNextEntityCodeWithoutTransaction(EntityNameEnum.CALENDAR_EXCEPTION_TYPE));
calendarExceptionType.setCodeAutogenerated(true);
calendarExceptionTypeDAO.save(calendarExceptionType);
}

View file

@ -39,15 +39,14 @@ import org.libreplan.business.common.Registry;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.workingday.EffortDuration;
import org.libreplan.business.workingday.EffortDuration.Granularity;
import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
/**
* Type of an exception day.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class CalendarExceptionType extends IntegrationEntity implements
IHumanIdentifiable {
public class CalendarExceptionType extends IntegrationEntity implements IHumanIdentifiable {
private String name;
@ -62,34 +61,34 @@ public class CalendarExceptionType extends IntegrationEntity implements
return create(new CalendarExceptionType());
}
public static CalendarExceptionType create(String name,
CalendarExceptionTypeColor color,
Boolean notAssignable) {
public static CalendarExceptionType create(String name, CalendarExceptionTypeColor color, Boolean notAssignable) {
return create(new CalendarExceptionType(name, color, notAssignable));
}
public static CalendarExceptionType create(String code, String name,
CalendarExceptionTypeColor color, Boolean notAssignable) {
return create(new CalendarExceptionType(name, color, notAssignable),
code);
public static CalendarExceptionType create(
String code, String name, CalendarExceptionTypeColor color, Boolean notAssignable) {
return create(new CalendarExceptionType(name, color, notAssignable), code);
}
public static CalendarExceptionType create(String code, String name,
CalendarExceptionTypeColor color, Boolean notAssignable,
Boolean updatable) {
CalendarExceptionType calendarExceptionType = new CalendarExceptionType(
name, color, notAssignable);
public static CalendarExceptionType create(
String code, String name, CalendarExceptionTypeColor color, Boolean notAssignable, Boolean updatable) {
CalendarExceptionType calendarExceptionType = new CalendarExceptionType(name, color, notAssignable);
calendarExceptionType.updatable = updatable;
return create(calendarExceptionType,
code);
return create(calendarExceptionType, code);
}
public static CalendarExceptionType create(String code, String name,
CalendarExceptionTypeColor color, Boolean notAssignable,
EffortDuration duration) {
CalendarExceptionType calendarExceptionType = new CalendarExceptionType(
name, color, notAssignable);
public static CalendarExceptionType create(String code,
String name,
CalendarExceptionTypeColor color,
Boolean notAssignable,
EffortDuration duration) {
CalendarExceptionType calendarExceptionType = new CalendarExceptionType(name, color, notAssignable);
calendarExceptionType.setDuration(duration);
return create(calendarExceptionType, code);
}
@ -97,16 +96,13 @@ public class CalendarExceptionType extends IntegrationEntity implements
* Constructor for hibernate. Do not use!
*/
protected CalendarExceptionType() {
}
public CalendarExceptionType(String name, CalendarExceptionTypeColor color,
Boolean notOverAssignable) {
public CalendarExceptionType(String name, CalendarExceptionTypeColor color, Boolean notOverAssignable) {
this.name = name;
this.color = color;
this.capacity = Capacity.zero();
this.capacity = this.capacity.overAssignableWithoutLimit(!BooleanUtils
.isTrue(notOverAssignable));
this.capacity = this.capacity.overAssignableWithoutLimit(!BooleanUtils.isTrue(notOverAssignable));
}
public boolean isUpdatable() {
@ -148,8 +144,7 @@ public class CalendarExceptionType extends IntegrationEntity implements
}
public void setOverAssignable(Boolean overAssignable) {
this.capacity = capacity.overAssignableWithoutLimit(BooleanUtils
.isTrue(overAssignable));
this.capacity = capacity.overAssignableWithoutLimit(BooleanUtils.isTrue(overAssignable));
}
public String getOverAssignableStr() {
@ -161,12 +156,14 @@ public class CalendarExceptionType extends IntegrationEntity implements
}
private String asString(EffortDuration duration) {
if (duration == null) {
if ( duration == null ) {
return "";
}
EnumMap<Granularity, Integer> values = duration.decompose();
Integer hours = values.get(Granularity.HOURS);
Integer minutes = values.get(Granularity.MINUTES);
return hours + ":" + minutes;
}
@ -181,18 +178,18 @@ public class CalendarExceptionType extends IntegrationEntity implements
@AssertTrue(message = "name is already used")
public boolean isUniqueNameConstraint() {
if (StringUtils.isBlank(name)) {
if ( StringUtils.isBlank(name) ) {
return true;
}
ICalendarExceptionTypeDAO calendarExceptionTypeDAO = getIntegrationEntityDAO();
if (isNewObject()) {
return !calendarExceptionTypeDAO.existsByNameAnotherTransaction(
name);
if ( isNewObject() ) {
return !calendarExceptionTypeDAO.existsByNameAnotherTransaction(name);
} else {
try {
CalendarExceptionType calendarExceptionType = calendarExceptionTypeDAO
.findUniqueByNameAnotherTransaction(name);
CalendarExceptionType calendarExceptionType =
calendarExceptionTypeDAO.findUniqueByNameAnotherTransaction(name);
return calendarExceptionType.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;

View file

@ -42,8 +42,7 @@ public enum CalendarExceptionTypeColor {
private final String colorOwnException;
private final String colorDerivedException;
private CalendarExceptionTypeColor(String name, String colorOwnException,
String colorDerivedException) {
CalendarExceptionTypeColor(String name, String colorOwnException, String colorDerivedException) {
this.name = name;
this.colorOwnException = colorOwnException;
this.colorDerivedException = colorDerivedException;

View file

@ -32,14 +32,14 @@ import org.springframework.transaction.annotation.Transactional;
@Service
public class AdHocTransactionService implements IAdHocTransactionService {
private static <T> T proxy(IAdHocTransactionService transactionService,
boolean readOnly,
Class<T> interfaceClass,
T interfaceObject) {
private static <T> T proxy(
IAdHocTransactionService transactionService, boolean readOnly, Class<T> interfaceClass, T interfaceObject) {
Class<?>[] interfaces = { interfaceClass };
return interfaceClass.cast(Proxy.newProxyInstance(interfaceClass
.getClassLoader(), interfaces, createHandler(interfaceObject,
transactionService, readOnly)));
return interfaceClass.cast(Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
interfaces,
createHandler(interfaceObject, transactionService, readOnly)));
}
/**
@ -50,8 +50,9 @@ public class AdHocTransactionService implements IAdHocTransactionService {
* @param interfaceObject
* @return
*/
public static <T> T readOnlyProxy(IAdHocTransactionService transactionService,
Class<T> interfaceClass, T interfaceObject) {
public static <T> T readOnlyProxy(
IAdHocTransactionService transactionService, Class<T> interfaceClass, T interfaceObject) {
return proxy(transactionService, true, interfaceClass, interfaceObject);
}
@ -63,45 +64,35 @@ public class AdHocTransactionService implements IAdHocTransactionService {
* @param interfaceObject
* @return
*/
public static <T> T proxy(IAdHocTransactionService transactionService,
Class<T> interfaceClass, T interfaceObject) {
public static <T> T proxy(IAdHocTransactionService transactionService, Class<T> interfaceClass, T interfaceObject) {
return proxy(transactionService, false, interfaceClass, interfaceObject);
}
private static InvocationHandler createHandler(final Object originalObject,
final IAdHocTransactionService transactionService,
final boolean readOnly) {
return new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method,
final Object[] args) throws Throwable {
IOnTransaction<Object> onTransaction = createOnTransaction(originalObject, method, args);
try {
if (readOnly) {
return transactionService
.runOnReadOnlyTransaction(onTransaction);
} else {
return transactionService.runOnTransaction(onTransaction);
}
} catch (RuntimeException e) {
throw e.getCause();
private static InvocationHandler createHandler(
final Object originalObject, final IAdHocTransactionService transactionService, final boolean readOnly) {
return (proxy, method, args) -> {
IOnTransaction<Object> onTransaction = createOnTransaction(originalObject, method, args);
try {
if ( readOnly ) {
return transactionService.runOnReadOnlyTransaction(onTransaction);
} else {
return transactionService.runOnTransaction(onTransaction);
}
} catch (RuntimeException e) {
throw e.getCause();
}
};
}
private static IOnTransaction<Object> createOnTransaction(
final Object originalObject, final Method method,
final Object[] args) {
return new IOnTransaction<Object>() {
final Object originalObject, final Method method, final Object[] args) {
@Override
public Object execute() {
try {
return method.invoke(originalObject, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
return () -> {
try {
return method.invoke(originalObject, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}

View file

@ -57,15 +57,16 @@ public abstract class BaseEntity implements INewObject {
* @param entities
* @return entities grouped by id
*/
public static <T extends BaseEntity> Map<Long, Set<T>> byId(
Collection<? extends T> entities) {
Map<Long, Set<T>> result = new HashMap<Long, Set<T>>();
public static <T extends BaseEntity> Map<Long, Set<T>> byId(Collection<? extends T> entities) {
Map<Long, Set<T>> result = new HashMap<>();
for (T each : entities) {
if ( !result.containsKey(each.getId()) ) {
result.put(each.getId(), new HashSet<T>());
result.put(each.getId(), new HashSet<>());
}
result.get(each.getId()).add(each);
}
return result;
}
@ -89,7 +90,7 @@ public abstract class BaseEntity implements INewObject {
}
public Long getVersion() {
if (isNewObject()) {
if ( isNewObject() ) {
return null;
}
@ -119,6 +120,7 @@ public abstract class BaseEntity implements INewObject {
protected static <T extends BaseEntity> T create(T baseEntity) {
baseEntity.setNewObject(true);
return baseEntity;
}
@ -146,6 +148,7 @@ public abstract class BaseEntity implements INewObject {
} catch (Exception e) {
final String message = "error doing toString";
LOG.error(message, e);
return message;
}
}

View file

@ -29,14 +29,16 @@ import org.apache.commons.lang3.BooleanUtils;
* Currently we have three options:
* <ul>
* <li>Enable/Disable the warning changing default password</li>
* <li>Enable/Disable default users (such as wsreader, wswriter,
* wssubcontracting, manager, hresources, outsourcing and reports)</li>
*
* <li>Enable/Disable default users
* (such as wsreader, wswriter, wssubcontracting, manager, hresources, outsourcing and reports)</li>
*
* <li>Enable/Disable E-mail sending functionality</li>
* </ul>
*
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
* @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
public class Configuration {
@ -57,12 +59,10 @@ public class Configuration {
}
/**
* It returns the current state of the default passwords control in order to
* show or not warnings.
* It returns the current state of the default passwords control in order to show or not warnings.
*/
public static Boolean isDefaultPasswordsControl() {
return singleton.getDefaultPasswordsControl() != null ? singleton
.getDefaultPasswordsControl() : true;
return singleton.getDefaultPasswordsControl() != null ? singleton.getDefaultPasswordsControl() : true;
}
public Boolean getDefaultPasswordsControl() {
return defaultPasswordsControl;

View file

@ -33,9 +33,8 @@ import org.libreplan.business.common.exceptions.InstanceNotFoundException;
/**
* Base class for all entities to be sent/received to/from other applications.
* These entities have a "code" attribute, which unlike "id" is unique among
* the applications to be integrated ("id" is only unique inside
* "libreplan").
* These entities have a "code" attribute, which unlike "id" is unique among the applications to be integrated
* ("id" is only unique inside "libreplan").
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
*/
@ -63,9 +62,7 @@ public abstract class IntegrationEntity extends BaseEntity {
* specifying a specific code (e.g. provided by the end-user or an external
* application).
*/
protected static <T extends IntegrationEntity> T create(
T integrationEntity, String code) {
protected static <T extends IntegrationEntity> T create(T integrationEntity, String code) {
BaseEntity.create(integrationEntity);
integrationEntity.setCode(code);
@ -78,8 +75,7 @@ public abstract class IntegrationEntity extends BaseEntity {
* automatically generate a code. This is a Template method which delegates
* code generation by calling on <code>generateCode()</code>.
*/
protected static <T extends IntegrationEntity> T create(
T integrationEntity) {
protected static <T extends IntegrationEntity> T create(T integrationEntity) {
BaseEntity.create(integrationEntity);
integrationEntity.setCode(generateCode());
@ -110,21 +106,20 @@ public abstract class IntegrationEntity extends BaseEntity {
@AssertTrue(message="code is already used")
public boolean isUniqueCodeConstraint() {
/* Check if it makes sense to check the constraint .*/
if (!iCodeSpecified()) {
// Check if it makes sense to check the constraint
if ( !iCodeSpecified() ) {
return true;
}
/* Check the constraint. */
IIntegrationEntityDAO<? extends IntegrationEntity>
integrationEntityDAO = findIntegrationEntityDAO();
IIntegrationEntityDAO<? extends IntegrationEntity> integrationEntityDAO = findIntegrationEntityDAO();
if (isNewObject()) {
if ( isNewObject() ) {
return !integrationEntityDAO.existsByCodeAnotherTransaction(code);
} else {
try {
IntegrationEntity entity =
integrationEntityDAO.findByCodeAnotherTransaction(code);
IntegrationEntity entity = integrationEntityDAO.findByCodeAnotherTransaction(code);
return entity.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -142,14 +137,14 @@ public abstract class IntegrationEntity extends BaseEntity {
protected String getFirstRepeatedCode(
Set<? extends IntegrationEntity> entities) {
Set<String> codes = new HashSet<String>();
Set<String> codes = new HashSet<>();
for (IntegrationEntity e : entities) {
String code = e.getCode();
if (!StringUtils.isBlank(code)) {
if (codes.contains(code.toLowerCase())) {
if ( !StringUtils.isBlank(code) ) {
if ( codes.contains(code.toLowerCase()) ) {
return code;
} else {
codes.add(code.toLowerCase());
@ -165,20 +160,17 @@ public abstract class IntegrationEntity extends BaseEntity {
/**
* It returns the DAO of this entity.
*/
protected abstract IIntegrationEntityDAO<? extends IntegrationEntity>
getIntegrationEntityDAO();
protected abstract IIntegrationEntityDAO<? extends IntegrationEntity> getIntegrationEntityDAO();
private IIntegrationEntityDAO<? extends IntegrationEntity>
findIntegrationEntityDAO() {
private IIntegrationEntityDAO<? extends IntegrationEntity> findIntegrationEntityDAO() {
IIntegrationEntityDAO<? extends IntegrationEntity>
integrationEntityDAO = getIntegrationEntityDAO();
IIntegrationEntityDAO<? extends IntegrationEntity> integrationEntityDAO = getIntegrationEntityDAO();
if (!integrationEntityDAO.getEntityClass().isAssignableFrom(
this.getClass())) {
throw new RuntimeException(this.getClass().getName() + "::" +
"getIntegrationEntityDAO returns an incompatible " +
"DAO: " + integrationEntityDAO.getClass().getName());
if ( !integrationEntityDAO.getEntityClass().isAssignableFrom(this.getClass())) {
throw new RuntimeException(
this.getClass().getName() +
":: getIntegrationEntityDAO returns an incompatible DAO: " +
integrationEntityDAO.getClass().getName());
} else {
return integrationEntityDAO;
}

View file

@ -69,11 +69,10 @@ import org.libreplan.business.workreports.daos.IWorkReportTypeDAO;
import org.springframework.beans.factory.annotation.Autowired;
/**
* A registry, AKA service locator, for objects in which dependency injection
* (DI) is not directly supported by Spring (e.g. entities) must use this class
* to access DAOs. For the rest of classes (e.g. services, tests, etc.), Spring
* DI is a more convenient option. The DAOs or services are added to the
* registry as needed.
* A registry, AKA service locator, for objects in which dependency injection (DI) is not directly supported by Spring
* (e.g. entities) must use this class to access DAOs.
* For the rest of classes (e.g. services, tests, etc.), Spring DI is a more convenient option.
* The DAOs or services are added to the registry as needed.
*
* @author Óscar González Fernández <ogonzalez@igalia.com>
* @author Fernando Bellas Permuy <fbellas@udc.es>
@ -93,7 +92,6 @@ public class Registry {
private ICriterionTypeDAO criterionTypeDAO;
@Autowired
private IUserDAO userDAO;
@Autowired
@ -163,8 +161,7 @@ public class Registry {
private ICriterionSatisfactionDAO criterionSatisfactionDAO;
@Autowired
private IResourcesCostCategoryAssignmentDAO
resourcesCostCategoryAssignmentDAO;
private IResourcesCostCategoryAssignmentDAO resourcesCostCategoryAssignmentDAO;
@Autowired
private IOrderElementTemplateDAO orderElementTemplateDAO;
@ -336,11 +333,8 @@ public class Registry {
return getInstance().criterionSatisfactionDAO;
}
public static IResourcesCostCategoryAssignmentDAO
getResourcesCostCategoryAssignmentDAO() {
public static IResourcesCostCategoryAssignmentDAO getResourcesCostCategoryAssignmentDAO() {
return getInstance().resourcesCostCategoryAssignmentDAO;
}
public static IOrderElementTemplateDAO getOrderElementTemplateDAO() {
@ -395,7 +389,9 @@ public class Registry {
return getInstance().issueLogDAO;
}
public static IRiskLogDAO getRiskLogDAO() {return getInstance().riskLogDAO;}
public static IRiskLogDAO getRiskLogDAO() {
return getInstance().riskLogDAO;
}
public static IExpenseSheetLineDAO getExpenseSheetLineDAO() {
return getInstance().expenseSheetLineDAO;

View file

@ -27,15 +27,13 @@ import java.util.List;
import org.apache.commons.lang3.Validate;
import org.hibernate.NonUniqueResultException;
import org.hibernate.criterion.Restrictions;
import org.libreplan.business.common.IAdHocTransactionService;
import org.libreplan.business.common.entities.EntityNameEnum;
import org.libreplan.business.common.entities.EntitySequence;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.i18n.I18nHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@ -46,11 +44,7 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class EntitySequenceDAO extends
GenericDAOHibernate<EntitySequence, Long> implements IEntitySequenceDAO {
@Autowired
private IAdHocTransactionService transactionService;
public class EntitySequenceDAO extends GenericDAOHibernate<EntitySequence, Long> implements IEntitySequenceDAO {
@Override
public List<EntitySequence> getAll() {
@ -59,27 +53,23 @@ public class EntitySequenceDAO extends
@Override
@SuppressWarnings("unchecked")
public List<EntitySequence> findEntitySquencesNotIn(
List<EntitySequence> entitySequences) {
List<Long> entitySequenceIds = new ArrayList<Long>();
public List<EntitySequence> findEntitySquencesNotIn(List<EntitySequence> entitySequences) {
List<Long> entitySequenceIds = new ArrayList<>();
for (EntitySequence entitySequence : entitySequences) {
if (!entitySequence.isNewObject()) {
if ( !entitySequence.isNewObject() ) {
entitySequenceIds.add(entitySequence.getId());
}
}
return getSession().createCriteria(EntitySequence.class).add(
Restrictions.not(Restrictions.in("id", entitySequenceIds)))
.list();
return getSession().createCriteria(EntitySequence.class)
.add(Restrictions.not(Restrictions.in("id", entitySequenceIds))).list();
}
@Override
public void remove(final EntitySequence entitySequence)
throws InstanceNotFoundException, IllegalArgumentException {
if (entitySequence.getLastValue() > 0) {
public void remove(final EntitySequence entitySequence) throws InstanceNotFoundException, IllegalArgumentException {
if ( entitySequence.getLastValue() > 0 ) {
throw new IllegalArgumentException(
I18nHelper
._("Entity Sequence cannot be deleted. Entity Sequence already in use"));
I18nHelper._("Entity Sequence cannot be deleted. Entity Sequence already in use"));
}
remove(entitySequence.getId());
@ -88,15 +78,15 @@ public class EntitySequenceDAO extends
@Override
public EntitySequence getActiveEntitySequence(EntityNameEnum entityName)
throws InstanceNotFoundException, NonUniqueResultException {
EntitySequence entitySequence = (EntitySequence) getSession()
.createCriteria(
EntitySequence.class).add(
Restrictions.eq("entityName", entityName)).add(
Restrictions.eq("active", true)).uniqueResult();
if (entitySequence == null) {
throw new InstanceNotFoundException(entitySequence,
"Entity sequence not exist");
EntitySequence entitySequence = (EntitySequence) getSession().createCriteria(EntitySequence.class)
.add(Restrictions.eq("entityName", entityName))
.add(Restrictions.eq("active", true)).uniqueResult();
if ( entitySequence == null ) {
throw new InstanceNotFoundException(entitySequence, "Entity sequence not exist");
}
return entitySequence;
}
@ -115,17 +105,14 @@ public class EntitySequenceDAO extends
do {
entitySequence.incrementLastValue();
code = entitySequence.getCode();
} while (entityName.getIntegrationEntityDAO()
.existsByCode(code));
} while (entityName.getIntegrationEntityDAO().existsByCode(code));
save(entitySequence);
return code;
} catch (HibernateOptimisticLockingFailureException e) {
} catch (HibernateOptimisticLockingFailureException |
InstanceNotFoundException |
NonUniqueResultException e) {
// Do nothing (optimistic approach 5 attempts)
} catch (InstanceNotFoundException e) {
} catch (NonUniqueResultException e) {
}
}
@ -133,12 +120,11 @@ public class EntitySequenceDAO extends
}
@Override
public boolean existOtherActiveSequenceByEntityNameForNewObject(
EntitySequence entitySequence) {
public boolean existOtherActiveSequenceByEntityNameForNewObject(EntitySequence entitySequence) {
Validate.notNull(entitySequence);
try {
EntitySequence t = getActiveEntitySequence(entitySequence
.getEntityName());
EntitySequence t = getActiveEntitySequence(entitySequence.getEntityName());
return (t != null && t != entitySequence);
} catch (InstanceNotFoundException e) {
return false;
@ -149,15 +135,14 @@ public class EntitySequenceDAO extends
@Override
public Integer getNumberOfDigitsCode(EntityNameEnum entityName) {
int numberOfDigits = 5;
int numberOfDigits;
try {
EntitySequence entitySequence = getActiveEntitySequence(entityName);
numberOfDigits = entitySequence.getNumberOfDigits();
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
} catch (NonUniqueResultException e) {
} catch (InstanceNotFoundException | NonUniqueResultException e) {
throw new RuntimeException(e);
}
return numberOfDigits;
}
}

View file

@ -41,17 +41,17 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* An implementation of <code>IGenericDao</code> based on Hibernate's native
* API. Concrete DAOs must extend directly from this class. This constraint is
* imposed by the constructor of this class that must infer the type of the
* entity from the declaration of the concrete DAO.
* An implementation of <code>IGenericDao</code> based on Hibernate's native API.
* Concrete DAOs must extend directly from this class.
* This constraint is imposed by the constructor of this class that must infer the
* type of the entity from the declaration of the concrete DAO.
* <p/>
* This class autowires a <code>SessionFactory</code> bean and allows to
* implement DAOs with Hibernate's native API. Subclasses access Hibernate's
* <code>Session</code> by calling on <code>getSession()</code> method.
* This class autowires a <code>SessionFactory</code> bean and allows to implement DAOs with Hibernate's native API.
* Subclasses access Hibernate's <code>Session</code> by calling on <code>getSession()</code> method.
* Operations must be implemented by catching <code>HibernateException</code>
* and rethrowing it by using <code>convertHibernateAccessException()</code>
* method. See source code of this class for an example.
* and rethrowing it by using <code>convertHibernateAccessException()</code> method.
* See source code of this class for an example.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
* @param <E>
* Entity class
@ -87,8 +87,9 @@ public class GenericDAOHibernate<E extends BaseEntity, PK extends Serializable>
/**
* It's necessary to save and validate later.
*
* Validate may retrieve the entity from DB and put it into the Session, which can eventually lead to
* a NonUniqueObject exception. Save works here to reattach the object as well as saving.
* Validate may retrieve the entity from DB and put it into the Session,
* which can eventually lead to a NonUniqueObject exception.
* Save works here to reattach the object as well as saving.
*/
public void save(E entity) throws ValidationException {
getSession().saveOrUpdate(entity);
@ -108,9 +109,7 @@ public class GenericDAOHibernate<E extends BaseEntity, PK extends Serializable>
}
public E merge(E entity) {
return entityClass.cast(getSession().merge(entity));
}
public void checkVersion(E entity) {
@ -155,7 +154,7 @@ public class GenericDAOHibernate<E extends BaseEntity, PK extends Serializable>
}
public void lock(E entity) {
// TODO resolve deprecated
getSession().lock(entity, LockMode.UPGRADE);
}
@ -168,7 +167,7 @@ public class GenericDAOHibernate<E extends BaseEntity, PK extends Serializable>
@Transactional(readOnly = true)
public E find(PK id) throws InstanceNotFoundException {
E entity = (E) getSession().get(entityClass, id);
E entity = getSession().get(entityClass, id);
if ( entity == null ) {
throw new InstanceNotFoundException(id, entityClass.getName());
@ -189,8 +188,9 @@ public class GenericDAOHibernate<E extends BaseEntity, PK extends Serializable>
public boolean exists(final PK id) {
return getSession().createCriteria(entityClass).add(
Restrictions.idEq(id)).setProjection(Projections.id())
return getSession().createCriteria(entityClass)
.add(Restrictions.idEq(id))
.setProjection(Projections.id())
.uniqueResult() != null;
}

View file

@ -29,9 +29,9 @@ import org.libreplan.business.common.exceptions.ValidationException;
import org.springframework.dao.OptimisticLockingFailureException;
/**
* The interface all DAOs (Data Access Objects) must implement. In general,
* a DAO must be implemented for each persistent entity. Concrete DAOs may
* provide (and usually will provide) additional methods.
* The interface all DAOs (Data Access Objects) must implement.
* In general, a DAO must be implemented for each persistent entity.
* Concrete DAOs may provide (and usually will provide) additional methods.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
*
@ -40,116 +40,120 @@ import org.springframework.dao.OptimisticLockingFailureException;
*/
public interface IGenericDAO <E, PK extends Serializable>{
public Class<E> getEntityClass();
Class<E> getEntityClass();
/**
* It inserts the object passed as a parameter in the ORM session, planning
* it for updating (even though it is not modified before or after the call
* to this method) or insertion, depending if it is was detached or
* transient. If another instance with the same key already exists in the
* ORM session, an exception is thrown. When updating, version check is
* executed (if the entity has version control enabled) with the possible
* <code>org.springframework.dao.OptimisticLockingFailureException</code>
* being thrown.
* It inserts the object passed as a parameter in the ORM session,
* planning it for updating (even though it is not modified before or after the call to this method)
* or insertion, depending if it is was detached or transient.
*
* If another instance with the same key already exists in the ORM session, an exception is thrown.
* When updating, version check is executed
* (if the entity has version control enabled) with
* the possible <code>org.springframework.dao.OptimisticLockingFailureException</code> being thrown.
*
* @throws ValidationException
* if the entity has some invalid values
*/
public void save(E entity) throws ValidationException;
void save(E entity) throws ValidationException;
/**
* Unlike <code>save</code>, it does not execute validations.
*/
public void saveWithoutValidating(E entity);
void saveWithoutValidating(E entity);
/**
* It reattaches the entity to the current session. This method bypasses
* hibernate validations and must only be used on read only transaction
* {@link OptimisticLockingFailureException} can be thrown if the entity has
* been updated for another transaction
* It reattaches the entity to the current session.
* This method bypasses hibernate validations and must only be used on read only
* transaction {@link OptimisticLockingFailureException} can be thrown if the entity has
* been updated for another transaction.
* @param entity
*/
public void reattach(E entity);
void reattach(E entity);
/**
* It inserts the object passed as a parameter in the ORM session. Unlike
* <code>save</code>, the entity passed as a parameter must not have been
* modified, and after calling the method, the entity is not considered
* dirty (but it will be considered dirty if it is modified after calling
* the method). Like <code>save</code>, if another instance with the same
* key already exists in the ORM session, an exception is thrown.
* It inserts the object passed as a parameter in the ORM session.
*
* Unlike <code>save</code>, the entity passed as a parameter must not have been modified,
* and after calling the method, the entity is not considered dirty
* (but it will be considered dirty if it is modified after calling the method).
*
* Like <code>save</code>, if another instance with the same key already exists in the ORM session,
* an exception is thrown.
* <p/>
* The intended use of the method is for reattachment of detached objects
* which have not been modified before calling this method and will not
* be modified during the transaction.
* The intended use of the method is for reattachment of detached objects which have not been modified
* before calling this method and will not be modified during the transaction.
*/
public void reattachUnmodifiedEntity(E entity);
void reattachUnmodifiedEntity(E entity);
/**
* It merges an entity. The caller must discard the reference passed as
* a parameter and work with the returned reference. Merging is an
* alternative technique to reattachment with <code>save</code>, which must
* be used when it cannot be assessed another instance with the same
* identifier as the one passed as a parameter already exists in the
* underlying ORM session. Like <code>save</code>, version check is
* executed when updating.
* It merges an entity.
*
* The caller must discard the reference passed as a parameter and work with the returned reference.
* Merging is analternative technique to reattachment with <code>save</code>,
* which must be used when it cannot be assessed another instance with the same identifier
* as the one passed as a parameter already exists in the underlying ORM session.
*
* Like <code>save</code>, version check is executed when updating.
* <p/>
* Since the caller must discard the reference passed as a parameter and
* work with the returned reference, merging is a technique more complicated
* than reattachmnent. Reattachment (by using <code>save</code> and/or
* <code>reattachUnmodifiedEntity</code>) should be the preferred technique.
* Since the caller must discard the reference passed as a parameter and work with the returned reference,
* merging is a technique more complicated than reattachment.
* Reattachment (by using <code>save</code> and/or <code>reattachUnmodifiedEntity</code>)
* should be the preferred technique.
*
* @param entity
*/
public E merge(E entity);
E merge(E entity);
/**
* It checks if the version of the instance passed as a parameter is equal
* to the one in the database. The instance must have methods conforming to
* the following signatures: <code>java.io.Serializable getId()</code> (to
* get the key) and <code>[long|Long] getVersion()</code> (to get the
* version).
* It checks if the version of the instance passed as a parameter is equal to the one in the database.
*
* The instance must have methods conforming to the following signatures:
* <code>java.io.Serializable getId()</code> (to get the key) and <code>[long|Long] getVersion()</code>
* (to get the version).
* <br/>
* If the check is not passed,
* <code>org.springframework.dao.OptimisticLockingFailureException</code>
* is thrown. If the key or the version of the entity is <code>null</code>,
* or the entity does not exist in database, the check is considered to be
* successful. This lets client code to treat creation and modification of
* instances in a unified way.
* <code>org.springframework.dao.OptimisticLockingFailureException</code> is thrown.
*
* If the key or the version of the entity is <code>null</code>, or the entity does not exist in database,
* the check is considered to be successful.
*
* This lets client code to treat creation and modification of instances in a unified way.
*/
public void checkVersion(E entity);
void checkVersion(E entity);
/**
* It sets a WRITE lock on the instance passed as a parameter, causing the
* same kind of reattachment as <code>reattachUnmodifiedEntity</code>.
* Other concurrent transactions will be blocked if they try to write or
* set a WRITE lock (but they can read) on the same persistent instance. If
* the version field is not equal to the one in the database,
* <code>org.springframework.dao.OptimisticLockingFailureException</code>
* is thrown. The lock is released when the transaction finishes.
* It sets a WRITE lock on the instance passed as a parameter, causing the same kind of reattachment
* as <code>reattachUnmodifiedEntity</code>.
*
* Other concurrent transactions will be blocked if they try to write or set a WRITE lock
* (but they can read) on the same persistent instance.
*
* If the version field is not equal to the one in the database,
* <code>org.springframework.dao.OptimisticLockingFailureException</code> is thrown.
* The lock is released when the transaction finishes.
* <p/>
* The intended use of this method is to enable pessimistic locking when
* the version check mechanism is not enough for controlling concurrent
* access. Most concurrent cases can be automatically managed with the usual
* version check mechanism.
* the version check mechanism is not enough for controlling concurrent access.
*
* Most concurrent cases can be automatically managed with the usual version check mechanism.
*/
public void lock(E entity);
void lock(E entity);
public E find(PK id) throws InstanceNotFoundException;
E find(PK id) throws InstanceNotFoundException;
/**
* Unlike <code>find(PK)</code>, it returns a runtime exception if the
* entity does not exist. So, this method should be used when the entity
* with the key passed as a parameter is supposed to exist.
* Unlike <code>find(PK)</code>, it returns a runtime exception if the entity does not exist.
* So, this method should be used when the entity with the key passed as a parameter is supposed to exist.
*/
public E findExistingEntity(PK id);
E findExistingEntity(PK id);
public boolean exists(PK id);
boolean exists(PK id);
public void remove(PK id) throws InstanceNotFoundException;
void remove(PK id) throws InstanceNotFoundException;
public <T extends E> List<T> list(Class<T> klass);
<T extends E> List<T> list(Class<T> klass);
public void flush();
void flush();
}

View file

@ -32,8 +32,8 @@ import java.util.Date;
* It represents the Email notification to be send to user.
*
* Created by
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
* on 19.10.15.
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
* on 19.10.2015.
*/
public class EmailNotification extends BaseEntity {

View file

@ -28,7 +28,7 @@ import org.libreplan.business.settings.entities.Language;
* It represents the E-mail template to be modified by admin and send to user.
*
* Created by
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
* on 29.09.2015.
*/
public class EmailTemplate extends BaseEntity {

View file

@ -25,7 +25,7 @@ import static org.libreplan.business.i18n.I18nHelper._;
* Available E-mail templates.
*
* Created by
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
* on 28.09.2015.
*
* TEMPLATE_N(_("Template N")) - for i18n

View file

@ -28,12 +28,14 @@ import static org.libreplan.business.i18n.I18nHelper._;
*/
public enum CommunicationType {
NEW_PROJECT(_("New project")), PROGRESS_UPDATE(_("Progress Update")), UPDATE_DELIVERING_DATE(
_("Update Delivering Date")), END_DATE_UPDATE(_("End date update"));
NEW_PROJECT(_("New project")),
PROGRESS_UPDATE(_("Progress Update")),
UPDATE_DELIVERING_DATE(_("Update Delivering Date")),
END_DATE_UPDATE(_("End date update"));
private String description;
private CommunicationType(String description) {
CommunicationType(String description) {
this.description = description;
}

View file

@ -58,45 +58,45 @@ import org.springframework.stereotype.Component;
/**
* @author Óscar González Fernández
*
*/
@Component
public class HibernateDatabaseModificationsListener implements
PostInsertEventListener, PostUpdateEventListener,
PostDeleteEventListener, ISnapshotRefresherService {
PostInsertEventListener,
PostUpdateEventListener,
PostDeleteEventListener,
ISnapshotRefresherService {
private static final Log LOG = LogFactory
.getLog(HibernateDatabaseModificationsListener.class);
private static final Log LOG = LogFactory.getLog(HibernateDatabaseModificationsListener.class);
private final ExecutorService executor = Executors.newFixedThreadPool(3);
private final ConcurrentMap<Class<?>, BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>>> interested;
private ConcurrentMap<Transaction, Dispatcher> pending = new ConcurrentHashMap<Transaction, Dispatcher>();
private ConcurrentMap<Transaction, Dispatcher> pending = new ConcurrentHashMap<>();
private Set<NotBlockingAutoUpdatedSnapshot<?>> snapshotsInterestedOn(
Class<?> entityClass) {
List<Class<?>> list = new ArrayList<Class<?>>(1);
private Set<NotBlockingAutoUpdatedSnapshot<?>> snapshotsInterestedOn(Class<?> entityClass) {
List<Class<?>> list = new ArrayList<>(1);
list.add(entityClass);
return snapshotsInterestedOn(list);
}
private Set<NotBlockingAutoUpdatedSnapshot<?>> snapshotsInterestedOn(
Collection<? extends Class<?>> classesList) {
Set<NotBlockingAutoUpdatedSnapshot<?>> result = new HashSet<NotBlockingAutoUpdatedSnapshot<?>>();
for (Class<?> each : new HashSet<Class<?>>(classesList)) {
BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>> queue = interested
.get(each);
if (queue != null) {
private Set<NotBlockingAutoUpdatedSnapshot<?>> snapshotsInterestedOn(Collection<? extends Class<?>> classesList) {
Set<NotBlockingAutoUpdatedSnapshot<?>> result = new HashSet<>();
for (Class<?> each : new HashSet<>(classesList)) {
BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>> queue = interested.get(each);
if ( queue != null ) {
result.addAll(queue);
}
}
return result;
}
private final class Dispatcher implements Synchronization {
private BlockingQueue<Class<?>> classes = new LinkedBlockingQueue<Class<?>>();
private BlockingQueue<Class<?>> classes = new LinkedBlockingQueue<>();
private final Transaction transaction;
public Dispatcher(Transaction transaction, Class<?> entityClass) {
@ -116,21 +116,22 @@ public class HibernateDatabaseModificationsListener implements
public void afterCompletion(int status) {
LOG.debug("transaction completed with status: " + status);
pending.remove(transaction);
if (isProbablySucessful(status)) {
List<Class<?>> list = new ArrayList<Class<?>>();
if ( isProbablySucessful(status) ) {
List<Class<?>> list = new ArrayList<>();
classes.drainTo(list);
LOG.debug(list.size() + " modification events recorded");
Set<NotBlockingAutoUpdatedSnapshot<?>> toDispatch = snapshotsInterestedOn(list);
LOG.debug("dispatching "
+ toDispatch
+ " snapshots to reload due to transaction successful completion");
LOG.debug(
"dispatching " + toDispatch + " snapshots to reload due to transaction successful completion");
dispatch(toDispatch);
}
}
private boolean isProbablySucessful(int status) {
return status != Status.STATUS_ROLLEDBACK
&& status != Status.STATUS_ROLLING_BACK;
return status != Status.STATUS_ROLLEDBACK && status != Status.STATUS_ROLLING_BACK;
}
}
@ -141,7 +142,7 @@ public class HibernateDatabaseModificationsListener implements
private volatile boolean hibernateListenersRegistered = false;
public HibernateDatabaseModificationsListener() {
interested = new ConcurrentHashMap<Class<?>, BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>>>();
interested = new ConcurrentHashMap<>();
}
@PostConstruct
@ -163,20 +164,17 @@ public class HibernateDatabaseModificationsListener implements
@Override
public void onPostDelete(PostDeleteEvent event) {
modificationOn(inferTransaction(event),
inferEntityClass(getEntityObject(event)));
modificationOn(inferTransaction(event), inferEntityClass(getEntityObject(event)));
}
@Override
public void onPostUpdate(PostUpdateEvent event) {
modificationOn(inferTransaction(event),
inferEntityClass(getEntityObject(event)));
modificationOn(inferTransaction(event), inferEntityClass(getEntityObject(event)));
}
@Override
public void onPostInsert(PostInsertEvent event) {
modificationOn(inferTransaction(event),
inferEntityClass(getEntityObject(event)));
modificationOn(inferTransaction(event), inferEntityClass(getEntityObject(event)));
}
@ -197,24 +195,27 @@ public class HibernateDatabaseModificationsListener implements
}
private static Class<?> inferEntityClass(Object entity) {
if (entity instanceof HibernateProxy) {
if ( entity instanceof HibernateProxy ) {
HibernateProxy proxy = (HibernateProxy) entity;
return proxy.getHibernateLazyInitializer().getPersistentClass();
}
return entity.getClass();
}
void modificationOn(Transaction transaction, Class<?> entityClass) {
if (transaction == null) {
if ( transaction == null ) {
dispatch(snapshotsInterestedOn(entityClass));
return;
}
Dispatcher newDispatcher = new Dispatcher(transaction, entityClass);
Dispatcher previous = null;
Dispatcher previous;
previous = pending.putIfAbsent(transaction, newDispatcher);
boolean dispatcherAlreadyExisted = previous != null;
if (dispatcherAlreadyExisted) {
if ( dispatcherAlreadyExisted ) {
previous.add(entityClass);
} else {
transaction.registerSynchronization(newDispatcher);
@ -222,9 +223,7 @@ public class HibernateDatabaseModificationsListener implements
}
private void dispatch(Set<NotBlockingAutoUpdatedSnapshot<?>> toBeDispatched) {
for (NotBlockingAutoUpdatedSnapshot<?> each : toBeDispatched) {
dispatch(each);
}
toBeDispatched.forEach(this::dispatch);
}
private void dispatch(NotBlockingAutoUpdatedSnapshot<?> each) {
@ -232,28 +231,28 @@ public class HibernateDatabaseModificationsListener implements
}
@Override
public <T> IAutoUpdatedSnapshot<T> takeSnapshot(String name,
Callable<T> callable, ReloadOn reloadOn) {
if (!hibernateListenersRegistered) {
public <T> IAutoUpdatedSnapshot<T> takeSnapshot(String name, Callable<T> callable, ReloadOn reloadOn) {
if ( !hibernateListenersRegistered ) {
throw new IllegalStateException(
"The hibernate listeners has not been registered. There is some configuration problem.");
}
final NotBlockingAutoUpdatedSnapshot<T> result;
result = new NotBlockingAutoUpdatedSnapshot<T>(name, callable);
result = new NotBlockingAutoUpdatedSnapshot<>(name, callable);
for (Class<?> each : reloadOn.getClassesOnWhichToReload()) {
interested.putIfAbsent(each, emptyQueue());
BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>> queue = interested
.get(each);
BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>> queue = interested.get(each);
boolean success = queue.add(result);
assert success : "the type of queue used must not have restricted capacity";
}
result.ensureFirstLoad(executor);
return result;
}
private BlockingQueue<NotBlockingAutoUpdatedSnapshot<?>> emptyQueue() {
return new LinkedBlockingQueue<NotBlockingAutoUpdatedSnapshot<?>>();
return new LinkedBlockingQueue<>();
}
}

View file

@ -80,14 +80,12 @@ import org.springframework.stereotype.Component;
/**
* @author Óscar González Fernández
*
*/
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class PredefinedDatabaseSnapshots {
private static final Log LOG = LogFactory
.getLog(PredefinedDatabaseSnapshots.class);
private static final Log LOG = LogFactory.getLog(PredefinedDatabaseSnapshots.class);
@Autowired
private IAdHocTransactionService transactionService;
@ -179,59 +177,69 @@ public class PredefinedDatabaseSnapshots {
private boolean snapshotsRegistered = false;
public void registerSnapshots() {
if (snapshotsRegistered) {
if ( snapshotsRegistered ) {
LOG.warn("snapshots have already been registered");
return;
}
snapshotsRegistered = true;
criterionsMap = snapshot("criterions map", calculateCriterionsMap(),
CriterionType.class, Criterion.class);
labelsMap = snapshot("labels map", calculateLabelsMap(),
LabelType.class, Label.class);
criterionsMap = snapshot("criterions map", calculateCriterionsMap(), CriterionType.class, Criterion.class);
labelsMap = snapshot("labels map", calculateLabelsMap(), LabelType.class, Label.class);
listWorkers = snapshot("workers", calculateWorkers(), Worker.class);
listCostCategories = snapshot("list cost categories",
calculateListCostCategories(),
CostCategory.class);
listCriterion = snapshot("list criterions", calculateListCriterion(),
Criterion.class);
mapResources = snapshot("map resources", calculateMapResources(),
Resource.class, Worker.class, Machine.class,
listCostCategories = snapshot("list cost categories", calculateListCostCategories(), CostCategory.class);
listCriterion = snapshot("list criterions", calculateListCriterion(), Criterion.class);
mapResources = snapshot(
"map resources",
calculateMapResources(),
Resource.class,
Worker.class,
Machine.class,
VirtualWorker.class);
externalCompanies = snapshot("external companies",
calculateExternalCompanies(),
ExternalCompany.class);
customerReferences = snapshot("customer references",
calculateCustomerReferences(), Order.class);
ordersCodes = snapshot("order codes", calculateOrdersCodes(),
Order.class);
resourceLoadChartData = snapshot("resource load grouped by date",
externalCompanies = snapshot("external companies", calculateExternalCompanies(), ExternalCompany.class);
customerReferences = snapshot("customer references", calculateCustomerReferences(), Order.class);
ordersCodes = snapshot("order codes", calculateOrdersCodes(), Order.class);
resourceLoadChartData = snapshot(
"resource load grouped by date",
calculateResourceLoadChartData(),
CalendarAvailability.class, CalendarException.class,
CalendarData.class, TaskElement.class, SpecificResourceAllocation.class,
GenericResourceAllocation.class, ResourceAllocation.class);
workReportLines = snapshot("work report lines", calculateWorkReportLines(),
WorkReportLine.class);
estimatedCostPerTask = snapshot("estimated cost per task",
CalendarAvailability.class,
CalendarException.class,
CalendarData.class,
TaskElement.class,
SpecificResourceAllocation.class,
GenericResourceAllocation.class,
ResourceAllocation.class);
workReportLines = snapshot("work report lines", calculateWorkReportLines(), WorkReportLine.class);
estimatedCostPerTask = snapshot(
"estimated cost per task",
calculateEstimatedCostPerTask(),
TaskElement.class, Task.class, TaskGroup.class, DayAssignment.class);
advanceCostPerTask = snapshot("advance cost per task",
TaskElement.class,
Task.class,
TaskGroup.class,
DayAssignment.class);
advanceCostPerTask = snapshot(
"advance cost per task",
calculateAdvanceCostPerTask(),
TaskElement.class, Task.class, TaskGroup.class,
TaskElement.class,
Task.class,
TaskGroup.class,
DirectAdvanceAssignment.class);
}
private <T> IAutoUpdatedSnapshot<T> snapshot(String name,
Callable<T> callable,
Class<?>... reloadOnChangesOf) {
return snapshotRefresherService.takeSnapshot(name,
callableOnReadOnlyTransaction(callable),
ReloadOn.onChangeOf(reloadOnChangesOf));
private <T> IAutoUpdatedSnapshot<T> snapshot(String name, Callable<T> callable, Class<?>... reloadOnChangesOf) {
return snapshotRefresherService
.takeSnapshot(name, callableOnReadOnlyTransaction(callable), ReloadOn.onChangeOf(reloadOnChangesOf));
}
@SuppressWarnings("unchecked")
private <T> Callable<T> callableOnReadOnlyTransaction(Callable<T> callable) {
return AdHocTransactionService.readOnlyProxy(transactionService,
Callable.class, callable);
return AdHocTransactionService.readOnlyProxy(transactionService, Callable.class, callable);
}
@Autowired
@ -241,31 +249,20 @@ public class PredefinedDatabaseSnapshots {
private ICriterionDAO criterionDAO;
private Callable<SortedMap<CriterionType, List<Criterion>>> calculateCriterionsMap() {
return new Callable<SortedMap<CriterionType, List<Criterion>>>() {
@Override
public SortedMap<CriterionType, List<Criterion>> call() {
SortedMap<CriterionType, List<Criterion>> result = new TreeMap<CriterionType, List<Criterion>>(
getComparatorByName());
for (CriterionType criterionType : criterionTypeDAO
.getSortedCriterionTypes()) {
if (criterionType.isEnabled()) {
List<Criterion> criterions = criterionType
.getSortCriterions();
result.put(criterionType, criterions);
}
return () -> {
SortedMap<CriterionType, List<Criterion>> result = new TreeMap<>(getComparatorByName());
for (CriterionType criterionType : criterionTypeDAO.getSortedCriterionTypes()) {
if ( criterionType.isEnabled() ) {
List<Criterion> criterions = criterionType.getSortCriterions();
result.put(criterionType, criterions);
}
return result;
}
return result;
};
}
private Comparator<CriterionType> getComparatorByName(){
return new Comparator<CriterionType>() {
@Override
public int compare(CriterionType arg0, CriterionType arg1) {
return (arg0.getName().compareTo(arg1.getName()));
}
};
return (arg0, arg1) -> (arg0.getName().compareTo(arg1.getName()));
}
@Autowired
@ -275,17 +272,13 @@ public class PredefinedDatabaseSnapshots {
private ILabelDAO labelDAO;
private Callable<Map<LabelType, List<Label>>> calculateLabelsMap() {
return new Callable<Map<LabelType,List<Label>>>() {
@Override
public Map<LabelType, List<Label>> call() {
Map<LabelType, List<Label>> result = new HashMap<LabelType, List<Label>>();
for (LabelType labelType : labelTypeDAO.getAll()) {
List<Label> labels = new ArrayList<Label>(
labelDAO.findByType(labelType));
result.put(labelType, labels);
}
return result;
return () -> {
Map<LabelType, List<Label>> result = new HashMap<>();
for (LabelType labelType : labelTypeDAO.getAll()) {
List<Label> labels = new ArrayList<>(labelDAO.findByType(labelType));
result.put(labelType, labels);
}
return result;
};
}
@ -293,56 +286,31 @@ public class PredefinedDatabaseSnapshots {
private IWorkerDAO workerDAO;
private Callable<List<Worker>> calculateWorkers() {
return new Callable<List<Worker>>() {
@Override
public List<Worker> call() {
return workerDAO.getAll();
}
};
return () -> workerDAO.getAll();
}
@Autowired
private ICostCategoryDAO costCategoryDAO;
private Callable<List<CostCategory>> calculateListCostCategories() {
return new Callable<List<CostCategory>>() {
@Override
public List<CostCategory> call() {
return costCategoryDAO.findActive();
}
};
return () -> costCategoryDAO.findActive();
}
private Callable<List<Criterion>> calculateListCriterion() {
return new Callable<List<Criterion>>() {
@Override
public List<Criterion> call() {
return criterionDAO.getAll();
}
};
return criterionDAO::getAll;
}
@Autowired
private IResourceDAO resourceDAO;
private Callable<Map<Class<?>, List<Resource>>> calculateMapResources() {
return new Callable<Map<Class<?>, List<Resource>>>() {
return () -> {
Map<Class<?>, List<Resource>> result = new HashMap<>();
result.put(Worker.class, Resource.sortByName(new ArrayList<>(resourceDAO.getRealWorkers())));
result.put(Machine.class, Resource.sortByName(new ArrayList<>(resourceDAO.getMachines())));
result.put(VirtualWorker.class, Resource.sortByName(new ArrayList<>(resourceDAO.getVirtualWorkers())));
@Override
public Map<Class<?>, List<Resource>> call() {
Map<Class<?>, List<Resource>> result = new HashMap<Class<?>, List<Resource>>();
result.put(Worker.class, Resource
.sortByName(new ArrayList<Resource>(resourceDAO
.getRealWorkers())));
result.put(Machine.class, Resource
.sortByName(new ArrayList<Resource>(resourceDAO
.getMachines())));
result.put(VirtualWorker.class, Resource
.sortByName(new ArrayList<Resource>(resourceDAO
.getVirtualWorkers())));
return result;
}
return result;
};
}
@ -351,44 +319,32 @@ public class PredefinedDatabaseSnapshots {
private IExternalCompanyDAO externalCompanyDAO;
private Callable<List<ExternalCompany>> calculateExternalCompanies() {
return new Callable<List<ExternalCompany>>() {
@Override
public List<ExternalCompany> call() {
return externalCompanyDAO.getExternalCompaniesAreClient();
}
};
return () -> externalCompanyDAO.getExternalCompaniesAreClient();
}
@Autowired
private IOrderDAO orderDAO;
private Callable<List<String>> calculateCustomerReferences() {
return new Callable<List<String>>() {
@Override
public List<String> call() {
// FIXME replace by a HQL query, for god's sake!
List<String> result = new ArrayList<String>();
for (Order order : orderDAO.getOrders()) {
if ((order.getCustomerReference() != null)
&& (!order.getCustomerReference().isEmpty())) {
result.add(order.getCustomerReference());
}
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());
}
return result;
}
return result;
};
}
private Callable<List<String>> calculateOrdersCodes() {
return new Callable<List<String>>() {
@Override
public List<String> call() {
List<String> result = new ArrayList<String>();
for (Order order : orderDAO.getOrders()) {
result.add(order.getCode());
}
return result;
return () -> {
List<String> result = new ArrayList<>();
for (Order order : orderDAO.getOrders()) {
result.add(order.getCode());
}
return result;
};
}
@ -399,16 +355,12 @@ public class PredefinedDatabaseSnapshots {
private IScenarioManager scenarioManager;
private Callable<ResourceLoadChartData> calculateResourceLoadChartData() {
return new Callable<ResourceLoadChartData>() {
@Override
public ResourceLoadChartData call() {
return () -> {
List<DayAssignment> dayAssignments = dayAssignmentDAO.getAllFor(scenarioManager.getCurrent(), null, null);
List<Resource> resources = resourceDAO.list(Resource.class);
List<DayAssignment> dayAssignments = dayAssignmentDAO.getAllFor(
scenarioManager.getCurrent(), null, null);
List<Resource> resources = resourceDAO.list(Resource.class);
return new ResourceLoadChartData(dayAssignments, resources);
return new ResourceLoadChartData(dayAssignments, resources);
}
};
}
@ -416,12 +368,7 @@ public class PredefinedDatabaseSnapshots {
private IWorkReportLineDAO workReportLineDAO;
private Callable<List<WorkReportLine>> calculateWorkReportLines() {
return new Callable<List<WorkReportLine>>() {
@Override
public List<WorkReportLine> call() {
return workReportLineDAO.list(WorkReportLine.class);
}
};
return () -> workReportLineDAO.list(WorkReportLine.class);
}
@Autowired
@ -431,34 +378,25 @@ public class PredefinedDatabaseSnapshots {
private ITaskElementDAO taskElementDAO;
private Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>> calculateEstimatedCostPerTask() {
return new Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>>() {
@Override
public Map<TaskElement, SortedMap<LocalDate, BigDecimal>> call() {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> map =
new HashMap<TaskElement, SortedMap<LocalDate,BigDecimal>>();
for(TaskElement task : taskElementDAO.list(TaskElement.class)) {
if(task instanceof Task) {
map.put(task, hoursCostCalculator.getEstimatedCost((Task)task));
}
}
return map;
}
return () -> {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> map = new HashMap<>();
taskElementDAO.list(TaskElement.class).stream().filter(task -> task instanceof Task)
.forEach(task -> map.put(task, hoursCostCalculator.getEstimatedCost((Task) task)));
return map;
};
}
private Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>> calculateAdvanceCostPerTask() {
return new Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>>() {
@Override
public Map<TaskElement, SortedMap<LocalDate, BigDecimal>> call() {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> map =
new HashMap<TaskElement, SortedMap<LocalDate,BigDecimal>>();
for(TaskElement task : taskElementDAO.list(TaskElement.class)) {
if(task instanceof Task) {
map.put(task, hoursCostCalculator.getAdvanceCost((Task)task));
}
return () -> {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> map = new HashMap<>();
for (TaskElement task : taskElementDAO.list(TaskElement.class)) {
if ( task instanceof Task ) {
map.put(task, hoursCostCalculator.getAdvanceCost((Task)task));
}
return map;
}
return map;
};
}

View file

@ -44,20 +44,18 @@ import org.libreplan.business.labels.daos.ILabelTypeDAO;
*
* @author Diego Pino Garcia<dpino@igalia.com>
*/
public class LabelType extends IntegrationEntity implements Comparable,
IHumanIdentifiable {
public class LabelType extends IntegrationEntity implements Comparable, IHumanIdentifiable {
@NotEmpty(message = "name not specified")
private String name;
private Set<Label> labels = new HashSet<Label>();
private Set<Label> labels = new HashSet<>();
private Integer lastLabelSequenceCode = 0;
// Default constructor, needed by Hibernate
// At least package visibility, https://www.hibernate.org/116.html#A6
// Default constructor, needed by Hibernate; at least package visibility
protected LabelType() {
}
public static LabelType create(String name) {
@ -96,7 +94,7 @@ public class LabelType extends IntegrationEntity implements Comparable,
@Override
public int compareTo(Object arg0) {
if (getName() != null) {
if ( getName() != null ) {
return getName().compareTo(((LabelType) arg0).getName());
}
return -1;
@ -109,11 +107,11 @@ public class LabelType extends IntegrationEntity implements Comparable,
@AssertTrue(message = "label names must be unique inside a label type")
public boolean isNonRepeatedLabelNamesConstraint() {
Set<String> labelNames = new HashSet<String>();
Set<String> labelNames = new HashSet<>();
for (Label label : labels) {
if (!StringUtils.isBlank(label.getName())) {
if (labelNames.contains(label.getName().toLowerCase())) {
if ( !StringUtils.isBlank(label.getName()) ) {
if ( labelNames.contains(label.getName().toLowerCase()) ) {
return false;
} else {
labelNames.add(label.getName().toLowerCase());
@ -126,18 +124,18 @@ public class LabelType extends IntegrationEntity implements Comparable,
@AssertTrue(message = "label type name is already in use")
public boolean isUniqueLabelTypeNameConstraint() {
if (!firstLevelValidationsPassed()) {
if ( !firstLevelValidationsPassed() ) {
return true;
}
ILabelTypeDAO labelTypeDAO = Registry.getLabelTypeDAO();
if (isNewObject()) {
if ( isNewObject() ) {
return !labelTypeDAO.existsByNameAnotherTransaction(this);
} else {
try {
LabelType c = labelTypeDAO
.findUniqueByNameAnotherTransaction(name);
LabelType c = labelTypeDAO.findUniqueByNameAnotherTransaction(name);
return c.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -150,7 +148,7 @@ public class LabelType extends IntegrationEntity implements Comparable,
}
public void updateUnvalidated(String name) {
if (!StringUtils.isBlank(name)) {
if ( !StringUtils.isBlank(name) ) {
this.name = name;
}
}
@ -162,12 +160,12 @@ public class LabelType extends IntegrationEntity implements Comparable,
public Label getLabelByCode(String code) throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
if ( StringUtils.isBlank(code) ) {
throw new InstanceNotFoundException(code, Label.class.getName());
}
for (Label l : labels) {
if (l.getCode().equalsIgnoreCase(StringUtils.trim(code))) {
if ( l.getCode().equalsIgnoreCase(StringUtils.trim(code)) ) {
return l;
}
}
@ -177,20 +175,24 @@ public class LabelType extends IntegrationEntity implements Comparable,
}
public void generateLabelCodes(int numberOfDigits) {
boolean condition;
for (Label label : this.getLabels()) {
if ((label.getCode() == null) || (label.getCode().isEmpty())
|| (!label.getCode().startsWith(this.getCode()))) {
condition = (label.getCode() == null) ||
(label.getCode().isEmpty()) ||
(!label.getCode().startsWith(this.getCode()));
if ( condition ) {
this.incrementLastLabelSequenceCode();
String labelCode = EntitySequence.formatValue(numberOfDigits,
this.getLastLabelSequenceCode());
label.setCode(this.getCode()
+ EntitySequence.CODE_SEPARATOR_CHILDREN + labelCode);
String labelCode = EntitySequence.formatValue(numberOfDigits, this.getLastLabelSequenceCode());
label.setCode(this.getCode() + EntitySequence.CODE_SEPARATOR_CHILDREN + labelCode);
}
}
}
public void incrementLastLabelSequenceCode() {
if (this.lastLabelSequenceCode == null) {
if ( this.lastLabelSequenceCode == null ) {
this.lastLabelSequenceCode = 0;
}
this.lastLabelSequenceCode++;

View file

@ -28,7 +28,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -71,8 +70,7 @@ import org.springframework.transaction.annotation.Transactional;
**/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
implements IOrderElementDAO {
public class OrderElementDAO extends IntegrationEntityDAO<OrderElement> implements IOrderElementDAO {
@Autowired
private IWorkReportLineDAO workReportLineDAO;
@ -90,14 +88,15 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public List<OrderElement> findWithoutParent() {
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.isNull("parent"));
return (List<OrderElement>) c.list();
}
public List<OrderElement> findByCodeAndParent(OrderElement parent,
String code) {
public List<OrderElement> findByCodeAndParent(OrderElement parent, String code) {
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.eq("infoComponent.code", code));
if (parent != null) {
if ( parent != null ) {
c.add(Restrictions.eq("parent", parent));
} else {
c.add(Restrictions.isNull("parent"));
@ -105,12 +104,10 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
return c.list();
}
public OrderElement findUniqueByCodeAndParent(OrderElement parent,
String code) throws InstanceNotFoundException {
public OrderElement findUniqueByCodeAndParent(OrderElement parent, String code) throws InstanceNotFoundException {
List<OrderElement> list = findByCodeAndParent(parent, code);
if (list.isEmpty() || list.size() > 1) {
throw new InstanceNotFoundException(code, OrderElement.class
.getName());
if ( list.isEmpty() || list.size() > 1 ) {
throw new InstanceNotFoundException(code, OrderElement.class.getName());
}
return list.get(0);
}
@ -118,13 +115,10 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
@Transactional(readOnly = true)
public EffortDuration getAssignedDirectEffort(OrderElement orderElement) {
List<WorkReportLine> listWRL = this.workReportLineDAO
.findByOrderElement(orderElement);
List<WorkReportLine> listWRL = this.workReportLineDAO.findByOrderElement(orderElement);
EffortDuration asignedDirectHours = EffortDuration.zero();
Iterator<WorkReportLine> iterator = listWRL.iterator();
while (iterator.hasNext()) {
asignedDirectHours = asignedDirectHours.plus(iterator.next()
.getEffort());
for (WorkReportLine aListWRL : listWRL) {
asignedDirectHours = asignedDirectHours.plus(aListWRL.getEffort());
}
return asignedDirectHours;
}
@ -132,16 +126,15 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
@Transactional(readOnly = true)
public BigDecimal getHoursAdvancePercentage(OrderElement orderElement) {
final EffortDuration totalChargedEffort = orderElement
.getSumChargedEffort() != null ? orderElement
.getSumChargedEffort().getTotalChargedEffort() : EffortDuration
.zero();
BigDecimal assignedHours = totalChargedEffort
.toHoursAsDecimalWithScale(2);
BigDecimal estimatedHours = new BigDecimal(orderElement.getWorkHours())
.setScale(2);
boolean condition = orderElement.getSumChargedEffort() != null;
if (estimatedHours.compareTo(BigDecimal.ZERO) <= 0) {
final EffortDuration totalChargedEffort =
condition ? orderElement.getSumChargedEffort().getTotalChargedEffort() : EffortDuration.zero();
BigDecimal assignedHours = totalChargedEffort.toHoursAsDecimalWithScale(2);
BigDecimal estimatedHours = new BigDecimal(orderElement.getWorkHours()).setScale(2);
if ( estimatedHours.compareTo(BigDecimal.ZERO) <= 0 ) {
return BigDecimal.ZERO;
}
@ -152,27 +145,28 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public void remove(Long id) throws InstanceNotFoundException {
OrderElement orderElement = find(id);
removeTaskSourcesFor(this.taskSourceDAO, orderElement);
for (WorkReport each : getWorkReportsPointingTo(orderElement)) {
workReportDAO.remove(each.getId());
}
super.remove(id);
}
public static void removeTaskSourcesFor(ITaskSourceDAO taskSourceDAO,
OrderElement orderElement) throws InstanceNotFoundException {
List<SchedulingDataForVersion> allVersions = orderElement
.getSchedulingDatasForVersionFromBottomToTop();
public static void removeTaskSourcesFor(ITaskSourceDAO taskSourceDAO, OrderElement orderElement)
throws InstanceNotFoundException {
List<SchedulingDataForVersion> allVersions = orderElement.getSchedulingDatasForVersionFromBottomToTop();
for (TaskSource each : taskSourcesFrom(allVersions)) {
each.detachAssociatedTaskFromParent();
taskSourceDAO.remove(each.getId());
}
}
private static List<TaskSource> taskSourcesFrom(
List<SchedulingDataForVersion> list) {
List<TaskSource> result = new ArrayList<TaskSource>();
private static List<TaskSource> taskSourcesFrom(List<SchedulingDataForVersion> list) {
List<TaskSource> result = new ArrayList<>();
for (SchedulingDataForVersion each : list) {
if (each.getTaskSource() != null) {
if ( each.getTaskSource() != null ) {
result.add(each.getTaskSource());
}
}
@ -180,9 +174,8 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
}
private Set<WorkReport> getWorkReportsPointingTo(OrderElement orderElement) {
Set<WorkReport> result = new HashSet<WorkReport>();
for (WorkReportLine each : workReportLineDAO
.findByOrderElementAndChildren(orderElement)) {
Set<WorkReport> result = new HashSet<>();
for (WorkReportLine each : workReportLineDAO.findByOrderElementAndChildren(orderElement)) {
result.add(each.getWorkReport());
}
return result;
@ -190,30 +183,27 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
public List<OrderElement> findAll() {
return getSession().createCriteria(getEntityClass()).addOrder(
org.hibernate.criterion.Order.asc("infoComponent.code")).list();
return getSession()
.createCriteria(getEntityClass())
.addOrder(org.hibernate.criterion.Order.asc("infoComponent.code")).list();
}
@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly = true)
public OrderElement findByCode(String code)
throws InstanceNotFoundException {
public OrderElement findByCode(String code) throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(null, getEntityClass()
.getName());
if ( StringUtils.isBlank(code) ) {
throw new InstanceNotFoundException(null, getEntityClass().getName());
}
OrderElement entity = (OrderElement) getSession().createCriteria(
getEntityClass())
.add(
Restrictions.eq("infoComponent.code", code.trim())
.ignoreCase()).uniqueResult();
OrderElement entity = (OrderElement) getSession()
.createCriteria(getEntityClass())
.add(Restrictions.eq("infoComponent.code", code.trim()).ignoreCase())
.uniqueResult();
if (entity == null) {
throw new InstanceNotFoundException(code, getEntityClass()
.getName());
if ( entity == null ) {
throw new InstanceNotFoundException(code, getEntityClass().getName());
} else {
return entity;
}
@ -223,19 +213,18 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public List<OrderElement> findByTemplate(OrderElementTemplate template) {
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.eq("template", template));
return (List<OrderElement>) c.list();
}
@Override
public OrderElement findUniqueByCode(String code)
throws InstanceNotFoundException {
public OrderElement findUniqueByCode(String code) throws InstanceNotFoundException {
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.eq("infoComponent.code", code));
OrderElement orderElement = (OrderElement) c.uniqueResult();
if (orderElement == null) {
throw new InstanceNotFoundException(code, OrderElement.class
.getName());
if ( orderElement == null ) {
throw new InstanceNotFoundException(code, OrderElement.class.getName());
} else {
return orderElement;
}
@ -243,8 +232,7 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public OrderElement findUniqueByCodeAnotherTransaction(String code)
throws InstanceNotFoundException {
public OrderElement findUniqueByCodeAnotherTransaction(String code) throws InstanceNotFoundException {
return findUniqueByCode(code);
}
@ -258,6 +246,7 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public List<OrderElement> findOrderElementsWithExternalCode() {
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.isNotNull("externalCode"));
return c.list();
}
@ -266,18 +255,16 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
public OrderElement findByExternalCode(String code) throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(null, getEntityClass()
.getName());
if ( StringUtils.isBlank(code) ) {
throw new InstanceNotFoundException(null, getEntityClass().getName());
}
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.eq("externalCode", code.trim()).ignoreCase());
OrderElement entity = (OrderElement) c.uniqueResult();
if (entity == null) {
throw new InstanceNotFoundException(code, getEntityClass()
.getName());
if ( entity == null ) {
throw new InstanceNotFoundException(code, getEntityClass().getName());
} else {
return entity;
}
@ -285,30 +272,27 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
}
/**
* Methods to calculate estatistics with the estimated hours and worked
* hours of a set of order elements.
* Methods to calculate statistics with the estimated hours and worked hours of a set of order elements.
* @param List
* <{@link OrderElement}>
*/
public BigDecimal calculateAverageEstimatedHours(
final List<OrderElement> list) {
public BigDecimal calculateAverageEstimatedHours(final List<OrderElement> list) {
BigDecimal sum = sumEstimatedHours(list);
return average(new BigDecimal(list.size()), sum);
}
public EffortDuration calculateAverageWorkedHours(
final List<OrderElement> list) {
public EffortDuration calculateAverageWorkedHours(final List<OrderElement> list) {
EffortDuration sum = sumWorkedHours(list);
return (list.size() == 0) ? EffortDuration.zero() : EffortDuration
.average(sum, list.size());
return (list.size() == 0) ? EffortDuration.zero() : EffortDuration.average(sum, list.size());
}
private BigDecimal average(BigDecimal divisor, BigDecimal sum) {
BigDecimal average = new BigDecimal(0);
if (sum.compareTo(new BigDecimal(0)) > 0) {
average = sum.divide(divisor, new MathContext(2,
RoundingMode.HALF_UP));
if ( sum.compareTo(new BigDecimal(0)) > 0 ) {
average = sum.divide(divisor, new MathContext(2, RoundingMode.HALF_UP));
}
return average;
}
@ -331,7 +315,7 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public BigDecimal calculateMaxEstimatedHours(final List<OrderElement> list) {
BigDecimal max = new BigDecimal(0);
if (!list.isEmpty()) {
if ( !list.isEmpty() ) {
max = new BigDecimal(list.get(0).getWorkHours());
for (OrderElement orderElement : list) {
BigDecimal value = new BigDecimal(orderElement.getWorkHours());
@ -342,18 +326,18 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
}
private BigDecimal getMax(BigDecimal valueA, BigDecimal valueB) {
if (valueA.compareTo(valueB) < 0) {
if ( valueA.compareTo(valueB) < 0 ) {
return valueB;
} else if (valueA.compareTo(valueB) > 0) {
} else if ( valueA.compareTo(valueB) > 0 ) {
return valueA;
}
return valueA;
}
private BigDecimal getMin(BigDecimal valueA, BigDecimal valueB) {
if (valueA.compareTo(valueB) > 0) {
if ( valueA.compareTo(valueB) > 0 ) {
return valueB;
} else if (valueA.compareTo(valueB) < 0) {
} else if ( valueA.compareTo(valueB) < 0 ) {
return valueA;
}
return valueA;
@ -361,7 +345,7 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public BigDecimal calculateMinEstimatedHours(final List<OrderElement> list) {
BigDecimal min = new BigDecimal(0);
if (!list.isEmpty()) {
if ( !list.isEmpty() ) {
min = new BigDecimal(list.get(0).getWorkHours());
for (OrderElement orderElement : list) {
BigDecimal value = new BigDecimal(orderElement.getWorkHours());
@ -374,7 +358,7 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
public EffortDuration calculateMaxWorkedHours(final List<OrderElement> list) {
EffortDuration max = EffortDuration.zero();
if (!list.isEmpty()) {
if ( !list.isEmpty() ) {
max = getAssignedDirectEffort(list.get(0));
for (OrderElement orderElement : list) {
EffortDuration value = getAssignedDirectEffort(orderElement);
@ -387,7 +371,7 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
public EffortDuration calculateMinWorkedHours(final List<OrderElement> list) {
EffortDuration min = EffortDuration.zero();
if (!list.isEmpty()) {
if ( !list.isEmpty() ) {
min = getAssignedDirectEffort(list.get(0));
for (OrderElement orderElement : list) {
EffortDuration value = getAssignedDirectEffort(orderElement);
@ -399,28 +383,28 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
@Override
public boolean isAlreadyInUse(OrderElement orderElement) {
if (orderElement.isNewObject()) {
if ( orderElement.isNewObject() ) {
return false;
}
boolean usedInWorkReports = !getSession().createCriteria(
WorkReport.class).add(
Restrictions.eq("orderElement", orderElement)).list().isEmpty();
boolean usedInWorkReportLines = !getSession().createCriteria(
WorkReportLine.class).add(
Restrictions.eq("orderElement", orderElement)).list().isEmpty();
boolean usedInWorkReports = !getSession()
.createCriteria(WorkReport.class)
.add(Restrictions.eq("orderElement", orderElement)).list().isEmpty();
boolean usedInWorkReportLines = !getSession()
.createCriteria(WorkReportLine.class)
.add(Restrictions.eq("orderElement", orderElement)).list().isEmpty();
return usedInWorkReports || usedInWorkReportLines;
}
@Override
public boolean isAlreadyInUseThisOrAnyOfItsChildren(
OrderElement orderElement) {
if (isAlreadyInUse(orderElement)) {
public boolean isAlreadyInUseThisOrAnyOfItsChildren(OrderElement orderElement) {
if ( isAlreadyInUse(orderElement) ) {
return true;
}
for (OrderElement child : orderElement.getChildren()) {
if (isAlreadyInUseThisOrAnyOfItsChildren(child)) {
if ( isAlreadyInUseThisOrAnyOfItsChildren(child) ) {
return true;
}
}
@ -436,22 +420,22 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
String strQuery = "SELECT order.infoComponent.code FROM OrderElement order ";
final List<Long> ids = getNoEmptyIds(orderElements);
if (!ids.isEmpty()) {
if ( !ids.isEmpty() ) {
strQuery += "WHERE order.id NOT IN (:ids)";
}
Query query = getSession().createQuery(strQuery);
if (!ids.isEmpty()) {
if ( !ids.isEmpty() ) {
query.setParameterList("ids", ids);
}
return new HashSet<String>(query.list());
return new HashSet<>(query.list());
}
private List<Long> getNoEmptyIds(List<OrderElement> orderElements) {
List<Long> result = new ArrayList<Long>();
List<Long> result = new ArrayList<>();
for (OrderElement each: orderElements) {
final Long id = each.getId();
if (id != null) {
if ( id != null ) {
result.add(id);
}
}
@ -463,17 +447,18 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
public OrderElement findRepeatedOrderCodeInDB(OrderElement order) {
final Map<String, OrderElement> orderElements = createMapByCode(getOrderAndAllChildren(order));
final Map<String, OrderElement> orderElementsInDB = createMapByCode(getAll());
boolean condition;
for (String code : orderElements.keySet()) {
OrderElement orderElement = orderElements.get(code);
OrderElement orderElementInDB = orderElementsInDB.get(code);
// There's an element in the DB with the same code and it's a
// different element in a different order
if (orderElementInDB != null
&& !orderElementInDB.getId().equals(orderElement.getId())
&& !orderElementInDB.getOrder().getId()
.equals(orderElement.getOrder().getId())) {
// There is an element in the DB with the same code and it's a different element in a different order
condition = orderElementInDB != null &&
!orderElementInDB.getId().equals(orderElement.getId()) &&
!orderElementInDB.getOrder().getId().equals(orderElement.getOrder().getId());
if ( condition ) {
return orderElement;
}
}
@ -481,14 +466,15 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
}
private List<OrderElement> getOrderAndAllChildren(OrderElement order) {
List<OrderElement> result = new ArrayList<OrderElement>();
List<OrderElement> result = new ArrayList<>();
result.add(order);
result.addAll(order.getAllChildren());
return result;
}
private Map<String, OrderElement> createMapByCode(List<OrderElement> orderElements) {
Map<String, OrderElement> result = new HashMap<String, OrderElement>();
Map<String, OrderElement> result = new HashMap<>();
for (OrderElement each: orderElements) {
final String code = each.getCode();
result.put(code, each);
@ -497,30 +483,30 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
}
@Override
public boolean hasImputedExpenseSheet(Long id)
throws InstanceNotFoundException {
public boolean hasImputedExpenseSheet(Long id) throws InstanceNotFoundException {
OrderElement orderElement = find(id);
return (!expenseSheetLineDAO.findByOrderElement(orderElement).isEmpty());
}
@Override
public boolean hasImputedExpenseSheetThisOrAnyOfItsChildren(Long id) throws InstanceNotFoundException {
OrderElement orderElement = find(id);
return (!expenseSheetLineDAO.findByOrderElementAndChildren(orderElement).isEmpty());
}
@SuppressWarnings("unchecked")
@Override
public List<OrderElement> findByLabelsAndCriteria(Set<Label> labels,
Set<Criterion> criteria) {
public List<OrderElement> findByLabelsAndCriteria(Set<Label> labels, Set<Criterion> criteria) {
String strQuery = "SELECT oe.id ";
strQuery += "FROM OrderElement oe ";
String where = "";
if (labels != null && !labels.isEmpty()) {
if ( labels != null && !labels.isEmpty() ) {
for (int i = 0; i < labels.size(); i++) {
if (where.isEmpty()) {
if ( where.isEmpty() ) {
where += "WHERE ";
} else {
where += "AND ";
@ -529,9 +515,9 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
}
}
if (criteria != null && !criteria.isEmpty()) {
if ( criteria != null && !criteria.isEmpty() ) {
strQuery += "JOIN oe.criterionRequirements cr ";
if (where.isEmpty()) {
if ( where.isEmpty() ) {
where += "WHERE ";
} else {
where += "AND ";
@ -545,53 +531,50 @@ public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
strQuery += where;
Query query = getSession().createQuery(strQuery);
if (labels != null && !labels.isEmpty()) {
if ( labels != null && !labels.isEmpty() ) {
int i = 0;
for (Label label : labels) {
query.setParameter("label" + i, label);
i++;
}
}
if (criteria != null && !criteria.isEmpty()) {
if ( criteria != null && !criteria.isEmpty() ) {
query.setParameterList("criteria", criteria);
query.setParameter("criteriaSize", (long) criteria.size());
}
List<Long> orderElementsIds = query.list();
if (orderElementsIds.isEmpty()) {
if ( orderElementsIds.isEmpty() ) {
return Collections.emptyList();
}
return getSession()
.createQuery(
"FROM OrderElement oe WHERE oe.id IN (:ids) ORDER BY oe.infoComponent.code")
.createQuery("FROM OrderElement oe WHERE oe.id IN (:ids) ORDER BY oe.infoComponent.code")
.setParameterList("ids", orderElementsIds).list();
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public boolean existsByCodeInAnotherOrderAnotherTransaction(
OrderElement orderElement) {
public boolean existsByCodeInAnotherOrderAnotherTransaction(OrderElement orderElement) {
return existsByCodeInAnotherOrder(orderElement);
}
private boolean existsByCodeInAnotherOrder(OrderElement orderElement) {
try {
OrderElement found = findUniqueByCode(orderElement.getCode());
return !areInTheSameOrder(orderElement, found);
} catch (InstanceNotFoundException e) {
return false;
}
}
private boolean areInTheSameOrder(OrderElement orderElement1,
OrderElement orderElement2) {
private boolean areInTheSameOrder(OrderElement orderElement1, OrderElement orderElement2) {
Order order1 = orderElement1.getOrder();
Order order2 = orderElement2.getOrder();
if (order1 == null || order2 == null) {
return false;
}
return Objects.equals(order1.getId(), order2.getId());
return !(order1 == null || order2 == null) && Objects.equals(order1.getId(), order2.getId());
}
}

View file

@ -30,7 +30,7 @@ import java.util.List;
/**
* Created by
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
* on 12.24.2015.
*/
@ -46,12 +46,12 @@ public class OrderFileDAO extends GenericDAOHibernate<OrderFile, Long> implement
public void delete(OrderFile file) {
try {
remove(file.getId());
} catch (InstanceNotFoundException e) {}
} catch (InstanceNotFoundException ignored) {
}
}
@Override
public List<OrderFile> findByParent(OrderElement parent) {
return getSession().createCriteria(OrderFile.class)
.add(Restrictions.eq("parent", parent)).list();
return getSession().createCriteria(OrderFile.class).add(Restrictions.eq("parent", parent)).list();
}
}

View file

@ -35,8 +35,6 @@ import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.common.IntegrationEntity;
import org.libreplan.business.common.Registry;
import org.libreplan.business.common.daos.IIntegrationEntityDAO;
@ -49,8 +47,6 @@ import org.libreplan.business.templates.entities.OrderLineTemplate;
public class HoursGroup extends IntegrationEntity implements Cloneable, ICriterionRequirable {
private static final Log LOG = LogFactory.getLog(HoursGroup.class);
private ResourceEnum resourceType = ResourceEnum.WORKER;
private Integer workingHours = 0;
@ -59,7 +55,7 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
private Boolean fixedPercentage = false;
private Set<CriterionRequirement> criterionRequirements = new HashSet<CriterionRequirement>();
private Set<CriterionRequirement> criterionRequirements = new HashSet<>();
private OrderLine parentOrderLine;
@ -74,21 +70,23 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
public static HoursGroup create(OrderLine parentOrderLine) {
HoursGroup result = new HoursGroup(parentOrderLine);
result.setNewObject(true);
return result;
}
public static HoursGroup create(OrderLineTemplate orderLineTemplate) {
HoursGroup result = new HoursGroup(orderLineTemplate);
result.setNewObject(true);
return result;
}
public static HoursGroup createUnvalidated(String code,
ResourceEnum resourceType, Integer workingHours) {
public static HoursGroup createUnvalidated(String code, ResourceEnum resourceType, Integer workingHours) {
HoursGroup result = create(new HoursGroup());
result.setCode(code);
result.setResourceType(resourceType);
result.setWorkingHours(workingHours);
return result;
}
@ -101,23 +99,26 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
*/
public static HoursGroup copyFrom(HoursGroup hoursGroup, OrderLineTemplate parent) {
HoursGroup result = copyFrom(hoursGroup);
result.setCriterionRequirements(copyDirectCriterionRequirements(
result, parent, hoursGroup.getDirectCriterionRequirement()));
result, hoursGroup.getDirectCriterionRequirement()));
result.setOrderLineTemplate(parent);
result.setParentOrderLine(null);
return result;
}
private static Set<CriterionRequirement> copyDirectCriterionRequirements(
HoursGroup hoursGroup,
Object orderLine,
Collection<DirectCriterionRequirement> criterionRequirements) {
Set<CriterionRequirement> result = new HashSet<CriterionRequirement>();
HoursGroup hoursGroup, Collection<DirectCriterionRequirement> criterionRequirements) {
Set<CriterionRequirement> result = new HashSet<>();
for (DirectCriterionRequirement each: criterionRequirements) {
final DirectCriterionRequirement directCriterionRequirement = (DirectCriterionRequirement) each;
DirectCriterionRequirement newDirectCriterionRequirement = DirectCriterionRequirement
.copyFrom(directCriterionRequirement, hoursGroup);
DirectCriterionRequirement newDirectCriterionRequirement =
DirectCriterionRequirement.copyFrom(each, hoursGroup);
newDirectCriterionRequirement.setHoursGroup(hoursGroup);
result.add(newDirectCriterionRequirement);
}
@ -126,10 +127,13 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
public static HoursGroup copyFrom(HoursGroup hoursGroup, OrderLine parent) {
HoursGroup result = copyFrom(hoursGroup);
result.setCriterionRequirements(copyDirectCriterionRequirements(
result, parent, hoursGroup.getDirectCriterionRequirement()));
result, hoursGroup.getDirectCriterionRequirement()));
result.setOrderLineTemplate(null);
result.setParentOrderLine(parent);
return result;
}
@ -138,10 +142,12 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
hoursGroup.getCode(),
hoursGroup.getResourceType(),
hoursGroup.getWorkingHours());
result.setCode(UUID.randomUUID().toString());
result.percentage = hoursGroup.getPercentage();
result.fixedPercentage = hoursGroup.isFixedPercentage();
result.origin = hoursGroup;
return result;
}
@ -173,12 +179,12 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
this.resourceType = resource;
}
public void setWorkingHours(Integer workingHours)
throws IllegalArgumentException {
if ((workingHours != null) && (workingHours < 0)) {
public void setWorkingHours(Integer workingHours) throws IllegalArgumentException {
if ( (workingHours != null) && (workingHours < 0) ) {
throw new IllegalArgumentException("Working hours should not be negative");
}
if (workingHours == null) {
if ( workingHours == null ) {
workingHours = 0;
}
this.workingHours = workingHours;
@ -234,10 +240,11 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
}
public Set<Criterion> getValidCriterions() {
Set<Criterion> criterions = new HashSet<Criterion>();
Set<Criterion> criterions = new HashSet<>();
for (CriterionRequirement criterionRequirement : getDirectCriterionRequirement()) {
criterions.add(criterionRequirement.getCriterion());
}
for (IndirectCriterionRequirement requirement : getIndirectCriterionRequirement()) {
if ( requirement.isValid() ) {
criterions.add(requirement.getCriterion());
@ -262,10 +269,7 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
}
public boolean canAddCriterionRequirement(CriterionRequirement newRequirement) {
if ( (isValidResourceType(newRequirement)) && (!existSameCriterionRequirement(newRequirement)) ) {
return false;
}
return true;
return !((isValidResourceType(newRequirement)) && (!existSameCriterionRequirement(newRequirement)));
}
@Override
@ -289,11 +293,11 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
public void updateMyCriterionRequirements() {
Set<CriterionRequirement> requirementsParent = criterionRequirementHandler
.getRequirementWithSameResourType(
getCriterionRequirementsFromParent(), resourceType);
.getRequirementWithSameResourType(getCriterionRequirementsFromParent(), resourceType);
Set<IndirectCriterionRequirement> currentIndirects = criterionRequirementHandler
.getCurrentIndirectRequirements(
getIndirectCriterionRequirement(), requirementsParent);
.getCurrentIndirectRequirements(getIndirectCriterionRequirement(), requirementsParent);
criterionRequirementHandler.removeOldIndirects(this, currentIndirects);
criterionRequirementHandler.addNewsIndirects(this, currentIndirects);
}
@ -302,20 +306,19 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
updateMyCriterionRequirements();
// Set valid value as original value for every indirect
Map<Criterion, Boolean> mapCriterionToValid = createCriterionToValidMap(origin
.getIndirectCriterionRequirement());
Map<Criterion, Boolean> mapCriterionToValid =
createCriterionToValidMap(origin.getIndirectCriterionRequirement());
for (CriterionRequirement each : criterionRequirements) {
if (each instanceof IndirectCriterionRequirement) {
if ( each instanceof IndirectCriterionRequirement ) {
IndirectCriterionRequirement indirect = (IndirectCriterionRequirement) each;
indirect.setValid(mapCriterionToValid.get(each.getCriterion()));
}
}
}
private Map<Criterion, Boolean> createCriterionToValidMap(
Set<IndirectCriterionRequirement> indirects) {
Map<Criterion, Boolean> result = new HashMap<Criterion, Boolean>();
private Map<Criterion, Boolean> createCriterionToValidMap(Set<IndirectCriterionRequirement> indirects) {
Map<Criterion, Boolean> result = new HashMap<>();
for (IndirectCriterionRequirement each : indirects) {
result.put(each.getCriterion(), each.isValid());
@ -324,15 +327,14 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
}
private Set<CriterionRequirement> getCriterionRequirementsFromParent() {
return (parentOrderLine != null) ? parentOrderLine
.getCriterionRequirements() : orderLineTemplate
.getCriterionRequirements();
return (parentOrderLine != null) ? parentOrderLine.getCriterionRequirements() :
orderLineTemplate.getCriterionRequirements();
}
public Set<IndirectCriterionRequirement> getIndirectCriterionRequirement() {
Set<IndirectCriterionRequirement> list = new HashSet<IndirectCriterionRequirement>();
Set<IndirectCriterionRequirement> list = new HashSet<>();
for(CriterionRequirement criterionRequirement : criterionRequirements ){
if(criterionRequirement instanceof IndirectCriterionRequirement){
if ( criterionRequirement instanceof IndirectCriterionRequirement ){
list.add((IndirectCriterionRequirement) criterionRequirement);
}
}
@ -340,9 +342,9 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
}
public Set<DirectCriterionRequirement> getDirectCriterionRequirement() {
Set<DirectCriterionRequirement> list = new HashSet<DirectCriterionRequirement>();
Set<DirectCriterionRequirement> list = new HashSet<>();
for(CriterionRequirement criterionRequirement : criterionRequirements ){
if(criterionRequirement instanceof DirectCriterionRequirement){
if ( criterionRequirement instanceof DirectCriterionRequirement ){
list.add((DirectCriterionRequirement) criterionRequirement);
}
}
@ -350,20 +352,17 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
}
public boolean isValidResourceType(CriterionRequirement newRequirement) {
ResourceEnum resourceTypeRequirement = newRequirement.getCriterion()
.getType().getResource();
if (resourceType != null) {
return (resourceType.equals(resourceTypeRequirement) || (resourceTypeRequirement
.equals(ResourceEnum.getDefault())));
}
return true;
ResourceEnum resourceTypeRequirement = newRequirement.getCriterion().getType().getResource();
return resourceType == null ||
(resourceType.equals(resourceTypeRequirement) ||
(resourceTypeRequirement.equals(ResourceEnum.getDefault())));
}
boolean existSameCriterionRequirement(
CriterionRequirement newRequirement) {
boolean existSameCriterionRequirement(CriterionRequirement newRequirement) {
Criterion criterion = newRequirement.getCriterion();
for(CriterionRequirement requirement : getCriterionRequirements()){
if (requirement.getCriterion().equals(criterion)) {
for (CriterionRequirement requirement : getCriterionRequirements()){
if ( requirement.getCriterion().equals(criterion) ) {
return true;
}
}
@ -393,8 +392,7 @@ public class HoursGroup extends IntegrationEntity implements Cloneable, ICriteri
@Override
public boolean isUniqueCodeConstraint() {
// the automatic checking of this constraint is avoided because it uses
// the wrong code property
// The automatic checking of this constraint is avoided because it uses the wrong code property
return true;
}

View file

@ -50,16 +50,17 @@ public class OrderLine extends OrderElement {
public static OrderLine create() {
OrderLine result = new OrderLine();
result.setNewObject(true);
return result;
}
public static OrderLine createUnvalidated(String code) {
OrderLine orderLine = create(new OrderLine(), code);
return orderLine;
return create(new OrderLine(), code);
}
public static OrderLine createUnvalidatedWithUnfixedPercentage(String code, int hours) {
OrderLine orderLine = createOrderLineWithUnfixedPercentage(hours);
return create(orderLine, code);
}
@ -70,6 +71,7 @@ public class OrderLine extends OrderElement {
hoursGroup.setFixedPercentage(false);
hoursGroup.setPercentage(new BigDecimal(1));
hoursGroup.setWorkingHours(hours);
return result;
}
@ -79,10 +81,9 @@ public class OrderLine extends OrderElement {
* Constructor for hibernate. Do not use!
*/
public OrderLine() {
}
private Set<HoursGroup> hoursGroups = new HashSet<HoursGroup>();
private Set<HoursGroup> hoursGroups = new HashSet<>();
private Integer lastHoursGroupSequenceCode = 0;
@ -95,7 +96,7 @@ public class OrderLine extends OrderElement {
@Override
public List<OrderElement> getChildren() {
return new ArrayList<OrderElement>();
return new ArrayList<>();
}
@Override
@ -105,38 +106,44 @@ public class OrderLine extends OrderElement {
@Override
public boolean isEmptyLeaf() {
if (getWorkHours() != 0) {
if ( getWorkHours() != 0 ) {
return false;
}
if (!getDirectCriterionRequirement().isEmpty()) {
if ( !getDirectCriterionRequirement().isEmpty() ) {
return false;
}
if (!getDirectAdvanceAssignments().isEmpty()) {
if ( !getDirectAdvanceAssignments().isEmpty() ) {
for (DirectAdvanceAssignment each : getDirectAdvanceAssignments()) {
if (!each.getAdvanceMeasurements().isEmpty()) {
if ( !each.getAdvanceMeasurements().isEmpty() ) {
return false;
}
}
}
if (!getQualityForms().isEmpty()) {
if ( !getQualityForms().isEmpty() ) {
return false;
}
if (!getLabels().isEmpty()) {
if ( !getLabels().isEmpty() ) {
return false;
}
if (!getMaterialAssignments().isEmpty()) {
if ( !getMaterialAssignments().isEmpty() ) {
return false;
}
if (getSumChargedEffort() != null
&& !getSumChargedEffort().getDirectChargedEffort().isZero()) {
if ( getSumChargedEffort() != null && !getSumChargedEffort().getDirectChargedEffort().isZero() ) {
return false;
}
if (getSumExpenses() != null && !getSumExpenses().isTotalDirectExpensesZero()) {
if ( getSumExpenses() != null && !getSumExpenses().isTotalDirectExpensesZero() ) {
return false;
}
if (!getTaskElements().isEmpty()) {
if (!getTaskElements().iterator().next()
.getDayAssignments(FilterType.KEEP_ALL).isEmpty()) {
if ( !getTaskElements().isEmpty() ) {
if ( !getTaskElements().iterator().next().getDayAssignments(FilterType.KEEP_ALL).isEmpty() ) {
return false;
}
}
@ -157,13 +164,14 @@ public class OrderLine extends OrderElement {
setCode("");
setName("");
convertedToContainer = true;
return result;
}
@Valid
@Override
public List<HoursGroup> getHoursGroups() {
return new ArrayList<HoursGroup>(hoursGroups);
return new ArrayList<>(hoursGroups);
}
public Set<HoursGroup> myHoursGroups() {
@ -214,8 +222,8 @@ public class OrderLine extends OrderElement {
@Override
public BigDecimal getAdvancePercentage(LocalDate date) {
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (directAdvanceAssignment.getReportGlobalAdvance()) {
if (date == null) {
if ( directAdvanceAssignment.getReportGlobalAdvance() ) {
if ( date == null ) {
return directAdvanceAssignment.getAdvancePercentage();
}
return directAdvanceAssignment.getAdvancePercentage(date);
@ -225,13 +233,12 @@ public class OrderLine extends OrderElement {
return BigDecimal.ZERO;
}
public Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(
AdvanceType advanceType) {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
public Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(AdvanceType advanceType) {
Set<DirectAdvanceAssignment> result = new HashSet<>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (directAdvanceAssignment.getAdvanceType().getUnitName().equals(
advanceType.getUnitName())) {
if ( directAdvanceAssignment.getAdvanceType().getUnitName().equals(advanceType.getUnitName()) ) {
result.add(directAdvanceAssignment);
return result;
}
}
@ -239,8 +246,7 @@ public class OrderLine extends OrderElement {
}
@Override
public Set<IndirectAdvanceAssignment> getAllIndirectAdvanceAssignments(
AdvanceType advanceType) {
public Set<IndirectAdvanceAssignment> getAllIndirectAdvanceAssignments(AdvanceType advanceType) {
return Collections.emptySet();
}
@ -251,27 +257,25 @@ public class OrderLine extends OrderElement {
@Override
protected Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignmentsReportGlobal() {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
Set<DirectAdvanceAssignment> result = new HashSet<>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (directAdvanceAssignment.getReportGlobalAdvance()) {
if ( directAdvanceAssignment.getReportGlobalAdvance() ) {
result.add(directAdvanceAssignment);
return result;
}
}
return result;
}
public boolean existSameCriterionRequirement(
CriterionRequirement newRequirement) {
return criterionRequirementHandler
.existSameCriterionRequirementIntoOrderLine(this,
newRequirement);
public boolean existSameCriterionRequirement(CriterionRequirement newRequirement) {
return criterionRequirementHandler.existSameCriterionRequirementIntoOrderLine(this, newRequirement);
}
@Override
public DirectAdvanceAssignment getReportGlobalAdvanceAssignment() {
for (DirectAdvanceAssignment directAdvanceAssignment : getDirectAdvanceAssignments()) {
if (directAdvanceAssignment.getReportGlobalAdvance()) {
if ( directAdvanceAssignment.getReportGlobalAdvance() ) {
return directAdvanceAssignment;
}
}
@ -281,7 +285,7 @@ public class OrderLine extends OrderElement {
@Override
public void removeReportGlobalAdvanceAssignment() {
AdvanceAssignment advanceAssignment = getReportGlobalAdvanceAssignment();
if (advanceAssignment != null) {
if ( advanceAssignment != null ) {
advanceAssignment.setReportGlobalAdvance(false);
}
markAsDirtyLastAdvanceMeasurementForSpreading();
@ -289,7 +293,7 @@ public class OrderLine extends OrderElement {
public boolean containsHoursGroup(String code) {
for (HoursGroup hoursGroup : getHoursGroups()) {
if (hoursGroup.getCode().equals(code)) {
if ( hoursGroup.getCode().equals(code) ) {
return true;
}
}
@ -297,12 +301,12 @@ public class OrderLine extends OrderElement {
}
public HoursGroup getHoursGroup(String code) {
if (code == null) {
if ( code == null ) {
return null;
}
for (HoursGroup hoursGroup : getHoursGroups()) {
if (hoursGroup.getCode().equals(code)) {
if ( hoursGroup.getCode().equals(code) ) {
return hoursGroup;
}
}
@ -315,7 +319,7 @@ public class OrderLine extends OrderElement {
}
public void incrementLastHoursGroupSequenceCode() {
if (lastHoursGroupSequenceCode == null) {
if ( lastHoursGroupSequenceCode == null ) {
lastHoursGroupSequenceCode = 0;
}
lastHoursGroupSequenceCode++;
@ -328,11 +332,11 @@ public class OrderLine extends OrderElement {
@AssertTrue(message = "Code already included in Hours Group codes")
public boolean isHoursGroupsCodeNotRepeatedConstraint() {
Set<String> codes = new HashSet<String>();
Set<String> codes = new HashSet<>();
for (HoursGroup hoursGroup : getHoursGroups()) {
String code = hoursGroup.getCode();
if (codes.contains(code)) {
if ( codes.contains(code) ) {
return false;
}
codes.add(code);
@ -348,6 +352,7 @@ public class OrderLine extends OrderElement {
@Override
public DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment(
IndirectAdvanceAssignment indirectAdvanceAssignment) {
return null;
}
@ -371,10 +376,9 @@ public class OrderLine extends OrderElement {
super.setCode(code);
Order order = getOrder();
if ((order != null) && (!order.isCodeAutogenerated())) {
if ( (order != null) && (!order.isCodeAutogenerated()) ) {
for (HoursGroup hoursGroup : getHoursGroups()) {
if ((hoursGroup.getCode() == null)
|| (hoursGroup.getCode().isEmpty())) {
if ( (hoursGroup.getCode() == null) || (hoursGroup.getCode().isEmpty()) ) {
hoursGroup.setCode(code);
}
}
@ -382,8 +386,7 @@ public class OrderLine extends OrderElement {
}
public void setBudget(BigDecimal budget) {
Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0,
"budget cannot be negative");
Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0, "budget cannot be negative");
this.budget = budget.setScale(2, RoundingMode.HALF_UP);
}

View file

@ -60,8 +60,7 @@ import org.libreplan.business.trees.ITreeParentNode;
/**
* Represents every container in the WBS view. A task of the WBS that has some
* children.<br />
* Represents every container in the WBS view. A task of the WBS that has some children.<br />
*
* The project itself is also an {@link OrderLineGroup}.
*
@ -98,7 +97,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
protected void onChildAddedAdditionalActions(OrderElement newChild) {
updateCriterionRequirements();
newChild.updateLabels();
if (!newChild.isNewObject()) {
if ( !newChild.isNewObject() ) {
getOrder().markAsNeededToRecalculateSumChargedEfforts();
getOrder().markAsNeededToRecalculateSumExpenses();
}
@ -106,10 +105,12 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
protected void onChildRemovedAdditionalActions(OrderElement removedChild) {
if (removedChild.isScheduled() && getThis().isScheduled()) {
if ( removedChild.isScheduled() && getThis().isScheduled() ) {
removeChildTask(removedChild);
}
updateCriterionRequirements();
if ( !removedChild.isNewObject() ) {
getOrder().markAsNeededToRecalculateSumChargedEfforts();
getOrder().markAsNeededToRecalculateSumExpenses();
@ -169,12 +170,12 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
public static OrderLineGroup create() {
OrderLineGroup result = new OrderLineGroup();
result.setNewObject(true);
return result;
}
public static OrderLineGroup createUnvalidated(String code) {
OrderLineGroup orderLineGroup = create(new OrderLineGroup(), code);
return orderLineGroup;
return create(new OrderLineGroup(), code);
}
public void addChildrenAdvanceOrderLineGroup() {
@ -198,13 +199,19 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
protected void updateSpreadAdvance() {
if ( getReportGlobalAdvanceAssignment() == null ) {
boolean condition;
// Set CHILDREN type as spread if any
String type = PredefinedAdvancedTypes.CHILDREN.getTypeName();
for (IndirectAdvanceAssignment each : indirectAdvanceAssignments) {
if ( each.getAdvanceType() != null &&
condition = each.getAdvanceType() != null &&
each.getAdvanceType().getType() != null &&
each.getAdvanceType().getType().equals(type) ) {
each.getAdvanceType().getType().equals(type);
if ( condition ) {
each.setReportGlobalAdvance(true);
return;
}
}
@ -225,17 +232,16 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
public IndirectAdvanceAssignment getChildrenAdvance() {
for (IndirectAdvanceAssignment advance : getIndirectAdvanceAssignments()) {
if (advance.getAdvanceType().getUnitName().equals(
PredefinedAdvancedTypes.CHILDREN.getTypeName())) {
if ( advance.getAdvanceType().getUnitName().equals(PredefinedAdvancedTypes.CHILDREN.getTypeName()) ) {
return advance;
}
}
return null;
}
private List<OrderElement> children = new ArrayList<OrderElement>();
private List<OrderElement> children = new ArrayList<>();
private Set<IndirectAdvanceAssignment> indirectAdvanceAssignments = new HashSet<IndirectAdvanceAssignment>();
private Set<IndirectAdvanceAssignment> indirectAdvanceAssignments = new HashSet<>();
/**
* Constructor for hibernate. Do not use!
@ -247,7 +253,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
@Valid
public List<OrderElement> getChildren() {
return new ArrayList<OrderElement>(children);
return new ArrayList<>(children);
}
@Override
@ -355,7 +361,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
private static Set<DirectAdvanceAssignment> copyDirectAdvanceAssignments(OrderElement origin,
OrderElement destination) {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
Set<DirectAdvanceAssignment> result = new HashSet<>();
for (DirectAdvanceAssignment each : origin.directAdvanceAssignments) {
result.add(DirectAdvanceAssignment.copy(each, destination));
}
@ -363,7 +369,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
private static Set<MaterialAssignment> copyMaterialAssignments(OrderElement origin, OrderElement destination) {
Set<MaterialAssignment> result = new HashSet<MaterialAssignment>();
Set<MaterialAssignment> result = new HashSet<>();
for (MaterialAssignment each : origin.materialAssignments) {
result.add(MaterialAssignment.copy(each, destination));
}
@ -371,7 +377,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
private static Set<Label> copyLabels(OrderElement origin, OrderElement destination) {
Set<Label> result = new HashSet<Label>();
Set<Label> result = new HashSet<>();
for (Label each : origin.labels) {
destination.addLabel(each);
result.add(each);
@ -380,7 +386,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
private static Set<TaskQualityForm> copyTaskQualityForms(OrderElement origin, OrderElement destination) {
Set<TaskQualityForm> result = new HashSet<TaskQualityForm>();
Set<TaskQualityForm> result = new HashSet<>();
for (TaskQualityForm each : origin.taskQualityForms) {
result.add(TaskQualityForm.copy(each, destination));
}
@ -414,7 +420,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
public List<HoursGroup> getHoursGroups() {
List<HoursGroup> hoursGroups = new ArrayList<HoursGroup>();
List<HoursGroup> hoursGroups = new ArrayList<>();
for (OrderElement orderElement : children) {
hoursGroups.addAll(orderElement.getHoursGroups());
}
@ -423,7 +429,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
public BigDecimal getAdvancePercentage(AdvanceType advanceType, LocalDate date) {
final DirectAdvanceAssignment directAdvanceAssignment = this.getAdvanceAssignmentByType(advanceType);
if (directAdvanceAssignment != null) {
if ( directAdvanceAssignment != null ) {
return directAdvanceAssignment.getAdvancePercentage(date);
}
return null;
@ -496,15 +502,16 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
public DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment(
IndirectAdvanceAssignment indirectAdvanceAssignment) {
if ( indirectAdvanceAssignment.getAdvanceType().getUnitName().equals(
PredefinedAdvancedTypes.CHILDREN.getTypeName()) ) {
boolean condition = indirectAdvanceAssignment.getAdvanceType().getUnitName()
.equals(PredefinedAdvancedTypes.CHILDREN.getTypeName());
if ( condition ) {
return calculateFakeDirectAdvanceAssignmentChildren(indirectAdvanceAssignment);
} else {
Set<DirectAdvanceAssignment> directAdvanceAssignments =
getAllDirectAdvanceAssignments(indirectAdvanceAssignment.getAdvanceType());
return mergeAdvanceAssignments(new ArrayList<DirectAdvanceAssignment>(directAdvanceAssignments));
return mergeAdvanceAssignments(new ArrayList<>(directAdvanceAssignments));
}
}
@ -517,18 +524,19 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
newDirectAdvanceAssignment.setAdvanceType(indirectAdvanceAssignment.getAdvanceType());
newDirectAdvanceAssignment.setOrderElement(this);
Set<DirectAdvanceAssignment> directAdvanceAssignments = new HashSet<DirectAdvanceAssignment>();
Set<DirectAdvanceAssignment> directAdvanceAssignments = new HashSet<>();
for (OrderElement orderElement : children) {
directAdvanceAssignments.addAll(orderElement.getAllDirectAdvanceAssignmentsReportGlobal());
}
List<AdvanceMeasurement> advanceMeasurements = new ArrayList<AdvanceMeasurement>();
List<AdvanceMeasurement> advanceMeasurements = new ArrayList<>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
advanceMeasurements.addAll(directAdvanceAssignment.getAdvanceMeasurements());
}
List<LocalDate> measurementDates = getMeasurementDates(advanceMeasurements);
SortedSet<AdvanceMeasurement> newAdvanceMeasurements = new TreeSet<AdvanceMeasurement>(new AdvanceMeasurementComparator());
SortedSet<AdvanceMeasurement> newAdvanceMeasurements = new TreeSet<>(new AdvanceMeasurementComparator());
for (LocalDate localDate : measurementDates) {
BigDecimal value = getAdvancePercentageChildren(localDate).multiply(new BigDecimal(100));
AdvanceMeasurement advanceMeasurement = AdvanceMeasurement.create(localDate, value);
@ -540,12 +548,11 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
return newDirectAdvanceAssignment;
}
private List<LocalDate> getMeasurementDates(
List<AdvanceMeasurement> advanceMeasurements) {
List<LocalDate> result = new ArrayList<LocalDate>();
private List<LocalDate> getMeasurementDates(List<AdvanceMeasurement> advanceMeasurements) {
List<LocalDate> result = new ArrayList<>();
for (AdvanceMeasurement advanceMeasurement : advanceMeasurements) {
LocalDate date = advanceMeasurement.getDate();
if (result.indexOf(date) < 0) {
if ( result.indexOf(date) < 0 ) {
result.add(date);
}
}
@ -555,73 +562,68 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
return result;
}
private DirectAdvanceAssignment mergeAdvanceAssignments(
List<DirectAdvanceAssignment> list) {
if (list.isEmpty()) {
private DirectAdvanceAssignment mergeAdvanceAssignments(List<DirectAdvanceAssignment> list) {
if ( list.isEmpty() ) {
return null;
}
Iterator<DirectAdvanceAssignment> iterator = list.iterator();
DirectAdvanceAssignment origAdvanceAssignment = iterator.next();
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create();
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment.create();
directAdvanceAssignment.setFake(true);
directAdvanceAssignment
.setMaxValue(origAdvanceAssignment.getMaxValue());
directAdvanceAssignment
.setAdvanceType(origAdvanceAssignment.getAdvanceType());
directAdvanceAssignment.setMaxValue(origAdvanceAssignment.getMaxValue());
directAdvanceAssignment.setAdvanceType(origAdvanceAssignment.getAdvanceType());
directAdvanceAssignment.setOrderElement(this);
directAdvanceAssignment.setAdvanceMeasurements(origAdvanceAssignment
.getAdvanceMeasurements());
directAdvanceAssignment.setAdvanceMeasurements(origAdvanceAssignment.getAdvanceMeasurements());
while (iterator.hasNext()) {
DirectAdvanceAssignment tempAssignment = iterator.next();
if (!directAdvanceAssignment.getAdvanceType().getPercentage()) {
if ( !directAdvanceAssignment.getAdvanceType().getPercentage() ) {
BigDecimal maxValue = tempAssignment.getMaxValue();
maxValue = maxValue.add(directAdvanceAssignment.getMaxValue());
directAdvanceAssignment.setMaxValue(maxValue);
}
SortedSet<AdvanceMeasurement> advanceMeasurements = new TreeSet<AdvanceMeasurement>(
new AdvanceMeasurementComparator());
SortedSet<AdvanceMeasurement> advanceMeasurements = new TreeSet<>(new AdvanceMeasurementComparator());
advanceMeasurements.addAll(mergeAdvanceMeasurements(
directAdvanceAssignment, new ArrayList<AdvanceMeasurement>(
directAdvanceAssignment.getAdvanceMeasurements()),
new ArrayList<AdvanceMeasurement>(tempAssignment
.getAdvanceMeasurements())));
directAdvanceAssignment,
new ArrayList<>(directAdvanceAssignment.getAdvanceMeasurements()),
new ArrayList<>(tempAssignment.getAdvanceMeasurements())));
directAdvanceAssignment.setAdvanceMeasurements(advanceMeasurements);
}
return directAdvanceAssignment;
}
private List<AdvanceMeasurement> mergeAdvanceMeasurements(
AdvanceAssignment advanceAssignment, List<AdvanceMeasurement> one,
List<AdvanceMeasurement> other) {
private List<AdvanceMeasurement> mergeAdvanceMeasurements(AdvanceAssignment advanceAssignment,
List<AdvanceMeasurement> one,
List<AdvanceMeasurement> other) {
Collections.reverse(one);
Collections.reverse(other);
ArrayList<AdvanceMeasurement> list = new ArrayList<AdvanceMeasurement>();
ArrayList<AdvanceMeasurement> list = new ArrayList<>();
mergeAdvanceMeasurements(advanceAssignment, one, other, list);
return list;
}
private void mergeAdvanceMeasurements(AdvanceAssignment advanceAssignment,
List<AdvanceMeasurement> list1, List<AdvanceMeasurement> list2,
List<AdvanceMeasurement> result) {
List<AdvanceMeasurement> list1, List<AdvanceMeasurement> list2,
List<AdvanceMeasurement> result) {
Iterator<AdvanceMeasurement> iterator1 = list1.iterator();
Iterator<AdvanceMeasurement> iterator2 = list2.iterator();
AdvanceMeasurement next1;
if (iterator1.hasNext()) {
if ( iterator1.hasNext() ) {
next1 = iterator1.next();
} else {
next1 = null;
}
AdvanceMeasurement next2;
if (iterator2.hasNext()) {
if ( iterator2.hasNext() ) {
next2 = iterator2.next();
} else {
next2 = null;
@ -636,44 +638,45 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
Date communicationDate;
BigDecimal totalHours = null;
if (advanceAssignment.getAdvanceType().getPercentage()) {
totalHours = new BigDecimal(advanceAssignment.getOrderElement()
.getWorkHours());
if ( advanceAssignment.getAdvanceType().getPercentage() ) {
totalHours = new BigDecimal(advanceAssignment.getOrderElement().getWorkHours());
}
while ((next1 != null) && (next2 != null)) {
if (next1.getDate().compareTo(next2.getDate()) < 0) {
if ( next1.getDate().compareTo(next2.getDate()) < 0 ) {
date = next1.getDate();
add = next1.getValue().subtract(previous1);
communicationDate = next1.getCommunicationDate();
previous1 = next1.getValue();
if (advanceAssignment.getAdvanceType().getPercentage()) {
BigDecimal orderElementHours = new BigDecimal(next1
.getAdvanceAssignment().getOrderElement()
.getWorkHours());
if ( advanceAssignment.getAdvanceType().getPercentage() ) {
BigDecimal orderElementHours =
new BigDecimal(next1.getAdvanceAssignment().getOrderElement().getWorkHours());
add = addMeasure(add, totalHours, orderElementHours);
}
if (iterator1.hasNext()) {
if ( iterator1.hasNext() ) {
next1 = iterator1.next();
} else {
next1 = null;
}
} else if (next1.getDate().compareTo(next2.getDate()) > 0) {
} else if ( next1.getDate().compareTo(next2.getDate() ) > 0) {
date = next2.getDate();
add = next2.getValue().subtract(previous2);
communicationDate = next2.getCommunicationDate();
previous2 = next2.getValue();
if (advanceAssignment.getAdvanceType().getPercentage()) {
BigDecimal orderElementHours = new BigDecimal(next2
.getAdvanceAssignment().getOrderElement()
.getWorkHours());
if ( advanceAssignment.getAdvanceType().getPercentage() ) {
BigDecimal orderElementHours =
new BigDecimal(next2.getAdvanceAssignment().getOrderElement().getWorkHours());
add = addMeasure(add, totalHours, orderElementHours);
}
if (iterator2.hasNext()) {
if ( iterator2.hasNext() ) {
next2 = iterator2.next();
} else {
next2 = null;
@ -683,20 +686,20 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
BigDecimal add1 = next1.getValue().subtract(previous1);
BigDecimal add2 = next2.getValue().subtract(previous2);
add = add1.add(add2);
communicationDate = getGreatestDate(next1
.getCommunicationDate(), next2.getCommunicationDate());
communicationDate = getGreatestDate(next1.getCommunicationDate(), next2.getCommunicationDate());
previous1 = next1.getValue();
previous2 = next2.getValue();
if (advanceAssignment.getAdvanceType().getPercentage()) {
BigDecimal orderElementHours1 = new BigDecimal(next1
.getAdvanceAssignment().getOrderElement()
.getWorkHours());
if ( advanceAssignment.getAdvanceType().getPercentage() ) {
BigDecimal orderElementHours1 =
new BigDecimal(next1.getAdvanceAssignment().getOrderElement().getWorkHours());
add1 = addMeasure(add1, totalHours, orderElementHours1);
BigDecimal orderElementHours2 = new BigDecimal(next2
.getAdvanceAssignment().getOrderElement()
.getWorkHours());
BigDecimal orderElementHours2 =
new BigDecimal(next2.getAdvanceAssignment().getOrderElement().getWorkHours());
add2 = addMeasure(add2, totalHours, orderElementHours2);
add = add1.add(add2);
}
@ -728,14 +731,15 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
communicationDate = next1.getCommunicationDate();
previous1 = next1.getValue();
if (advanceAssignment.getAdvanceType().getPercentage()) {
BigDecimal orderElementHours = new BigDecimal(next1
.getAdvanceAssignment().getOrderElement()
.getWorkHours());
if ( advanceAssignment.getAdvanceType().getPercentage() ) {
BigDecimal orderElementHours =
new BigDecimal(next1.getAdvanceAssignment().getOrderElement().getWorkHours());
add = addMeasure(add, totalHours, orderElementHours);
}
if (iterator1.hasNext()) {
if ( iterator1.hasNext() ) {
next1 = iterator1.next();
} else {
next1 = null;
@ -756,14 +760,15 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
communicationDate = next2.getCommunicationDate();
previous2 = next2.getValue();
if (advanceAssignment.getAdvanceType().getPercentage()) {
BigDecimal orderElementHours = new BigDecimal(next2
.getAdvanceAssignment().getOrderElement()
.getWorkHours());
if ( advanceAssignment.getAdvanceType().getPercentage() ) {
BigDecimal orderElementHours =
new BigDecimal(next2.getAdvanceAssignment().getOrderElement().getWorkHours());
add = addMeasure(add, totalHours, orderElementHours);
}
if (iterator2.hasNext()) {
if ( iterator2.hasNext() ) {
next2 = iterator2.next();
} else {
next2 = null;
@ -780,23 +785,23 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
private void checkAndSetValue(AdvanceMeasurement advanceMeasurement,
BigDecimal previousResult) {
private void checkAndSetValue(AdvanceMeasurement advanceMeasurement, BigDecimal previousResult) {
advanceMeasurement.setValue(previousResult);
if (!advanceMeasurement
.isValidPrecisionConstraint()) {
AdvanceAssignment advanceAssignment = advanceMeasurement
.getAdvanceAssignment();
if ((previousResult == null) || (advanceAssignment == null)
|| (advanceAssignment.getAdvanceType() == null)) {
if ( !advanceMeasurement.isValidPrecisionConstraint() ) {
AdvanceAssignment advanceAssignment = advanceMeasurement.getAdvanceAssignment();
boolean condition = (previousResult == null) ||
(advanceAssignment == null) ||
(advanceAssignment.getAdvanceType() == null);
if ( condition ) {
return;
}
BigDecimal precision = advanceAssignment.getAdvanceType()
.getUnitPrecision();
BigDecimal precision = advanceAssignment.getAdvanceType().getUnitPrecision();
BigDecimal result[] = previousResult.divideAndRemainder(precision);
BigDecimal checkResult;
if (previousResult.compareTo(result[1]) >= 0) {
if ( previousResult.compareTo(result[1]) >= 0 ) {
checkResult = previousResult.subtract(result[1]);
} else {
checkResult = previousResult.add(result[1]);
@ -805,11 +810,9 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
}
private BigDecimal addMeasure(BigDecimal add, BigDecimal totalHours,
BigDecimal orderElementHours) {
if ((totalHours != null) && (totalHours.compareTo(BigDecimal.ZERO) > 0)) {
add = add.multiply(orderElementHours).divide(totalHours,
RoundingMode.DOWN);
private BigDecimal addMeasure(BigDecimal add, BigDecimal totalHours, BigDecimal orderElementHours) {
if ( (totalHours != null) && (totalHours.compareTo(BigDecimal.ZERO) > 0) ) {
add = add.multiply(orderElementHours).divide(totalHours, RoundingMode.DOWN);
} else {
add = add.multiply(orderElementHours);
}
@ -826,7 +829,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
public Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(AdvanceType advanceType) {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
Set<DirectAdvanceAssignment> result = new HashSet<>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if ( directAdvanceAssignment.getAdvanceType().getUnitName().equals(advanceType.getUnitName()) ) {
@ -844,10 +847,10 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
public Set<IndirectAdvanceAssignment> getAllIndirectAdvanceAssignments(AdvanceType advanceType) {
Set<IndirectAdvanceAssignment> result = new HashSet<IndirectAdvanceAssignment>();
Set<IndirectAdvanceAssignment> result = new HashSet<>();
IndirectAdvanceAssignment indirectAdvanceAssignment = getIndirectAdvanceAssignment(advanceType);
if( indirectAdvanceAssignment != null ){
if ( indirectAdvanceAssignment != null ) {
result.add(indirectAdvanceAssignment);
}
@ -869,7 +872,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
protected Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignmentsReportGlobal() {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
Set<DirectAdvanceAssignment> result = new HashSet<>();
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if ( directAdvanceAssignment.getReportGlobalAdvance() ) {
@ -886,7 +889,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
protected Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments() {
Set<DirectAdvanceAssignment> result = new HashSet<DirectAdvanceAssignment>();
Set<DirectAdvanceAssignment> result = new HashSet<>();
result.addAll(directAdvanceAssignments);
@ -960,7 +963,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
if ( !newAdvanceAssignment.getReportGlobalAdvance() ) {
return;
}
Set<AdvanceAssignment> advanceAssignments = new HashSet<AdvanceAssignment>();
Set<AdvanceAssignment> advanceAssignments = new HashSet<>();
advanceAssignments.addAll(directAdvanceAssignments);
advanceAssignments.addAll(indirectAdvanceAssignments);
for (AdvanceAssignment advanceAssignment : advanceAssignments) {
@ -979,13 +982,13 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
public DirectAdvanceAssignment getReportGlobalAdvanceAssignment() {
for (DirectAdvanceAssignment directAdvanceAssignment : getDirectAdvanceAssignments()) {
if (directAdvanceAssignment.getReportGlobalAdvance()) {
if ( directAdvanceAssignment.getReportGlobalAdvance() ) {
return directAdvanceAssignment;
}
}
for (IndirectAdvanceAssignment indirectAdvanceAssignment : getIndirectAdvanceAssignments()) {
if (indirectAdvanceAssignment.getReportGlobalAdvance()) {
if ( indirectAdvanceAssignment.getReportGlobalAdvance() ) {
return calculateFakeDirectAdvanceAssignment(indirectAdvanceAssignment);
}
}
@ -994,18 +997,18 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@Override
public void removeReportGlobalAdvanceAssignment() {
Set<AdvanceAssignment> advanceAssignments = new HashSet<AdvanceAssignment>();
Set<AdvanceAssignment> advanceAssignments = new HashSet<>();
advanceAssignments.addAll(getDirectAdvanceAssignments());
advanceAssignments.addAll(getIndirectAdvanceAssignments());
AdvanceAssignment advanceAssignment = null;
for (AdvanceAssignment each : advanceAssignments) {
if (each.getReportGlobalAdvance()) {
if ( each.getReportGlobalAdvance() ) {
advanceAssignment = each;
}
}
if (advanceAssignment != null) {
if ( advanceAssignment != null ) {
advanceAssignment.setReportGlobalAdvance(false);
}
markAsDirtyLastAdvanceMeasurementForSpreading();
@ -1013,12 +1016,12 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
public DirectAdvanceAssignment getAdvanceAssignmentByType(AdvanceType type) {
DirectAdvanceAssignment result = getDirectAdvanceAssignmentByType(type);
if (result != null) {
if ( result != null ) {
return result;
}
for (IndirectAdvanceAssignment each : getIndirectAdvanceAssignments()) {
if (type != null && each.getAdvanceType().getId().equals(type.getId())) {
if ( type != null && each.getAdvanceType().getId().equals(type.getId()) ) {
return calculateFakeDirectAdvanceAssignment(each);
}
}
@ -1070,13 +1073,13 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
public OrderElement findRepeatedOrderCode() {
Set<String> codes = new HashSet<String>();
Set<String> codes = new HashSet<>();
codes.add(getCode());
for (OrderElement each : getAllOrderElements()) {
String code = each.getCode();
if (code != null && !code.isEmpty()) {
if (codes.contains(code)) {
if ( code != null && !code.isEmpty() ) {
if ( codes.contains(code) ) {
return each;
}
codes.add(code);
@ -1087,12 +1090,12 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
public HoursGroup findRepeatedHoursGroupCode() {
Set<String> codes = new HashSet<String>();
Set<String> codes = new HashSet<>();
for (HoursGroup hoursGroup : getHoursGroups()) {
String code = hoursGroup.getCode();
if (code != null && !code.isEmpty()) {
if (codes.contains(code)) {
if ( code != null && !code.isEmpty() ) {
if ( codes.contains(code) ) {
return hoursGroup;
}
codes.add(code);
@ -1103,8 +1106,7 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
}
public List<OrderElement> getAllOrderElements() {
List<OrderElement> result = new ArrayList<OrderElement>(
this.getChildren());
List<OrderElement> result = new ArrayList<>(this.getChildren());
for (OrderElement orderElement : this.getChildren()) {
result.addAll(orderElement.getAllChildren());
}
@ -1113,10 +1115,10 @@ public class OrderLineGroup extends OrderElement implements ITreeParentNode<Orde
@AssertTrue(message = "indirect progress assignments should have different types")
public boolean isIndirectAdvanceAssignmentsWithDifferentTypeConstraint() {
Set<String> types = new HashSet<String>();
Set<String> types = new HashSet<>();
for (IndirectAdvanceAssignment each : indirectAdvanceAssignments) {
String type = each.getAdvanceType().getUnitName();
if (types.contains(type)) {
if ( types.contains(type) ) {
return false;
}
types.add(type);

View file

@ -69,13 +69,11 @@ public class SumChargedEffort extends BaseEntity {
}
public void addDirectChargedEffort(EffortDuration directChargedEffort) {
this.directChargedEffort = this.directChargedEffort
.plus(directChargedEffort);
this.directChargedEffort = this.directChargedEffort.plus(directChargedEffort);
}
public void subtractDirectChargedEffort(EffortDuration directChargedEffort) {
this.directChargedEffort = this.directChargedEffort
.minus(directChargedEffort);
this.directChargedEffort = this.directChargedEffort.minus(directChargedEffort);
}
public EffortDuration getDirectChargedEffort() {
@ -83,14 +81,11 @@ public class SumChargedEffort extends BaseEntity {
}
public void addIndirectChargedEffort(EffortDuration indirectChargedEffort) {
this.indirectChargedEffort = this.indirectChargedEffort
.plus(indirectChargedEffort);
this.indirectChargedEffort = this.indirectChargedEffort.plus(indirectChargedEffort);
}
public void subtractIndirectChargedEffort(
EffortDuration indirectChargedEffort) {
this.indirectChargedEffort = this.indirectChargedEffort
.minus(indirectChargedEffort);
public void subtractIndirectChargedEffort(EffortDuration indirectChargedEffort) {
this.indirectChargedEffort = this.indirectChargedEffort.minus(indirectChargedEffort);
}
public EffortDuration getIndirectChargedEffort() {
@ -128,8 +123,7 @@ public class SumChargedEffort extends BaseEntity {
this.lastTimesheetDate = lastTimesheetDate;
}
public void setTimesheetDates(Date firstTimesheetDate,
Date lastTimesheetDate) {
public void setTimesheetDates(Date firstTimesheetDate, Date lastTimesheetDate) {
setFirstTimesheetDate(firstTimesheetDate);
setLastTimesheetDate(lastTimesheetDate);
}

View file

@ -24,8 +24,6 @@ package org.libreplan.business.planner.entities;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
@ -50,12 +48,12 @@ public class SubcontractedTaskData extends BaseEntity {
public static SubcontractedTaskData create(Task task) {
SubcontractedTaskData subcontractedTaskData = new SubcontractedTaskData(task);
subcontractedTaskData.subcontratationDate = new Date();
return create(subcontractedTaskData);
}
public static SubcontractedTaskData createFrom(
SubcontractedTaskData subcontractedTaskData) {
if (subcontractedTaskData == null) {
public static SubcontractedTaskData createFrom(SubcontractedTaskData subcontractedTaskData) {
if ( subcontractedTaskData == null ) {
return null;
}
@ -73,8 +71,10 @@ public class SubcontractedTaskData extends BaseEntity {
result.hoursGroupsExported = subcontractedTaskData.hoursGroupsExported;
result.setState(subcontractedTaskData.getState());
result.setRequiredDeliveringDates(subcontractedTaskData.getRequiredDeliveringDates());
result.setEndDatesCommunicatedFromSubcontractor(subcontractedTaskData
.getEndDatesCommunicatedFromSubcontractor());
result.setEndDatesCommunicatedFromSubcontractor(
subcontractedTaskData.getEndDatesCommunicatedFromSubcontractor());
return create(result);
}
@ -100,13 +100,11 @@ public class SubcontractedTaskData extends BaseEntity {
private SubcontractState state = SubcontractState.PENDING_INITIAL_SEND;
private final SortedSet<SubcontractorDeliverDate> requiredDeliveringDates = new TreeSet<SubcontractorDeliverDate>(
new DeliverDateComparator());
private final SortedSet<SubcontractorDeliverDate> requiredDeliveringDates =
new TreeSet<>(new DeliverDateComparator());
private Set<SubcontractorCommunication> subcontractorCommunications = new HashSet<SubcontractorCommunication>();
private SortedSet<EndDateCommunication> endDatesCommunicatedFromSubcontractor = new TreeSet<EndDateCommunication>(
new EndDateCommunicationComparator());
private SortedSet<EndDateCommunication> endDatesCommunicatedFromSubcontractor =
new TreeSet<>(new EndDateCommunicationComparator());
/**
* Constructor for hibernate. Do not use!
@ -136,8 +134,7 @@ public class SubcontractedTaskData extends BaseEntity {
return subcontractCommunicationDate;
}
public void setSubcontractCommunicationDate(
Date subcontractCommunicationDate) {
public void setSubcontractCommunicationDate(Date subcontractCommunicationDate) {
this.subcontractCommunicationDate = subcontractCommunicationDate;
}
@ -166,58 +163,60 @@ public class SubcontractedTaskData extends BaseEntity {
}
public boolean isNodeWithoutChildrenExported() {
if (nodeWithoutChildrenExported == null) {
if ( nodeWithoutChildrenExported == null ) {
return false;
}
return nodeWithoutChildrenExported;
}
public void setNodeWithoutChildrenExported(
Boolean nodeWithoutChildrenExported) {
if (nodeWithoutChildrenExported == null) {
public void setNodeWithoutChildrenExported(Boolean nodeWithoutChildrenExported) {
if ( nodeWithoutChildrenExported == null ) {
nodeWithoutChildrenExported = false;
}
this.nodeWithoutChildrenExported = nodeWithoutChildrenExported;
}
public boolean isLabelsExported() {
if (labelsExported == null) {
if ( labelsExported == null ) {
return false;
}
return labelsExported;
}
public void setLabelsExported(Boolean labelsExported) {
if (labelsExported == null) {
if ( labelsExported == null ) {
labelsExported = false;
}
this.labelsExported = labelsExported;
}
public Boolean isMaterialAssignmentsExported() {
if (materialAssignmentsExported == null) {
if ( materialAssignmentsExported == null ) {
return false;
}
return materialAssignmentsExported;
}
public void setMaterialAssignmentsExported(
Boolean materialAssignmentsExported) {
if (materialAssignmentsExported == null) {
public void setMaterialAssignmentsExported(Boolean materialAssignmentsExported) {
if ( materialAssignmentsExported == null ) {
materialAssignmentsExported = false;
}
this.materialAssignmentsExported = materialAssignmentsExported;
}
public Boolean isHoursGroupsExported() {
if (hoursGroupsExported == null) {
if ( hoursGroupsExported == null ) {
return false;
}
return hoursGroupsExported;
}
public void setHoursGroupsExported(Boolean hoursGroupsExported) {
if (hoursGroupsExported == null) {
if ( hoursGroupsExported == null ) {
hoursGroupsExported = false;
}
this.hoursGroupsExported = hoursGroupsExported;
@ -241,17 +240,13 @@ public class SubcontractedTaskData extends BaseEntity {
this.hoursGroupsExported = subcontratedTask.hoursGroupsExported;
this.state = subcontratedTask.getState();
this.setRequiredDeliveringDates(subcontratedTask.getRequiredDeliveringDates());
this.setEndDatesCommunicatedFromSubcontractor(subcontratedTask
.getEndDatesCommunicatedFromSubcontractor());
this.setEndDatesCommunicatedFromSubcontractor(subcontratedTask.getEndDatesCommunicatedFromSubcontractor());
}
@AssertTrue(message = "external company should be subcontractor")
public boolean isExternalCompanyIsSubcontractorConstraint() {
if (!firstLevelValidationsPassed()) {
return true;
}
return !firstLevelValidationsPassed() || externalCompany.isSubcontractor();
return externalCompany.isSubcontractor();
}
private boolean firstLevelValidationsPassed() {
@ -268,12 +263,10 @@ public class SubcontractedTaskData extends BaseEntity {
}
public boolean isSendable() {
return state.isSendable()
&& externalCompany.getInteractsWithApplications();
return state.isSendable() && externalCompany.getInteractsWithApplications();
}
public void setRequiredDeliveringDates(
SortedSet<SubcontractorDeliverDate> requiredDeliveringDates) {
public void setRequiredDeliveringDates(SortedSet<SubcontractorDeliverDate> requiredDeliveringDates) {
this.requiredDeliveringDates.clear();
this.requiredDeliveringDates.addAll(requiredDeliveringDates);
}
@ -283,33 +276,31 @@ public class SubcontractedTaskData extends BaseEntity {
return Collections.unmodifiableSortedSet(this.requiredDeliveringDates);
}
public void addRequiredDeliveringDates(
SubcontractorDeliverDate subDeliverDate) {
public void addRequiredDeliveringDates(SubcontractorDeliverDate subDeliverDate) {
this.requiredDeliveringDates.add(subDeliverDate);
}
public void removeRequiredDeliveringDates(
SubcontractorDeliverDate subcontractorDeliverDate) {
public void removeRequiredDeliveringDates(SubcontractorDeliverDate subcontractorDeliverDate) {
this.requiredDeliveringDates.remove(subcontractorDeliverDate);
}
public void updateFirstRequiredDeliverDate(Date subcontractCommunicationDate){
if(this.requiredDeliveringDates != null && !this.requiredDeliveringDates.isEmpty()){
if ( this.requiredDeliveringDates != null && !this.requiredDeliveringDates.isEmpty() ) {
this.requiredDeliveringDates.first().setCommunicationDate(subcontractCommunicationDate);
}
}
public Date getLastRequiredDeliverDate() {
if (this.requiredDeliveringDates != null
&& !this.requiredDeliveringDates.isEmpty()) {
return this.requiredDeliveringDates.first()
.getSubcontractorDeliverDate();
if ( this.requiredDeliveringDates != null && !this.requiredDeliveringDates.isEmpty() ) {
return this.requiredDeliveringDates.first().getSubcontractorDeliverDate();
}
return null;
}
public void setEndDatesCommunicatedFromSubcontractor(
SortedSet<EndDateCommunication> endDatesCommunicatedFromSubcontractor) {
this.endDatesCommunicatedFromSubcontractor = endDatesCommunicatedFromSubcontractor;
}
@ -318,9 +309,10 @@ public class SubcontractedTaskData extends BaseEntity {
}
public EndDateCommunication getLastEndDatesCommunicatedFromSubcontractor() {
if (getEndDatesCommunicatedFromSubcontractor() != null) {
if ( getEndDatesCommunicatedFromSubcontractor() != null ) {
return getEndDatesCommunicatedFromSubcontractor().first();
}
return null;
}
}

View file

@ -26,10 +26,9 @@ import java.util.List;
import javax.validation.constraints.NotNull;
import org.libreplan.business.common.BaseEntity;
import org.libreplan.business.externalcompanies.entities.CommunicationType;
import org.libreplan.business.qualityforms.entities.QualityFormItem;
/**
* Entity {@link SubcontractorCommunication}.
* Entity {@link SubcontractorCommunication}.
*
* @author Susana Montes Pedreira <smontes@wirelessgalicia>
*/
@ -43,14 +42,18 @@ public class SubcontractorCommunication extends BaseEntity {
private Boolean reviewed = false;
private List<SubcontractorCommunicationValue> subcontractorCommunicationValues = new ArrayList<SubcontractorCommunicationValue>();
private List<SubcontractorCommunicationValue> subcontractorCommunicationValues = new ArrayList<>();
// Default constructor, needed by Hibernate
protected SubcontractorCommunication() {
}
private SubcontractorCommunication ( SubcontractedTaskData subcontractedTaskData, CommunicationType communicationType, Date communicationDate, Boolean reviewed){
private SubcontractorCommunication(SubcontractedTaskData subcontractedTaskData,
CommunicationType communicationType,
Date communicationDate,
Boolean reviewed){
this.setSubcontractedTaskData(subcontractedTaskData);
this.setCommunicationType(communicationType);
this.setCommunicationDate(communicationDate);
@ -61,8 +64,9 @@ public class SubcontractorCommunication extends BaseEntity {
SubcontractedTaskData subcontractedTaskData,
CommunicationType communicationType, Date communicationDate,
Boolean reviewed) {
return create(new SubcontractorCommunication(subcontractedTaskData,
communicationType, communicationDate, reviewed));
return create(
new SubcontractorCommunication(subcontractedTaskData, communicationType, communicationDate, reviewed));
}
public static SubcontractorCommunication create() {
@ -104,6 +108,7 @@ public class SubcontractorCommunication extends BaseEntity {
public void setSubcontractorCommunicationValues(
List<SubcontractorCommunicationValue> subcontractorCommunicationValues) {
this.subcontractorCommunicationValues = subcontractorCommunicationValues;
}
@ -112,14 +117,16 @@ public class SubcontractorCommunication extends BaseEntity {
}
public SubcontractorCommunicationValue getLastSubcontractorCommunicationValues(){
if (subcontractorCommunicationValues.isEmpty()){
if ( subcontractorCommunicationValues.isEmpty() ){
return null;
}
return subcontractorCommunicationValues.get(subcontractorCommunicationValues.size()-1);
}
public Date getLastSubcontractorCommunicationValueDate(){
SubcontractorCommunicationValue value = getLastSubcontractorCommunicationValues();
return (value == null) ? null : value.getDate();
}
}

View file

@ -25,8 +25,6 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
@ -54,47 +52,38 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class CriterionDAO extends IntegrationEntityDAO<Criterion>
implements ICriterionDAO {
public class CriterionDAO extends IntegrationEntityDAO<Criterion> implements ICriterionDAO {
private static final Log log = LogFactory.getLog(CriterionDAO.class);
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
public boolean thereIsOtherWithSameNameAndType(Criterion criterion) {
List<Criterion> withSameNameAndType = findByNameAndType(criterion);
if (withSameNameAndType.isEmpty()) {
return false;
}
if (withSameNameAndType.size() > 1) {
return true;
}
return areDifferentInDB(withSameNameAndType.get(0), criterion);
return !withSameNameAndType.isEmpty() && (withSameNameAndType.size() > 1 ||
areDifferentInDB(withSameNameAndType.get(0), criterion));
}
private boolean areDifferentInDB(Criterion existentCriterion,
Criterion other) {
private boolean areDifferentInDB(Criterion existentCriterion, Criterion other) {
return !existentCriterion.getId().equals(other.getId());
}
@Override
public List<Criterion> findByNameAndType(Criterion criterion) {
if (criterion.getType() == null) {
return new ArrayList<Criterion>();
if ( criterion.getType() == null ) {
return new ArrayList<>();
}
return findByNameAndType(criterion.getName(), criterion.getType()
.getName());
return findByNameAndType(criterion.getName(), criterion.getType().getName());
}
@Override
public List<Criterion> findByNameAndType(String name, String type) {
if ((name == null) || (type == null)) {
return new ArrayList<Criterion>();
if ( (name == null) || (type == null) ) {
return new ArrayList<>();
}
Criteria c = getSession().createCriteria(Criterion.class);
c.add(Restrictions.eq("name", name).ignoreCase())
.createCriteria("type").add(
Restrictions.eq("name", type).ignoreCase());
.createCriteria("type").add(Restrictions.eq("name", type).ignoreCase());
return (List<Criterion>) c.list();
}
@ -102,9 +91,8 @@ public class CriterionDAO extends IntegrationEntityDAO<Criterion>
public Criterion findUniqueByNameAndType(Criterion criterion) throws InstanceNotFoundException {
List<Criterion> list = findByNameAndType(criterion);
if (list.size() != 1) {
throw new InstanceNotFoundException(criterion, Criterion.class
.getName());
if ( list.size() != 1 ) {
throw new InstanceNotFoundException(criterion, Criterion.class.getName());
}
return list.get(0);
@ -120,27 +108,28 @@ public class CriterionDAO extends IntegrationEntityDAO<Criterion>
@Override
public boolean existsPredefinedCriterion(Criterion predefinedCriterion) {
Validate.notNull(predefinedCriterion
.getPredefinedCriterionInternalName());
return existsByNameAndType(predefinedCriterion)
|| existsByInternalCode(predefinedCriterion);
Validate.notNull(predefinedCriterion.getPredefinedCriterionInternalName());
return existsByNameAndType(predefinedCriterion) || existsByInternalCode(predefinedCriterion);
}
private boolean existsByInternalCode(Criterion criterion) {
Criteria c = getSession().createCriteria(Criterion.class);
c.add(Restrictions.eq("predefinedCriterionInternalName",
c.add(Restrictions.eq(
"predefinedCriterionInternalName",
criterion.getPredefinedCriterionInternalName()).ignoreCase());
return c.list().size() > 0;
}
@Override
public Criterion find(Criterion criterion) throws InstanceNotFoundException {
if (criterion.getId() != null) {
if ( criterion.getId() != null ) {
return super.find(criterion.getId());
}
Criterion result = findUniqueByNameAndType(criterion);
return result;
return findUniqueByNameAndType(criterion);
}
@Override
@ -156,12 +145,14 @@ public class CriterionDAO extends IntegrationEntityDAO<Criterion>
@Override
public List<Criterion> findByType(ICriterionType<?> type) {
List<Criterion> list = list(Criterion.class);
ArrayList<Criterion> result = new ArrayList<Criterion>();
ArrayList<Criterion> result = new ArrayList<>();
for (Criterion criterion : list) {
if (type.contains(criterion)) {
if ( type.contains(criterion) ) {
result.add(criterion);
}
}
return result;
}
@ -172,46 +163,49 @@ public class CriterionDAO extends IntegrationEntityDAO<Criterion>
public List<Criterion> getAllSorted() {
Criteria c = getSession().createCriteria(Criterion.class);
c.addOrder(Order.asc("name"));
return (List<Criterion>) c.list();
}
@Override
public List<Criterion> getAllSortedByTypeAndName() {
Query query = getSession()
.createQuery(
"select criterion from Criterion criterion "
+ "JOIN criterion.type type "
+ "order by type.name asc, criterion.name asc");
Query query = getSession().createQuery(
"select criterion from Criterion criterion " +
"JOIN criterion.type type " +
"order by type.name asc, criterion.name asc");
return (List<Criterion>) query.list();
}
@Override
public int numberOfRelatedRequirements(Criterion criterion) {
Criteria c = getSession().createCriteria(CriterionRequirement.class)
.add(Restrictions.eq("criterion", criterion)).setProjection(
Projections.rowCount());
return Integer.valueOf(c.uniqueResult().toString()).intValue();
Criteria c = getSession()
.createCriteria(CriterionRequirement.class)
.add(Restrictions.eq("criterion", criterion)).setProjection(Projections.rowCount());
return Integer.valueOf(c.uniqueResult().toString());
}
@Override
public int numberOfRelatedSatisfactions(Criterion criterion) {
Criteria c = getSession().createCriteria(CriterionSatisfaction.class)
.add(Restrictions.eq("criterion", criterion)).setProjection(
Projections.rowCount());
return Integer.valueOf(c.uniqueResult().toString()).intValue();
Criteria c = getSession()
.createCriteria(CriterionSatisfaction.class)
.add(Restrictions.eq("criterion", criterion)).setProjection(Projections.rowCount());
return Integer.valueOf(c.uniqueResult().toString());
}
@Override
public boolean hasCostCategoryAssignments(CostCategory costCategory) {
for (Criterion crit: getAll()) {
if (crit.getCostCategory() != null) {
if (crit.getCostCategory().getCode().equals(costCategory
.getCode())) {
if ( crit.getCostCategory() != null ) {
if ( crit.getCostCategory().getCode().equals(costCategory.getCode()) ) {
return true;
}
}
}
return false;
}

View file

@ -71,12 +71,12 @@ public class ResourcesSearcher implements IResourcesSearcher {
private SessionFactory sessionFactory;
public IResourcesQuery<Machine> searchMachines() {
return new Query<Machine>(Machine.class);
return new Query<>(Machine.class);
}
@Override
public IResourcesQuery<Worker> searchWorkers() {
return new Query<Worker>(Worker.class);
return new Query<>(Worker.class);
}
class Query<T extends Resource> implements IResourcesQuery<T> {
@ -96,14 +96,15 @@ public class ResourcesSearcher implements IResourcesSearcher {
@Override
public IResourcesQuery<T> byName(String name) {
this.name = name;
return this;
}
@Override
public IResourcesQuery<T> byCriteria(
Collection<? extends Criterion> criteria) {
public IResourcesQuery<T> byCriteria(Collection<? extends Criterion> criteria) {
Validate.noNullElements(criteria);
this.criteria = new ArrayList<Criterion>(criteria);
this.criteria = new ArrayList<>(criteria);
return this;
}
@ -115,18 +116,12 @@ public class ResourcesSearcher implements IResourcesSearcher {
@Override
public List<T> execute() {
return adHocTransactionService
.runOnReadOnlyTransaction(new IOnTransaction<List<T>>() {
@Override
@SuppressWarnings("unchecked")
public List<T> execute() {
Session session = sessionFactory
.getCurrentSession();
List<T> resources = buildCriteria(session).list();
return restrictToSatisfyAllCriteria(resources);
}
return adHocTransactionService.runOnReadOnlyTransaction(() -> {
Session session = sessionFactory.getCurrentSession();
List<T> resources = buildCriteria(session).list();
});
return restrictToSatisfyAllCriteria(resources);
});
}
private Criteria buildCriteria(Session session) {
@ -135,15 +130,16 @@ public class ResourcesSearcher implements IResourcesSearcher {
addQueryByName(result);
addFindRelatedWithSomeOfTheCriterions(result);
result.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return result;
}
private void addFindRelatedWithSomeOfTheCriterions(Criteria criteria) {
if (!criteriaSpecified()) {
if ( !criteriaSpecified() ) {
return;
}
criteria.createCriteria("criterionSatisfactions").add(
in("criterion", Criterion.withAllDescendants(this.criteria)));
criteria.createCriteria("criterionSatisfactions")
.add(in("criterion", Criterion.withAllDescendants(this.criteria)));
}
private boolean criteriaSpecified() {
@ -151,53 +147,57 @@ public class ResourcesSearcher implements IResourcesSearcher {
}
private void addQueryByName(Criteria criteria) {
if (name == null) {
if ( name == null ) {
return;
}
final String nameWithWildcards = "%" + name + "%";
if (klass.equals(Worker.class)) {
criteria.add(or(
or(ilike("firstName", nameWithWildcards),
ilike("surname", nameWithWildcards)),
if ( klass.equals(Worker.class) ) {
criteria.add(or(or(
ilike("firstName", nameWithWildcards), ilike("surname", nameWithWildcards)),
like("nif", nameWithWildcards)));
} else if (klass.equals(Machine.class)) {
criteria.add(or(ilike("name", nameWithWildcards),
ilike("code", nameWithWildcards)));
} else if ( klass.equals(Machine.class) ) {
criteria.add(or(ilike("name", nameWithWildcards), ilike("code", nameWithWildcards)));
} else {
LOG.warn("can't handle " + klass);
}
}
private List<T> restrictToSatisfyAllCriteria(List<T> resources) {
if (!criteriaSpecified()) {
if ( !criteriaSpecified() ) {
return resources;
}
List<T> result = new ArrayList<T>();
List<T> result = new ArrayList<>();
for (T each : resources) {
if (each.satisfiesCriterionsAtSomePoint(criteria)) {
if ( each.satisfiesCriterionsAtSomePoint(criteria) ) {
result.add(each);
}
}
return result;
}
@Override
public Map<CriterionType, Set<Criterion>> getCriteria() {
return adHocTransactionService
.runOnReadOnlyTransaction(getCriterionsTree(klass));
return adHocTransactionService.runOnReadOnlyTransaction(getCriterionsTree(klass));
}
}
@Override
public IResourcesQuery<?> searchBy(ResourceEnum resourceType) {
Validate.notNull(resourceType);
switch (resourceType) {
case MACHINE:
return searchMachines();
case WORKER:
return searchWorkers();
default:
throw new RuntimeException("can't handle " + resourceType);
case MACHINE:
return searchMachines();
case WORKER:
return searchWorkers();
default:
throw new RuntimeException("can't handle " + resourceType);
}
}
@ -211,14 +211,15 @@ public class ResourcesSearcher implements IResourcesSearcher {
public IResourcesQuery<Resource> byName(String name) {
searchWorkers.byName(name);
searchMachines.byName(name);
return this;
}
@Override
public IResourcesQuery<Resource> byCriteria(
Collection<? extends Criterion> criteria) {
public IResourcesQuery<Resource> byCriteria(Collection<? extends Criterion> criteria) {
searchWorkers.byCriteria(criteria);
searchMachines.byCriteria(criteria);
return this;
}
@ -226,23 +227,24 @@ public class ResourcesSearcher implements IResourcesSearcher {
public IResourcesQuery<Resource> byResourceType(ResourceType type) {
searchWorkers.byResourceType(type);
searchMachines.byResourceType(type);
return this;
}
@Override
public List<Resource> execute() {
List<Resource> result = new ArrayList<Resource>();
List<Resource> result = new ArrayList<>();
List<Worker> workers = searchWorkers.execute();
result.addAll(workers);
List<Machine> machines = searchMachines.execute();
result.addAll(machines);
return result;
}
@Override
public Map<CriterionType, Set<Criterion>> getCriteria() {
return adHocTransactionService
.runOnReadOnlyTransaction(getCriterionsTree(Resource.class));
return adHocTransactionService.runOnReadOnlyTransaction(getCriterionsTree(Resource.class));
}
};
}
@ -252,23 +254,21 @@ public class ResourcesSearcher implements IResourcesSearcher {
private IOnTransaction<Map<CriterionType, Set<Criterion>>> getCriterionsTree(
final Class<? extends Resource> klassTheCriterionTypeMustBeRelatedWith) {
return new IOnTransaction<Map<CriterionType, Set<Criterion>>>() {
@Override
public Map<CriterionType, Set<Criterion>> execute() {
Map<CriterionType, Set<Criterion>> result = new LinkedHashMap<CriterionType, Set<Criterion>>();
for (Criterion criterion : criterionDAO
.getAllSortedByTypeAndName()) {
CriterionType key = criterion.getType();
if (klassTheCriterionTypeMustBeRelatedWith
.isAssignableFrom(key.getResource().asClass())) {
if (!result.containsKey(key)) {
result.put(key, new LinkedHashSet<Criterion>());
}
result.get(key).add(criterion);
return () -> {
Map<CriterionType, Set<Criterion>> result = new LinkedHashMap<>();
for (Criterion criterion : criterionDAO.getAllSortedByTypeAndName()) {
CriterionType key = criterion.getType();
if ( klassTheCriterionTypeMustBeRelatedWith.isAssignableFrom(key.getResource().asClass()) ) {
if ( !result.containsKey(key) ) {
result.put(key, new LinkedHashSet<>());
}
result.get(key).add(criterion);
}
return result;
}
return result;
};
}

View file

@ -59,7 +59,7 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
* For each order tracked by this Scenario exists an OrderVersion that will
* have specific data for that order
*/
private Map<Order, OrderVersion> orders = new HashMap<Order, OrderVersion>();
private Map<Order, OrderVersion> orders = new HashMap<>();
private Scenario predecessor = null;
@ -90,7 +90,7 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
Iterator<OrderVersion> iterator = orders.values().iterator();
while (iterator.hasNext()) {
OrderVersion each = iterator.next();
if (Objects.equals(orderVersion, each)) {
if ( Objects.equals(orderVersion, each) ) {
iterator.remove();
}
}
@ -98,11 +98,12 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
public OrderVersion addOrder(Order order) {
addOrder(order, OrderVersion.createInitialVersion(this));
return orders.get(order);
}
public void addOrder(Order order, OrderVersion orderVersion) {
if (!orders.keySet().contains(order)) {
if ( !orders.keySet().contains(order) ) {
orders.put(order, orderVersion);
}
}
@ -133,29 +134,31 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
}
public List<Scenario> getPredecessors() {
List<Scenario> result = new ArrayList<Scenario>();
List<Scenario> result = new ArrayList<>();
Scenario current = getPredecessor();
while (current != null) {
result.add(current);
current = current.getPredecessor();
}
return result;
}
@AssertTrue(message = "name is already used")
public boolean isUniqueNameConstraint() {
if (StringUtils.isBlank(name)) {
if ( StringUtils.isBlank(name) ) {
return true;
}
IScenarioDAO scenarioDAO = Registry.getScenarioDAO();
if (isNewObject()) {
return !scenarioDAO.existsByNameAnotherTransaction(
name);
if ( isNewObject() ) {
return !scenarioDAO.existsByNameAnotherTransaction(name);
} else {
try {
Scenario scenario = scenarioDAO.findByName(name);
return scenario.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -176,20 +179,21 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
for (Order order : orders.keySet()) {
result.addOrder(order, orders.get(order));
}
return result;
}
public boolean isPredefined() {
if (name == null) {
if ( name == null ) {
return false;
}
for (PredefinedScenarios predefinedScenario : PredefinedScenarios
.values()) {
if (predefinedScenario.getName().equals(name)) {
for (PredefinedScenarios predefinedScenario : PredefinedScenarios.values()) {
if ( predefinedScenario.getName().equals(name) ) {
return true;
}
}
return false;
}
@ -212,12 +216,13 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
public boolean usesVersion(OrderVersion previousOrderVersion, Order order) {
Validate.notNull(order);
OrderVersion orderVersionForThisScenario = getOrderVersion(order);
if (previousOrderVersion == null) {
if ( previousOrderVersion == null ) {
return (orderVersionForThisScenario == null);
}
return orderVersionForThisScenario != null
&& orderVersionForThisScenario.getId().equals(
previousOrderVersion.getId());
return orderVersionForThisScenario != null &&
orderVersionForThisScenario.getId().equals(previousOrderVersion.getId());
}
public void removeOrderVersionForOrder(Order order) {
@ -228,51 +233,56 @@ public class Scenario extends BaseEntity implements IHumanIdentifiable {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((getId() == null || isNewObject()) ? super.hashCode()
: getId().hashCode());
result = prime * result +
((getId() == null || isNewObject()) ? super.hashCode() : getId().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
if ( this == obj ) {
return true;
}
if (obj == null || isNewObject()) {
if ( obj == null || isNewObject() ) {
return false;
}
if (!(obj instanceof Scenario)) {
if ( !(obj instanceof Scenario) ) {
return false;
}
Scenario other = (Scenario) obj;
if (getId() == null) {
if (other.getId() != null) {
if ( getId() == null ) {
if ( other.getId() != null ) {
return false;
}
} else if (!getId().equals(other.getId())) {
} else if ( !getId().equals(other.getId()) ) {
return false;
}
return true;
}
public List<Entry<Order, OrderVersion>> getOrderVersionsNeedingReassignation() {
List<Entry<Order, OrderVersion>> result = new ArrayList<Entry<Order, OrderVersion>>();
List<Entry<Order, OrderVersion>> result = new ArrayList<>();
for (Entry<Order, OrderVersion> each : orders.entrySet()) {
OrderVersion orderVersion = each.getValue();
if (needsReassignation(orderVersion)) {
if ( needsReassignation(orderVersion) ) {
result.add(each);
}
}
return result;
}
private boolean needsReassignation(OrderVersion orderVersion) {
boolean isOwnerScenario = this.equals(orderVersion.getOwnerScenario());
return !isOwnerScenario
&& orderVersion
.hasBeenModifiedAfter(lastNotOwnedReassignationsTimeStamp);
return !isOwnerScenario && orderVersion.hasBeenModifiedAfter(lastNotOwnedReassignationsTimeStamp);
}
@Override

View file

@ -55,7 +55,6 @@ import org.libreplan.business.orders.entities.Order;
import org.libreplan.business.orders.entities.OrderElement;
import org.libreplan.business.orders.entities.OrderLineGroup;
import org.libreplan.business.orders.entities.SchedulingState;
import org.libreplan.business.orders.entities.SchedulingState.ITypeChangedListener;
import org.libreplan.business.orders.entities.SchedulingState.Type;
import org.libreplan.business.qualityforms.entities.QualityForm;
import org.libreplan.business.requirements.entities.CriterionRequirement;
@ -63,17 +62,16 @@ import org.libreplan.business.requirements.entities.DirectCriterionRequirement;
import org.libreplan.business.requirements.entities.IndirectCriterionRequirement;
import org.libreplan.business.templates.daos.IOrderElementTemplateDAO;
import org.libreplan.business.trees.ITreeNode;
import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
/**
* @author Óscar González Fernández <ogonzalez@igalia.com>
*
*/
public abstract class OrderElementTemplate extends BaseEntity implements
ICriterionRequirable, ITreeNode<OrderElementTemplate> {
public abstract class OrderElementTemplate extends BaseEntity
implements ICriterionRequirable, ITreeNode<OrderElementTemplate> {
private static final Log LOG = LogFactory
.getLog(OrderElementTemplate.class);
private static final Log LOG = LogFactory.getLog(OrderElementTemplate.class);
private SchedulingState.Type schedulingStateType;
@ -85,40 +83,41 @@ public abstract class OrderElementTemplate extends BaseEntity implements
private OrderLineGroupTemplate parent;
private Set<CriterionRequirement> criterionRequirements = new HashSet<CriterionRequirement>();
private Set<CriterionRequirement> criterionRequirements = new HashSet<>();
private Set<MaterialAssignmentTemplate> materialAssignments = new HashSet<MaterialAssignmentTemplate>();
private Set<MaterialAssignmentTemplate> materialAssignments = new HashSet<>();
private Set<Label> labels = new HashSet<Label>();
private Set<Label> labels = new HashSet<>();
private Set<QualityForm> qualityForms = new HashSet<QualityForm>();
private Set<QualityForm> qualityForms = new HashSet<>();
private Set<AdvanceAssignmentTemplate> advanceAssignmentTemplates = new HashSet<AdvanceAssignmentTemplate>();
private Set<AdvanceAssignmentTemplate> advanceAssignmentTemplates = new HashSet<>();
private SchedulingState schedulingState;
private OrderElement origin;
public static <T extends OrderElementTemplate> T create(T beingBuilt,
OrderElement origin) {
public static <T extends OrderElementTemplate> T create(T beingBuilt, OrderElement origin) {
InfoComponent infoComponentCopied = origin.getInfoComponent().copy();
Order order = origin.getOrder();
Days fromBeginningToStart = daysBetween(order.getInitDate(), origin
.getInitDate());
Days fromBeginningToEnd = daysBetween(order.getInitDate(), origin
.getDeadline());
beingBuilt.setMaterialAssignments(copyMaterialAssignmentsFrom(beingBuilt, origin
.getMaterialAssignments()));
beingBuilt.setCriterionRequirements(copyDirectCriterionRequirements(
beingBuilt, origin.getDirectCriterionRequirement()));
Days fromBeginningToStart = daysBetween(order.getInitDate(), origin.getInitDate());
Days fromBeginningToEnd = daysBetween(order.getInitDate(), origin.getDeadline());
beingBuilt.setMaterialAssignments(copyMaterialAssignmentsFrom(beingBuilt, origin.getMaterialAssignments()));
beingBuilt.setCriterionRequirements(
copyDirectCriterionRequirements(beingBuilt, origin.getDirectCriterionRequirement()));
beingBuilt.addLabels(origin.getLabels());
beingBuilt.setQualityForms(origin.getQualityForms());
beingBuilt.setAdvanceAssignmentTemplates(copyDirectAdvanceAssignments(
beingBuilt, origin.getDirectAdvanceAssignments()));
beingBuilt.setAdvanceAssignmentTemplates(
copyDirectAdvanceAssignments(beingBuilt, origin.getDirectAdvanceAssignments()));
beingBuilt.setInfoComponent(infoComponentCopied);
beingBuilt.setSchedulingStateType(origin.getSchedulingStateType());
assignDates(beingBuilt, fromBeginningToStart, fromBeginningToEnd);
beingBuilt.setOrigin(origin);
return create(beingBuilt);
}
@ -130,47 +129,54 @@ public abstract class OrderElementTemplate extends BaseEntity implements
* @param criterionRequirements
* @return
*/
private static Set<CriterionRequirement> copyDirectCriterionRequirements(OrderElementTemplate beingBuilt,
Collection<DirectCriterionRequirement> criterionRequirements) {
Set<CriterionRequirement> result = new HashSet<CriterionRequirement>();
private static Set<CriterionRequirement> copyDirectCriterionRequirements(
OrderElementTemplate beingBuilt, Collection<DirectCriterionRequirement> criterionRequirements) {
Set<CriterionRequirement> result = new HashSet<>();
for (DirectCriterionRequirement each: criterionRequirements) {
final DirectCriterionRequirement directCriterionRequirement = (DirectCriterionRequirement) each;
DirectCriterionRequirement newDirectCriterionRequirement = DirectCriterionRequirement
.copyFrom(directCriterionRequirement, beingBuilt);
DirectCriterionRequirement newDirectCriterionRequirement =
DirectCriterionRequirement.copyFrom(each, beingBuilt);
result.add(newDirectCriterionRequirement);
}
return result;
}
private static Set<AdvanceAssignmentTemplate> copyDirectAdvanceAssignments(
OrderElementTemplate beingBuilt,
Set<DirectAdvanceAssignment> directAdvanceAssignments) {
Set<AdvanceAssignmentTemplate> result = new HashSet<AdvanceAssignmentTemplate>();
OrderElementTemplate beingBuilt, Set<DirectAdvanceAssignment> directAdvanceAssignments) {
Set<AdvanceAssignmentTemplate> result = new HashSet<>();
for (DirectAdvanceAssignment each : directAdvanceAssignments) {
result.add(AdvanceAssignmentTemplate.convert(beingBuilt, each));
}
return result;
}
public static <T extends OrderElementTemplate> T createNew(T beingBuilt) {
beingBuilt.setInfoComponent(new InfoComponent());
assignDates(beingBuilt, null, null);
return create(beingBuilt);
}
private static Set<MaterialAssignmentTemplate> copyMaterialAssignmentsFrom(OrderElementTemplate beingBuilt,
Collection<? extends MaterialAssignment> assignments) {
Set<MaterialAssignmentTemplate> result = new HashSet<MaterialAssignmentTemplate>();
private static Set<MaterialAssignmentTemplate> copyMaterialAssignmentsFrom(
OrderElementTemplate beingBuilt, Collection<? extends MaterialAssignment> assignments) {
Set<MaterialAssignmentTemplate> result = new HashSet<>();
for (MaterialAssignment each : assignments) {
result.add(MaterialAssignmentTemplate.copyFrom(each, beingBuilt));
}
return result;
}
private static void assignDates(OrderElementTemplate beingBuilt,
Days fromBeginningToStart, Days fromBeginningToEnd) {
private static void assignDates(
OrderElementTemplate beingBuilt, Days fromBeginningToStart, Days fromBeginningToEnd) {
Validate.isTrue(isNullOrPositive(fromBeginningToStart));
Validate.isTrue(isNullOrPositive(fromBeginningToEnd));
beingBuilt.startAsDaysFromBeginning = daysToInteger(fromBeginningToStart);
@ -178,9 +184,10 @@ public abstract class OrderElementTemplate extends BaseEntity implements
}
private static Days daysBetween(Date start, Date end) {
if (start == null || end == null) {
if ( start == null || end == null ) {
return null;
}
return Days.daysBetween(asDateTime(start), asDateTime(end));
}
@ -204,62 +211,62 @@ public abstract class OrderElementTemplate extends BaseEntity implements
setupLabels(orderElement);
setupQualityForms(orderElement);
setupAdvances(orderElement);
return orderElement;
}
protected <T extends OrderElement> T setupSchedulingStateType(T orderElement) {
orderElement.initializeType(schedulingStateType);
return orderElement;
}
protected <T extends OrderElement> T setupVersioningInfo(
OrderLineGroup parent, T orderElement) {
protected <T extends OrderElement> T setupVersioningInfo(OrderLineGroup parent, T orderElement) {
orderElement.useSchedulingDataFor(parent.getCurrentOrderVersion());
return orderElement;
}
private void setupInfoComponent(OrderElement orderElement) {
// orderElement.setCode(getCode());
orderElement.setName(getName());
orderElement.setDescription(getDescription());
}
private <T> void setupDates(OrderElement orderElement) {
private void setupDates(OrderElement orderElement) {
Date orderInitDate = orderElement.getOrder().getInitDate();
if (getStartAsDaysFromBeginning() != null) {
orderElement.setInitDate(plusDays(orderInitDate,
getStartAsDaysFromBeginning()));
if ( getStartAsDaysFromBeginning() != null ) {
orderElement.setInitDate(plusDays(orderInitDate, getStartAsDaysFromBeginning()));
}
if (getDeadlineAsDaysFromBeginning() != null) {
orderElement.setDeadline(plusDays(orderInitDate,
getDeadlineAsDaysFromBeginning()));
if ( getDeadlineAsDaysFromBeginning() != null ) {
orderElement.setDeadline(plusDays(orderInitDate, getDeadlineAsDaysFromBeginning()));
}
}
private Date plusDays(Date date, Integer days) {
LocalDate localDate = new LocalDate(date);
return localDate.plusDays(days).toDateTimeAtStartOfDay().toDate();
}
private void setupCriterionRequirements(OrderElement orderElement) {
for (DirectCriterionRequirement each : getDirectCriterionRequirements()) {
if (orderElement.canAddCriterionRequirement(each)) {
orderElement.addCriterionRequirement(DirectCriterionRequirement
.copyFrom(each, orderElement));
if ( orderElement.canAddCriterionRequirement(each) ) {
orderElement.addCriterionRequirement(DirectCriterionRequirement.copyFrom(each, orderElement));
}
}
}
private void setupMaterialAssignments(OrderElement orderElement) {
for (MaterialAssignmentTemplate each : materialAssignments) {
orderElement.addMaterialAssignment(each
.createAssignment(orderElement));
orderElement.addMaterialAssignment(each.createAssignment(orderElement));
}
}
private void setupLabels(OrderElement orderElement) {
for (Label each : getLabels()) {
if (orderElement.checkAncestorsNoOtherLabelRepeated(each)) {
if ( orderElement.checkAncestorsNoOtherLabelRepeated(each) ) {
orderElement.addLabel(each);
}
}
@ -274,8 +281,7 @@ public abstract class OrderElementTemplate extends BaseEntity implements
private void setupAdvances(OrderElement orderElement) {
for (AdvanceAssignmentTemplate each : advanceAssignmentTemplates) {
try {
orderElement.addAdvanceAssignment(each
.createAdvanceAssignment(orderElement));
orderElement.addAdvanceAssignment(each.createAdvanceAssignment(orderElement));
} catch (Exception e) {
String errorMessage = "error adding advance assignment to newly instantiated orderElement. Ignoring it";
LOG.warn(errorMessage, e);
@ -286,31 +292,31 @@ public abstract class OrderElementTemplate extends BaseEntity implements
public abstract OrderElement createElement(OrderLineGroup parent);
public SchedulingState getSchedulingState() {
if (schedulingState == null) {
if ( schedulingState == null ) {
schedulingState = SchedulingState.createSchedulingState(
getSchedulingStateType(),
getChildrenStates(), new ITypeChangedListener() {
@Override
public void typeChanged(Type newType) {
schedulingStateType = newType;
}
});
getChildrenStates(),
newType -> schedulingStateType = newType);
}
return schedulingState;
}
private List<SchedulingState> getChildrenStates() {
List<SchedulingState> result = new ArrayList<SchedulingState>();
List<SchedulingState> result = new ArrayList<>();
for (OrderElementTemplate each : getChildren()) {
result.add(each.getSchedulingState());
}
return result;
}
public SchedulingState.Type getSchedulingStateType() {
if (schedulingStateType == null) {
if ( schedulingStateType == null ) {
schedulingStateType = Type.NO_SCHEDULED;
}
return schedulingStateType;
}
@ -327,9 +333,10 @@ public abstract class OrderElementTemplate extends BaseEntity implements
}
protected InfoComponent getInfoComponent() {
if (infoComponent == null) {
if ( infoComponent == null ) {
infoComponent = new InfoComponent();
}
return infoComponent;
}
@ -396,18 +403,16 @@ public abstract class OrderElementTemplate extends BaseEntity implements
return Collections.unmodifiableSet(materialAssignments);
}
protected void setMaterialAssignments(Set<MaterialAssignmentTemplate> materialAssigments) {
this.materialAssignments = materialAssignments;
protected void setMaterialAssignments(Set<MaterialAssignmentTemplate> newMaterialAssigments) {
this.materialAssignments = newMaterialAssigments;
}
public void addMaterialAssignment(
MaterialAssignmentTemplate materialAssignment) {
public void addMaterialAssignment(MaterialAssignmentTemplate materialAssignment) {
Validate.notNull(materialAssignment);
materialAssignments.add(materialAssignment);
}
public void removeMaterialAssignment(
MaterialAssignmentTemplate materialAssignment) {
public void removeMaterialAssignment(MaterialAssignmentTemplate materialAssignment) {
materialAssignments.remove(materialAssignment);
}
@ -416,16 +421,18 @@ public abstract class OrderElementTemplate extends BaseEntity implements
for (MaterialAssignmentTemplate each : materialAssignments) {
result = result.add(each.getTotalPrice());
}
return result;
}
public BigDecimal getTotalMaterialAssigmentUnits() {
BigDecimal result = BigDecimal.ZERO;
for (MaterialAssignmentTemplate each : materialAssignments) {
if (each.getUnits() != null) {
if ( each.getUnits() != null ) {
result = result.add(each.getUnits());
}
}
return result;
}
@ -471,8 +478,7 @@ public abstract class OrderElementTemplate extends BaseEntity implements
return Collections.unmodifiableSet(advanceAssignmentTemplates);
}
protected void setAdvanceAssignmentTemplates(
Set<AdvanceAssignmentTemplate> advanceAssignmentTemplates) {
protected void setAdvanceAssignmentTemplates(Set<AdvanceAssignmentTemplate> advanceAssignmentTemplates) {
this.advanceAssignmentTemplates = advanceAssignmentTemplates;
}
@ -482,19 +488,17 @@ public abstract class OrderElementTemplate extends BaseEntity implements
@AssertTrue(message = "template name is already in use")
public boolean isUniqueRootTemplateNameConstraint() {
if (getParent() != null) {
if ( getParent() != null ) {
return true;
}
IOrderElementTemplateDAO orderElementTemplateDAO = Registry
.getOrderElementTemplateDAO();
if (isNewObject()) {
return !orderElementTemplateDAO
.existsRootByNameAnotherTransaction(this);
IOrderElementTemplateDAO orderElementTemplateDAO = Registry.getOrderElementTemplateDAO();
if ( isNewObject() ) {
return !orderElementTemplateDAO.existsRootByNameAnotherTransaction(this);
} else {
try {
OrderElementTemplate template = orderElementTemplateDAO
.findUniqueRootByName(getName());
OrderElementTemplate template = orderElementTemplateDAO.findUniqueRootByName(getName());
return template.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -509,11 +513,13 @@ public abstract class OrderElementTemplate extends BaseEntity implements
public List<OrderElementTemplate> getAllChildren() {
List<OrderElementTemplate> children = getChildrenTemplates();
List<OrderElementTemplate> result = new ArrayList<OrderElementTemplate>();
List<OrderElementTemplate> result = new ArrayList<>();
for (OrderElementTemplate orderElement : children) {
result.add(orderElement);
result.addAll(orderElement.getAllChildren());
}
return result;
}
@ -536,17 +542,15 @@ public abstract class OrderElementTemplate extends BaseEntity implements
*/
protected CriterionRequirementTemplateHandler criterionRequirementHandler =
CriterionRequirementTemplateHandler.getInstance();
CriterionRequirementTemplateHandler.getInstance();
public void setValidCriterionRequirement(IndirectCriterionRequirement requirement, boolean valid){
requirement.setValid(valid);
criterionRequirementHandler.propagateValidCriterionRequirement(this,
requirement.getParent(), valid);
criterionRequirementHandler.propagateValidCriterionRequirement(this, requirement.getParent(), valid);
}
public void removeDirectCriterionRequirement(DirectCriterionRequirement criterionRequirement){
criterionRequirementHandler.propagateRemoveCriterionRequirement(this,
criterionRequirement);
criterionRequirementHandler.propagateRemoveCriterionRequirement(this, criterionRequirement);
removeCriterionRequirement(criterionRequirement);
}
@ -554,32 +558,25 @@ public abstract class OrderElementTemplate extends BaseEntity implements
@Override
public void removeCriterionRequirement(CriterionRequirement requirement) {
criterionRequirements.remove(requirement);
if (requirement instanceof IndirectCriterionRequirement) {
((IndirectCriterionRequirement)requirement).getParent().
getChildren().remove((IndirectCriterionRequirement)requirement);
if ( requirement instanceof IndirectCriterionRequirement ) {
((IndirectCriterionRequirement)requirement).getParent().getChildren().remove(requirement);
}
}
@Override
public void addCriterionRequirement(
CriterionRequirement criterionRequirement) {
criterionRequirementHandler.addCriterionRequirement(this,
criterionRequirement);
public void addCriterionRequirement(CriterionRequirement criterionRequirement) {
criterionRequirementHandler.addCriterionRequirement(this, criterionRequirement);
}
public void addDirectCriterionRequirement(
CriterionRequirement criterionRequirement) {
public void addDirectCriterionRequirement(CriterionRequirement criterionRequirement) {
criterionRequirementHandler.addDirectCriterionRequirement(this, criterionRequirement);
}
public void addIndirectCriterionRequirement(
IndirectCriterionRequirement criterionRequirement) {
criterionRequirementHandler.addIndirectCriterionRequirement(this,
criterionRequirement);
public void addIndirectCriterionRequirement(IndirectCriterionRequirement criterionRequirement) {
criterionRequirementHandler.addIndirectCriterionRequirement(this, criterionRequirement);
}
protected void basicAddCriterionRequirement(
CriterionRequirement criterionRequirement) {
protected void basicAddCriterionRequirement(CriterionRequirement criterionRequirement) {
criterionRequirement.setOrderElementTemplate(this);
this.criterionRequirements.add(criterionRequirement);
}
@ -589,10 +586,8 @@ public abstract class OrderElementTemplate extends BaseEntity implements
criterionRequirementHandler.propagateUpdateCriterionRequirements(this);
}
public boolean canAddCriterionRequirement(
DirectCriterionRequirement newRequirement) {
return criterionRequirementHandler.canAddCriterionRequirement(this,
newRequirement);
public boolean canAddCriterionRequirement(DirectCriterionRequirement newRequirement) {
return criterionRequirementHandler.canAddCriterionRequirement(this, newRequirement);
}
protected Set<IndirectCriterionRequirement> getIndirectCriterionRequirement() {
@ -600,8 +595,7 @@ public abstract class OrderElementTemplate extends BaseEntity implements
}
public Set<DirectCriterionRequirement> getDirectCriterionRequirements() {
return criterionRequirementHandler
.getDirectCriterionRequirement(criterionRequirements);
return criterionRequirementHandler.getDirectCriterionRequirement(criterionRequirements);
}
public Order getOrder() {

View file

@ -45,46 +45,41 @@ import org.springframework.transaction.annotation.Transactional;
* @author Fernando Bellas Permuy <fbellas@udc.es>
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
* @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Vova Perebykivskiy <vova@libreplan-enterprise.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/
@Repository
public class UserDAO extends GenericDAOHibernate<User, Long>
implements IUserDAO {
public class UserDAO extends GenericDAOHibernate<User, Long> implements IUserDAO {
@Autowired
private IOrderAuthorizationDAO orderAuthorizationDAO;
@Override
@Transactional(readOnly = true)
public User findByLoginName(String loginName)
throws InstanceNotFoundException {
public User findByLoginName(String loginName) throws InstanceNotFoundException {
Criteria c = getSession().createCriteria(User.class);
c.add(Restrictions.eq("loginName", loginName).ignoreCase());
User user = (User) c.uniqueResult();
User user = (User) getSession()
.createCriteria(User.class)
.add(Restrictions.eq("loginName", loginName).ignoreCase())
.uniqueResult();
if (user == null) {
throw new InstanceNotFoundException(loginName,
User.class.getName());
if ( user == null ) {
throw new InstanceNotFoundException(loginName, User.class.getName());
} else {
user.getProfiles().size();
return user;
}
}
@Override
public User findByLoginNameNotDisabled(String loginName)
throws InstanceNotFoundException {
public User findByLoginNameNotDisabled(String loginName) throws InstanceNotFoundException {
Criteria c = getSession().createCriteria(User.class);
c.add(Restrictions.eq("loginName", loginName).ignoreCase());
c.add(Restrictions.eq("disabled", false));
User user = (User) c.uniqueResult();
if (user == null) {
throw new InstanceNotFoundException(loginName,
User.class.getName());
if ( user == null ) {
throw new InstanceNotFoundException(loginName, User.class.getName());
} else {
return user;
}
@ -104,6 +99,7 @@ public class UserDAO extends GenericDAOHibernate<User, Long>
public boolean existsByLoginName(String loginName) {
try {
findByLoginName(loginName);
return true;
} catch (InstanceNotFoundException e) {
return false;
@ -120,6 +116,7 @@ public class UserDAO extends GenericDAOHibernate<User, Long>
public List<User> listNotDisabled() {
Criteria c = getSession().createCriteria(User.class);
c.add(Restrictions.eq("disabled", false));
return c.list();
}
@ -127,6 +124,7 @@ public class UserDAO extends GenericDAOHibernate<User, Long>
public List<User> findByLastConnectedScenario(Scenario scenario) {
Criteria c = getSession().createCriteria(User.class);
c.add(Restrictions.eq("lastConnectedScenario", scenario));
return c.list();
}
@ -134,16 +132,20 @@ public class UserDAO extends GenericDAOHibernate<User, Long>
List orderAuthorizations = getSession()
.createCriteria(UserOrderAuthorization.class)
.add(Restrictions.eq("user", user)).list();
return orderAuthorizations;
}
@Override
public List<User> getUnboundUsers(Worker worker) {
List<User> result = new ArrayList<User>();
List<User> result = new ArrayList<>();
boolean condition;
for (User user : getUsersOrderByLoginame()) {
if ((user.getWorker() == null)
|| (worker != null && !worker.isNewObject() && worker
.getId().equals(user.getWorker().getId()))) {
condition = (user.getWorker() == null) ||
(worker != null && !worker.isNewObject() && worker.getId().equals(user.getWorker().getId()));
if ( condition ) {
result.add(user);
}
}
@ -151,8 +153,7 @@ public class UserDAO extends GenericDAOHibernate<User, Long>
}
private List<User> getUsersOrderByLoginame() {
return getSession().createCriteria(User.class).addOrder(
org.hibernate.criterion.Order.asc("loginName")).list();
return getSession().createCriteria(User.class).addOrder(org.hibernate.criterion.Order.asc("loginName")).list();
}
@Override
@ -168,7 +169,7 @@ public class UserDAO extends GenericDAOHibernate<User, Long>
@Override
public void remove(User user) throws InstanceNotFoundException {
List<OrderAuthorization> orderAuthorizations = getOrderAuthorizationsByUser(user);
if (!orderAuthorizations.isEmpty()) {
if ( !orderAuthorizations.isEmpty() ) {
for (OrderAuthorization orderAuthorization : orderAuthorizations) {
orderAuthorizationDAO.remove(orderAuthorization.getId());
}

View file

@ -31,7 +31,6 @@ import javax.validation.constraints.AssertTrue;
import org.hibernate.validator.constraints.NotEmpty;
import org.libreplan.business.common.BaseEntity;
import org.libreplan.business.common.IHumanIdentifiable;
import org.libreplan.business.common.IOnTransaction;
import org.libreplan.business.common.Registry;
import org.libreplan.business.common.entities.Configuration;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
@ -61,9 +60,9 @@ public class User extends BaseEntity implements IHumanIdentifiable{
private Language applicationLanguage = Language.BROWSER_LANGUAGE;
private Set<UserRole> roles = new HashSet<UserRole>();
private Set<UserRole> roles = new HashSet<>();
private Set<Profile> profiles = new HashSet<Profile>();
private Set<Profile> profiles = new HashSet<>();
private String email;
@ -104,8 +103,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{
public User() {
}
private User(String loginName, String password, Set<UserRole> roles,
Set<Profile> profiles) {
private User(String loginName, String password, Set<UserRole> roles, Set<Profile> profiles) {
this.loginName = loginName;
this.password = password;
this.roles = roles;
@ -118,13 +116,11 @@ public class User extends BaseEntity implements IHumanIdentifiable{
this.email = email;
}
public static User create(String loginName, String password,
Set<UserRole> roles) {
return create(loginName, password, roles, new HashSet<Profile>());
public static User create(String loginName, String password, Set<UserRole> roles) {
return create(loginName, password, roles, new HashSet<>());
}
public static User create(String loginName, String password,
Set<UserRole> roles, Set<Profile> profiles) {
public static User create(String loginName, String password, Set<UserRole> roles, Set<Profile> profiles) {
return create(new User(loginName, password, roles, profiles));
}
@ -180,10 +176,11 @@ public class User extends BaseEntity implements IHumanIdentifiable{
* @return A list of UserRole objects
*/
public Set<UserRole> getAllRoles() {
Set<UserRole> allRoles = new HashSet<UserRole>(roles);
Set<UserRole> allRoles = new HashSet<>(roles);
for (Profile profile : getProfiles()) {
allRoles.addAll(profile.getRoles());
}
return allRoles;
}
@ -191,14 +188,16 @@ public class User extends BaseEntity implements IHumanIdentifiable{
* Checks if current user is in the requested role
*/
public boolean isInRole(UserRole role) {
if (roles.contains(role)) {
if ( roles.contains(role) ) {
return true;
}
for (Profile profile : profiles) {
if (profile.getRoles().contains(role)) {
if ( profile.getRoles().contains(role) ) {
return true;
}
}
return false;
}
@ -215,17 +214,18 @@ public class User extends BaseEntity implements IHumanIdentifiable{
}
public void addProfile(Profile profile) {
if (!containsProfile(profile)) {
if ( !containsProfile(profile) ) {
profiles.add(profile);
}
}
private boolean containsProfile(Profile profile) {
for (Profile assignedProfile : profiles) {
if (assignedProfile.getId().equals(profile.getId())) {
if ( assignedProfile.getId().equals(profile.getId()) ) {
return true;
}
}
return false;
}
@ -250,11 +250,12 @@ public class User extends BaseEntity implements IHumanIdentifiable{
IUserDAO userDAO = Registry.getUserDAO();
if (isNewObject()) {
if ( isNewObject() ) {
return !userDAO.existsByLoginNameAnotherTransaction(loginName);
} else {
try {
User u = userDAO.findByLoginNameAnotherTransaction(loginName);
return u.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -292,8 +293,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{
return expandCompanyPlanningViewCharts;
}
public void setExpandOrderPlanningViewCharts(
boolean expandOrderPlanningViewCharts) {
public void setExpandOrderPlanningViewCharts(boolean expandOrderPlanningViewCharts) {
this.expandOrderPlanningViewCharts = expandOrderPlanningViewCharts;
}
@ -301,8 +301,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{
return expandOrderPlanningViewCharts;
}
public void setExpandResourceLoadViewCharts(
boolean expandResourceLoadViewCharts) {
public void setExpandResourceLoadViewCharts(boolean expandResourceLoadViewCharts) {
this.expandResourceLoadViewCharts = expandResourceLoadViewCharts;
}
@ -310,8 +309,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{
return expandResourceLoadViewCharts;
}
public void setExpandCompanyPlanningViewCharts(
boolean expandCompanyPlanningViewCharts) {
public void setExpandCompanyPlanningViewCharts(boolean expandCompanyPlanningViewCharts) {
this.expandCompanyPlanningViewCharts = expandCompanyPlanningViewCharts;
}
@ -342,7 +340,7 @@ public class User extends BaseEntity implements IHumanIdentifiable{
public void setWorker(Worker worker) {
this.worker = worker;
if (worker == null) {
if ( worker == null ) {
roles.remove(UserRole.ROLE_BOUND_USER);
} else {
roles.add(UserRole.ROLE_BOUND_USER);
@ -359,11 +357,12 @@ public class User extends BaseEntity implements IHumanIdentifiable{
public enum UserAuthenticationType {
DATABASE(_("Database")), LDAP(_("LDAP"));
DATABASE(_("Database")),
LDAP(_("LDAP"));
private String name;
private UserAuthenticationType(String name) {
UserAuthenticationType(String name) {
this.name = name;
}
@ -373,36 +372,32 @@ public class User extends BaseEntity implements IHumanIdentifiable{
}
public UserAuthenticationType getUserType() {
return isLibrePlanUser() ? UserAuthenticationType.DATABASE
: UserAuthenticationType.LDAP;
return isLibrePlanUser() ? UserAuthenticationType.DATABASE : UserAuthenticationType.LDAP;
}
@AssertTrue(message = "You have exceeded the maximum limit of users")
public boolean isMaxUsersConstraint() {
return Registry.getTransactionService()
.runOnAnotherReadOnlyTransaction(new IOnTransaction<Boolean>() {
@Override
public Boolean execute() {
Configuration configuration = Registry
.getConfigurationDAO().getConfiguration();
if (configuration == null) {
return true;
}
return Registry.getTransactionService().runOnAnotherReadOnlyTransaction(() -> {
Configuration configuration = Registry.getConfigurationDAO().getConfiguration();
if ( configuration == null ) {
return true;
}
Integer maxUsers = configuration.getMaxUsers();
if (maxUsers != null && maxUsers > 0) {
List<User> users = Registry.getUserDAO().findAll();
int usersNumber = users.size();
if (isNewObject()) {
usersNumber++;
}
if (usersNumber > maxUsers) {
return false;
}
}
return true;
}
});
Integer maxUsers = configuration.getMaxUsers();
if ( maxUsers != null && maxUsers > 0 ) {
List<User> users = Registry.getUserDAO().findAll();
int usersNumber = users.size();
if ( isNewObject() ) {
usersNumber++;
}
if ( usersNumber > maxUsers ) {
return false;
}
}
return true;
});
}
public Label getProjectsFilterLabel() {

View file

@ -38,7 +38,8 @@ import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.labels.entities.LabelType;
import org.libreplan.business.workreports.daos.IWorkReportTypeDAO;
import org.libreplan.business.workreports.valueobjects.DescriptionField;
import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
/**
* @author Diego Pino García <dpino@igalia.com>
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
@ -62,20 +63,18 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
private Boolean orderElementIsSharedInLines = false;
private HoursManagementEnum hoursManagement = HoursManagementEnum
.getDefault();
private HoursManagementEnum hoursManagement = HoursManagementEnum.getDefault();
private Set<WorkReportLabelTypeAssigment> workReportLabelTypeAssigments = new HashSet<WorkReportLabelTypeAssigment>();
private Set<WorkReportLabelTypeAssigment> workReportLabelTypeAssigments = new HashSet<>();
private Set<DescriptionField> headingFields = new HashSet<DescriptionField>();
private Set<DescriptionField> headingFields = new HashSet<>();
private Set<DescriptionField> lineFields = new HashSet<DescriptionField>();
private Set<DescriptionField> lineFields = new HashSet<>();
/**
* Constructor for hibernate. Do not use!
*/
public WorkReportType() {
}
private WorkReportType(String name) {
@ -100,8 +99,7 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
}
public Boolean getResourceIsSharedInLines() {
return resourceIsSharedInLines == null ? false
: resourceIsSharedInLines;
return resourceIsSharedInLines == null ? false : resourceIsSharedInLines;
}
public void setResourceIsSharedInLines(Boolean resourceIsSharedInLines) {
@ -109,12 +107,10 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
}
public Boolean getOrderElementIsSharedInLines() {
return orderElementIsSharedInLines == null ? false
: orderElementIsSharedInLines;
return orderElementIsSharedInLines == null ? false : orderElementIsSharedInLines;
}
public void setOrderElementIsSharedInLines(
Boolean orderElementIsSharedInLines) {
public void setOrderElementIsSharedInLines(Boolean orderElementIsSharedInLines) {
this.orderElementIsSharedInLines = orderElementIsSharedInLines;
}
@ -131,8 +127,7 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
return workReportLabelTypeAssigments;
}
public void setWorkReportLabelTypeAssigments(
Set<WorkReportLabelTypeAssigment> workReportLabelTypeAssigments) {
public void setWorkReportLabelTypeAssigments(Set<WorkReportLabelTypeAssigment> workReportLabelTypeAssigments) {
this.workReportLabelTypeAssigments = workReportLabelTypeAssigments;
}
@ -157,21 +152,19 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
@SuppressWarnings("unused")
@AssertTrue(message = "Value is not valid.\n Code cannot contain chars like '_'.")
public boolean isWorkReportTypeCodeWithoutIncorrectCharacterConstraint() {
if ((getCode() == null) || (getCode().contains("_"))) {
return false;
}
return true;
return !((getCode() == null) || (getCode().contains("_")));
}
@SuppressWarnings("unused")
@AssertTrue(message = "timesheet template name is already being used")
public boolean isUniqueWorkReportTypeNameConstraint() {
IWorkReportTypeDAO workReportTypeDAO = Registry.getWorkReportTypeDAO();
if (isNewObject()) {
if ( isNewObject() ) {
return !workReportTypeDAO.existsByNameAnotherTransaction(this);
} else {
try {
WorkReportType c = workReportTypeDAO.findUniqueByName(name);
return c.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
@ -187,10 +180,11 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
@AssertTrue(message = "The field name must be unique.")
public boolean isUniqueNamesDescriptionFieldsConstraint() {
for (DescriptionField descriptionField : getDescriptionFields()) {
if (existSameFieldName(descriptionField)) {
if ( existSameFieldName(descriptionField) ) {
return false;
}
}
return true;
}
@ -198,221 +192,191 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
@AssertTrue(message = "Assigned Label Type cannot be repeated in a Timesheet Template.")
public boolean isNotExistRepeatedLabelTypesConstraint() {
for (WorkReportLabelTypeAssigment assignedLabelType : this.workReportLabelTypeAssigments) {
if (existRepeatedLabelType(assignedLabelType)) {
if ( existRepeatedLabelType(assignedLabelType) ) {
return false;
}
}
return true;
}
public boolean existRepeatedLabelType(
WorkReportLabelTypeAssigment assignedLabelType) {
public boolean existRepeatedLabelType(WorkReportLabelTypeAssigment assignedLabelType) {
boolean condition;
for (WorkReportLabelTypeAssigment oldAssignedLabelType : this.workReportLabelTypeAssigments) {
if ((!oldAssignedLabelType.equals(assignedLabelType))
&& (isTheSameLabelType(oldAssignedLabelType.getLabelType(),
assignedLabelType.getLabelType()))) {
condition = (!oldAssignedLabelType.equals(assignedLabelType) ) &&
(isTheSameLabelType(oldAssignedLabelType.getLabelType(), assignedLabelType.getLabelType()));
if ( condition ) {
return true;
}
}
return false;
}
public boolean isTheSameLabelType(LabelType oldLabelType,
LabelType newLabelType) {
if ((oldLabelType != null) && (newLabelType != null)
&& (oldLabelType.equals(newLabelType))) {
return true;
}
return false;
public boolean isTheSameLabelType(LabelType oldLabelType, LabelType newLabelType) {
return (oldLabelType != null) && (newLabelType != null) && (oldLabelType.equals(newLabelType));
}
public boolean existSameFieldName(DescriptionField descriptionField) {
boolean condition;
for (DescriptionField oldDescriptionField : getDescriptionFields()) {
if ((!oldDescriptionField.equals(descriptionField))
&& (isTheSameFieldName(oldDescriptionField.getFieldName(),
descriptionField.getFieldName()))) {
condition = (!oldDescriptionField.equals(descriptionField)) &&
(isTheSameFieldName(oldDescriptionField.getFieldName(), descriptionField.getFieldName()));
if ( condition ) {
return true;
}
}
return false;
}
private boolean isTheSameFieldName(String oldName, String newName) {
if ((oldName != null) && (newName != null) && (!oldName.isEmpty())
&& (!newName.isEmpty()) && (oldName.equals(newName))) {
return true;
}
return false;
return (oldName != null) &&
(newName != null) &&
(!oldName.isEmpty()) &&
(!newName.isEmpty()) &&
(oldName.equals(newName));
}
public Set<DescriptionField> getDescriptionFields() {
Set<DescriptionField> descriptionFields = new HashSet<DescriptionField>();
Set<DescriptionField> descriptionFields = new HashSet<>();
descriptionFields.addAll(this.getHeadingFields());
descriptionFields.addAll(this.getLineFields());
return descriptionFields;
}
/* Operation to manage the index */
public void addDescriptionFieldToEndLine(DescriptionField descriptionField) {
addDescriptionFieldToLine(descriptionField, getLineFieldsAndLabels()
.size());
addDescriptionFieldToLine(descriptionField, getLineFieldsAndLabels().size());
}
public void addDescriptionFieldToEndHead(DescriptionField descriptionField) {
addDescriptionFieldToHead(descriptionField, getHeadingFieldsAndLabels()
.size());
addDescriptionFieldToHead(descriptionField, getHeadingFieldsAndLabels().size());
}
public void addLabelAssigmentToEndHead(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
addLabelAssigmentToHead(workReportLabelTypeAssigment,
getHeadingFieldsAndLabels().size());
public void addLabelAssigmentToEndHead(WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
addLabelAssigmentToHead(workReportLabelTypeAssigment, getHeadingFieldsAndLabels().size());
}
public void addLabelAssigmentToEndLine(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
addLabelAssigmentToLine(workReportLabelTypeAssigment,
getLineFieldsAndLabels().size());
public void addLabelAssigmentToEndLine(WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
addLabelAssigmentToLine(workReportLabelTypeAssigment, getLineFieldsAndLabels().size());
}
public void addDescriptionFieldToLine(DescriptionField descriptionField,
int position) {
if (isValidIndexToAdd(position, getLineFieldsAndLabels())) {
public void addDescriptionFieldToLine(DescriptionField descriptionField, int position) {
if ( isValidIndexToAdd(position, getLineFieldsAndLabels()) ) {
updateIndexFromPosition(getLineFieldsAndLabels(), position, 1);
descriptionField.setPositionNumber(position);
getLineFields().add(descriptionField);
}
}
public void addDescriptionFieldToHead(DescriptionField descriptionField,
int position) {
if (isValidIndexToAdd(position, getHeadingFieldsAndLabels())) {
public void addDescriptionFieldToHead(DescriptionField descriptionField, int position) {
if ( isValidIndexToAdd(position, getHeadingFieldsAndLabels()) ) {
updateIndexFromPosition(getHeadingFieldsAndLabels(), position, 1);
descriptionField.setPositionNumber(position);
getHeadingFields().add(descriptionField);
}
}
public void addLabelAssigmentToHead(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment,
int position) {
if (isValidIndexToAdd(position, getHeadingFieldsAndLabels())) {
public void addLabelAssigmentToHead(WorkReportLabelTypeAssigment workReportLabelTypeAssigment, int position) {
if ( isValidIndexToAdd(position, getHeadingFieldsAndLabels()) ) {
updateIndexFromPosition(getHeadingFieldsAndLabels(), position, 1);
workReportLabelTypeAssigment.setLabelsSharedByLines(true);
workReportLabelTypeAssigment.setPositionNumber(position);
getWorkReportLabelTypeAssigments()
.add(workReportLabelTypeAssigment);
getWorkReportLabelTypeAssigments().add(workReportLabelTypeAssigment);
}
}
public void addLabelAssigmentToLine(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment,
int position) {
if (isValidIndexToAdd(position, getLineFieldsAndLabels())) {
public void addLabelAssigmentToLine(WorkReportLabelTypeAssigment workReportLabelTypeAssigment, int position) {
if ( isValidIndexToAdd(position, getLineFieldsAndLabels()) ) {
updateIndexFromPosition(getLineFieldsAndLabels(), position, 1);
workReportLabelTypeAssigment.setLabelsSharedByLines(false);
workReportLabelTypeAssigment.setPositionNumber(
position);
getWorkReportLabelTypeAssigments()
.add(workReportLabelTypeAssigment);
workReportLabelTypeAssigment.setPositionNumber(position);
getWorkReportLabelTypeAssigments().add(workReportLabelTypeAssigment);
}
}
public void moveLabelToEndHead(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
moveLabelToHead(workReportLabelTypeAssigment,
getHeadingFieldsAndLabels().size() - 1);
public void moveLabelToEndHead(WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
moveLabelToHead(workReportLabelTypeAssigment, getHeadingFieldsAndLabels().size() - 1);
}
public void moveLabelToEndLine(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
moveLabelToLine(workReportLabelTypeAssigment, getLineFieldsAndLabels()
.size() - 1);
public void moveLabelToEndLine(WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
moveLabelToLine(workReportLabelTypeAssigment, getLineFieldsAndLabels().size() - 1);
}
public void moveDescriptionFieldToEndHead(DescriptionField descriptionField) {
moveDescriptionFieldToHead(descriptionField,
getHeadingFieldsAndLabels().size() - 1);
moveDescriptionFieldToHead(descriptionField, getHeadingFieldsAndLabels().size() - 1);
}
public void moveDescriptionFieldToEndLine(DescriptionField descriptionField) {
moveDescriptionFieldToLine(descriptionField, getLineFieldsAndLabels()
.size() - 1);
moveDescriptionFieldToLine(descriptionField, getLineFieldsAndLabels().size() - 1);
}
public void moveLabelToHead(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment,
int position) {
if (isValidIndexToMove(position, getHeadingFieldsAndLabels())) {
public void moveLabelToHead(WorkReportLabelTypeAssigment workReportLabelTypeAssigment, int position) {
if ( isValidIndexToMove(position, getHeadingFieldsAndLabels()) ) {
removeLabel(workReportLabelTypeAssigment);
addLabelAssigmentToHead(workReportLabelTypeAssigment, position);
}
}
public void moveLabelToLine(
WorkReportLabelTypeAssigment workReportLabelTypeAssigment,
int position) {
if (isValidIndexToMove(position, getLineFieldsAndLabels())) {
public void moveLabelToLine(WorkReportLabelTypeAssigment workReportLabelTypeAssigment, int position) {
if ( isValidIndexToMove(position, getLineFieldsAndLabels()) ) {
removeLabel(workReportLabelTypeAssigment);
addLabelAssigmentToLine(workReportLabelTypeAssigment, position);
}
}
public void moveDescriptionFieldToHead(DescriptionField descriptionField,
int position) {
if (isValidIndexToMove(position, getHeadingFieldsAndLabels())) {
public void moveDescriptionFieldToHead(DescriptionField descriptionField, int position) {
if ( isValidIndexToMove(position, getHeadingFieldsAndLabels()) ) {
removeDescriptionField(descriptionField);
addDescriptionFieldToHead(descriptionField, position);
}
}
public void moveDescriptionFieldToLine(DescriptionField descriptionField,
int position) {
if (isValidIndexToMove(position, getLineFieldsAndLabels())) {
public void moveDescriptionFieldToLine(DescriptionField descriptionField, int position) {
if ( isValidIndexToMove(position, getLineFieldsAndLabels()) ) {
removeDescriptionField(descriptionField);
addDescriptionFieldToLine(descriptionField, position);
}
}
public void removeDescriptionField(DescriptionField descriptionField){
if (getHeadingFields().contains(descriptionField)) {
if ( getHeadingFields().contains(descriptionField) ) {
getHeadingFields().remove(descriptionField);
updateIndexFromPosition(getHeadingFieldsAndLabels(),
descriptionField.getPositionNumber(), -1);
updateIndexFromPosition(getHeadingFieldsAndLabels(), descriptionField.getPositionNumber(), -1);
} else {
getLineFields().remove(descriptionField);
updateIndexFromPosition(getLineFieldsAndLabels(), descriptionField
.getPositionNumber(), -1);
updateIndexFromPosition(getLineFieldsAndLabels(), descriptionField.getPositionNumber(), -1);
}
}
public void removeLabel(WorkReportLabelTypeAssigment workReportLabelTypeAssigment) {
getWorkReportLabelTypeAssigments().remove(workReportLabelTypeAssigment);
if (workReportLabelTypeAssigment.getLabelsSharedByLines()) {
updateIndexFromPosition(getHeadingFieldsAndLabels(),
workReportLabelTypeAssigment.getPositionNumber(), -1);
if ( workReportLabelTypeAssigment.getLabelsSharedByLines() ) {
updateIndexFromPosition(getHeadingFieldsAndLabels(), workReportLabelTypeAssigment.getPositionNumber(), -1);
} else {
updateIndexFromPosition(getLineFieldsAndLabels(),
workReportLabelTypeAssigment.getPositionNumber(), -1);
updateIndexFromPosition(getLineFieldsAndLabels(), workReportLabelTypeAssigment.getPositionNumber(), -1);
}
}
private void setIndex(Object object, Integer index) {
if (object instanceof DescriptionField) {
if ( object instanceof DescriptionField ) {
((DescriptionField) object).setPositionNumber(index);
} else {
((WorkReportLabelTypeAssigment) object).setPositionNumber(index);
}
}
private void updateIndexFromPosition(List<Object> list, Integer position,
Integer change) {
for (int i = 0; i < list.size(); i++) {
if (getIndex(list.get(i)).compareTo(position) >= 0) {
setIndex(list.get(i), getIndex(list.get(i)) + change);
private void updateIndexFromPosition(List<Object> list, Integer position, Integer change) {
for (Object aList : list) {
if (getIndex(aList).compareTo(position) >= 0) {
setIndex(aList, getIndex(aList) + change);
}
}
}
@ -429,68 +393,74 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
return validateTheIndexFieldsAndLabels(getLineFieldsAndLabels());
}
private boolean validateTheIndexFieldsAndLabels(
List<Object> listFieldsAndLabels) {
private boolean validateTheIndexFieldsAndLabels(List<Object> listFieldsAndLabels) {
List<Object> result = getListToNull(listFieldsAndLabels);
for (Object object : listFieldsAndLabels) {
// Check if index is out of range
Integer index = getIndex(object);
if ((index.compareTo(0) < 0)
|| (index.compareTo(result.size()) >= 0)) {
if ( (index.compareTo(0) < 0) || (index.compareTo(result.size()) >= 0) ) {
return false;
}
// Check if index is repeated
if (result.get(getIndex(object)) != null) {
if ( result.get(getIndex(object)) != null ) {
return false;
}
result.set(getIndex(object), object);
}
// Check if the indexs are consecutives
// Check if the indexes are consecutive
for (Object object : result) {
if (object == null) {
if ( object == null ) {
return false;
}
}
return true;
}
public List<Object> getHeadingFieldsAndLabels() {
List<Object> result = new ArrayList<Object>();
List<Object> result = new ArrayList<>();
result.addAll(getHeadingLabels());
result.addAll(getHeadingFields());
return result;
}
public List<Object> getLineFieldsAndLabels() {
List<Object> result = new ArrayList<Object>();
List<Object> result = new ArrayList<>();
result.addAll(getLineLabels());
result.addAll(getLineFields());
return result;
}
public List<WorkReportLabelTypeAssigment> getHeadingLabels() {
List<WorkReportLabelTypeAssigment> result = new ArrayList<WorkReportLabelTypeAssigment>();
List<WorkReportLabelTypeAssigment> result = new ArrayList<>();
for (WorkReportLabelTypeAssigment label : getWorkReportLabelTypeAssigments()) {
if (label.getLabelsSharedByLines()) {
if ( label.getLabelsSharedByLines() ) {
result.add(label);
}
}
return result;
}
public List<WorkReportLabelTypeAssigment> getLineLabels() {
List<WorkReportLabelTypeAssigment> result = new ArrayList<WorkReportLabelTypeAssigment>();
List<WorkReportLabelTypeAssigment> result = new ArrayList<>();
for (WorkReportLabelTypeAssigment label : getWorkReportLabelTypeAssigments()) {
if (!label.getLabelsSharedByLines()) {
if ( !label.getLabelsSharedByLines() ) {
result.add(label);
}
}
return result;
}
private Integer getIndex(Object object) {
if (object instanceof DescriptionField) {
if ( object instanceof DescriptionField ) {
return ((DescriptionField) object).getPositionNumber();
} else {
return ((WorkReportLabelTypeAssigment) object).getPositionNumber();
@ -498,10 +468,11 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
}
private List<Object> getListToNull(List<Object> list) {
List<Object> result = new ArrayList<Object>(list.size());
List<Object> result = new ArrayList<>(list.size());
for (int i = 0; i < list.size(); i++) {
result.add(null);
}
return result;
}
@ -510,8 +481,7 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
}
private boolean isValidIndexToAdd(Integer position, List<Object> list) {
return ((position.compareTo(0) >= 0) && (position
.compareTo(list.size()) <= 0));
return ((position.compareTo(0) >= 0) && (position.compareTo(list.size()) <= 0));
}
@Override
@ -525,18 +495,11 @@ public class WorkReportType extends IntegrationEntity implements IHumanIdentifia
}
public boolean isPersonalTimesheetsType() {
if (StringUtils.isBlank(name)) {
return false;
}
return name.equals(PredefinedWorkReportTypes.PERSONAL_TIMESHEETS
.getName());
return !StringUtils.isBlank(name) && name.equals(PredefinedWorkReportTypes.PERSONAL_TIMESHEETS.getName());
}
public boolean isJiraTimesheetsType() {
if (StringUtils.isBlank(name)) {
return false;
}
return name.equals(PredefinedWorkReportTypes.JIRA_TIMESHEETS.getName());
return !StringUtils.isBlank(name) && name.equals(PredefinedWorkReportTypes.JIRA_TIMESHEETS.getName());
}
}

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="use-capacity-instead-of-effort_duration-and-not_over_assignable" author="ogonzalez">
<comment>Convert from duration + notAssignable (not over assignable) to capacity property</comment>

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="add-new-column-ldap-host" author="calvarinop">
<comment>Add new column to store ldap host</comment>
@ -60,8 +61,7 @@
</addColumn>
</changeSet>
<changeSet id="add-new-column-navalplan-user"
author="idiazt">
<changeSet id="add-new-column-navalplan-user" author="idiazt">
<comment>Add new column to store if it is a navalplan user</comment>
<addColumn tableName="user_table">
<column name="navalplan_user" type="BOOLEAN" />
@ -319,8 +319,9 @@
<changeSet id="change-navalplan_user-to-libreplan_user-in-user_table" author="mrego">
<comment>Changing navalplan_user to libreplan_user in user_table</comment>
<renameColumn tableName="user_table" oldColumnName="navalplan_user"
newColumnName="libreplan_user" columnDataType="BOOLEAN" />
<renameColumn tableName="user_table"
oldColumnName="navalplan_user"
newColumnName="libreplan_user" columnDataType="BOOLEAN" />
</changeSet>
<changeSet id="add-new-column-ldap-role-strategy" author="idiazt">

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="smontes" id="initial-database-creation-customer-comunication">
<createTable tableName="customer_comunication">
@ -18,6 +19,7 @@
<column name="order_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="smontes" id="initial-database-creation-subcontractor-comunication">
<createTable tableName="subcontractor_comunication">
<column name="id" type="BIGINT">
@ -32,6 +34,7 @@
<column name="subcontracted_task_data" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="smontes" id="initial-database-creation-subcontractor-comunication-value">
<createTable tableName="subcontrator_comunication_values">
<column name="subcontractor_comunication_id" type="BIGINT">
@ -45,7 +48,8 @@
</createTable>
</changeSet>
<changeSet id="rename-table-customer_comunication-to-customer_communication" author="smontes">
<changeSet id="rename-table-customer_comunication-to-customer_communication" author="smontes">
<comment>Rename table customer_comunication to customer_communication</comment>
<renameTable oldTableName="customer_comunication" newTableName="customer_communication" />
</changeSet>

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="change-column-notes-in-task_element-to-text"
author="jaragunde" dbms="postgresql">

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="add-id_cost_category-column-to-criterion-table" author="ltilve">
<comment>Add column to criterion table to store the relationship with cost category</comment>

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="adding-email_template-table" author="vova/jeroen">

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="mrego" id="initial-database-creation-1">
<createTable tableName="advance_assignment">
@ -15,6 +16,7 @@
<column name="advance_type_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-2">
<createTable tableName="advance_assignment_template">
<column name="id" type="BIGINT">
@ -29,6 +31,7 @@
<column name="max_value" type="DECIMAL(19,2)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-3">
<createTable tableName="advance_measurement">
<column name="id" type="BIGINT">
@ -43,6 +46,7 @@
<column name="communication_date" type="DATETIME"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-4">
<createTable tableName="advance_type">
<column name="id" type="BIGINT">
@ -60,6 +64,7 @@
<column name="quality_form" type="BOOLEAN"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-5">
<createTable tableName="all_criterions">
<column name="generic_resource_allocation_id" type="BIGINT">
@ -70,6 +75,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-6">
<createTable tableName="assignment_function">
<column name="id" type="BIGINT">
@ -80,6 +86,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-7">
<createTable tableName="base_calendar">
<column name="id" type="BIGINT">
@ -96,6 +103,7 @@
<column name="last_sequence_code" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-8">
<createTable tableName="calendar_availability">
<column name="id" type="BIGINT">
@ -113,6 +121,7 @@
<column name="position_in_calendar" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-9">
<createTable tableName="calendar_data">
<column name="id" type="BIGINT">
@ -130,6 +139,7 @@
<column name="position_in_calendar" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-10">
<createTable tableName="calendar_exception">
<column name="id" type="BIGINT">
@ -147,6 +157,7 @@
<column name="base_calendar_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-11">
<createTable tableName="calendar_exception_type">
<column name="id" type="BIGINT">
@ -167,6 +178,7 @@
<column name="duration" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-12">
<createTable tableName="configuration">
<column name="id" type="BIGINT">
@ -225,6 +237,7 @@
<column name="progress_type" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-13">
<createTable tableName="consolidated_value">
<column name="id" type="BIGINT">
@ -243,6 +256,7 @@
<column name="advance_measurement_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-14">
<createTable tableName="consolidation">
<column name="id" type="BIGINT">
@ -258,6 +272,7 @@
<column name="ind_advance_assignment_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-15">
<createTable tableName="cost_category">
<column name="id" type="BIGINT">
@ -279,6 +294,7 @@
<column name="enabled" type="BOOLEAN"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-16">
<createTable tableName="criterion">
<column name="id" type="BIGINT">
@ -299,6 +315,7 @@
<column name="parent" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-17">
<createTable tableName="criterion_requirement">
<column name="id" type="BIGINT">
@ -318,6 +335,7 @@
<column name="valid" type="BOOLEAN"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-18">
<createTable tableName="criterion_satisfaction">
<column name="id" type="BIGINT">
@ -342,6 +360,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-19">
<createTable tableName="criterion_type">
<column name="id" type="BIGINT">
@ -366,6 +385,7 @@
<column name="resource" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-20">
<createTable tableName="day_assignment">
<column name="id" type="BIGINT">
@ -392,6 +412,7 @@
<column name="derived_container_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-21">
<createTable tableName="dependency">
<column name="id" type="BIGINT">
@ -406,6 +427,7 @@
<column name="type" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-22">
<createTable tableName="derived_allocation">
<column name="id" type="BIGINT">
@ -420,6 +442,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-23">
<createTable tableName="derived_day_assignments_container">
<column name="id" type="BIGINT">
@ -432,6 +455,7 @@
<column name="scenario" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-24">
<createTable tableName="description_values">
<column name="description_value_id" type="BIGINT">
@ -441,6 +465,7 @@
<column name="value" type="VARCHAR(255)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-25">
<createTable tableName="description_values_in_line">
<column name="description_value_id" type="BIGINT">
@ -450,6 +475,7 @@
<column name="value" type="VARCHAR(255)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-26">
<createTable tableName="direct_advance_assignment">
<column name="advance_assignment_id" type="BIGINT">
@ -459,6 +485,7 @@
<column name="max_value" type="DECIMAL(19,2)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-27">
<createTable tableName="effort_per_day">
<column name="base_calendar_id" type="BIGINT">
@ -470,6 +497,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-28">
<createTable tableName="entity_sequence">
<column name="id" type="BIGINT">
@ -485,6 +513,7 @@
<column name="active" type="BOOLEAN"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-29">
<createTable tableName="external_company">
<column name="id" type="BIGINT">
@ -504,6 +533,7 @@
<column name="company_user" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-30">
<createTable tableName="generic_day_assignments_container">
<column name="id" type="BIGINT">
@ -520,6 +550,7 @@
<column name="duration_in_last_day" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-31">
<createTable tableName="generic_resource_allocation">
<column name="resource_allocation_id" type="BIGINT">
@ -528,6 +559,7 @@
<column name="resource_type" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-32">
<createTable tableName="heading_field">
<column name="heading_id" type="BIGINT">
@ -538,6 +570,7 @@
<column name="positionnumber" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-33">
<createTable tableName="hour_cost">
<column name="id" type="BIGINT">
@ -556,6 +589,7 @@
<column name="cost_category_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-34">
<createTable tableName="hours_group">
<column name="id" type="BIGINT">
@ -577,6 +611,7 @@
<column name="order_line_template" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-35">
<createTable tableName="indirect_advance_assignment">
<column name="advance_assignment_id" type="BIGINT">
@ -585,6 +620,7 @@
<column name="indirect_order_element_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-36">
<createTable tableName="label">
<column name="id" type="BIGINT">
@ -600,6 +636,7 @@
<column name="label_type_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-37">
<createTable tableName="label_type">
<column name="id" type="BIGINT">
@ -618,6 +655,7 @@
<column name="last_label_sequence_code" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-38">
<createTable tableName="limiting_resource_queue">
<column name="id" type="BIGINT">
@ -629,6 +667,7 @@
<column name="resource_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-39">
<createTable tableName="limiting_resource_queue_dependency">
<column name="id" type="BIGINT">
@ -639,6 +678,7 @@
<column name="destiny_queue_element_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-40">
<createTable tableName="limiting_resource_queue_element">
<column name="id" type="BIGINT">
@ -658,6 +698,7 @@
<column name="end_hour" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-41">
<createTable tableName="line_field">
<column name="heading_id" type="BIGINT">
@ -668,6 +709,7 @@
<column name="positionnumber" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-42">
<createTable tableName="machine">
<column name="machine_id" type="BIGINT">
@ -677,6 +719,7 @@
<column name="description" type="VARCHAR(255)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-43">
<createTable tableName="machine_configuration_unit_required_criterions">
<column name="id" type="BIGINT">
@ -687,6 +730,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-44">
<createTable tableName="machine_worker_assignment">
<column name="id" type="BIGINT">
@ -703,6 +747,7 @@
<column name="worker_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-45">
<createTable tableName="machine_workers_configuration_unit">
<column name="id" type="BIGINT">
@ -722,6 +767,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-46">
<createTable tableName="material">
<column name="id" type="BIGINT">
@ -740,6 +786,7 @@
<column name="category_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-47">
<createTable tableName="material_assigment">
<column name="id" type="BIGINT">
@ -756,6 +803,7 @@
<column name="order_element_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-48">
<createTable tableName="material_assigment_template">
<column name="id" type="BIGINT">
@ -770,6 +818,7 @@
<column name="order_element_template_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-49">
<createTable tableName="material_category">
<column name="id" type="BIGINT">
@ -791,6 +840,7 @@
<column name="parent_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-50">
<createTable tableName="order_authorization">
<column name="id" type="BIGINT">
@ -810,6 +860,7 @@
<column name="profile_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-51">
<createTable tableName="order_element">
<column name="id" type="BIGINT">
@ -832,6 +883,7 @@
<column name="position_in_container" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-52">
<createTable tableName="order_element_label">
<column name="order_element_id" type="BIGINT">
@ -842,6 +894,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-53">
<createTable tableName="order_element_template">
<column name="id" type="BIGINT">
@ -860,6 +913,7 @@
<column name="position_in_container" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-54">
<createTable tableName="order_element_template_label">
<column name="order_element_template_id" type="BIGINT">
@ -870,6 +924,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-55">
<createTable tableName="order_element_template_quality_form">
<column name="order_element_template_id" type="BIGINT">
@ -880,6 +935,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-56">
<createTable tableName="order_line">
<column name="order_element_id" type="BIGINT">
@ -888,6 +944,7 @@
<column name="last_hours_group_sequence_code" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-57">
<createTable tableName="order_line_group">
<column name="order_element_id" type="BIGINT">
@ -895,6 +952,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-58">
<createTable tableName="order_line_group_template">
<column name="group_template_id" type="BIGINT">
@ -902,6 +960,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-59">
<createTable tableName="order_line_template">
<column name="order_line_template_id" type="BIGINT">
@ -910,6 +969,7 @@
<column name="last_hours_group_sequence_code" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-60">
<createTable tableName="order_table">
<column name="order_element_id" type="BIGINT">
@ -929,6 +989,7 @@
<column name="base_calendar_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-61">
<createTable tableName="order_template">
<column name="order_template_id" type="BIGINT">
@ -937,6 +998,7 @@
<column name="base_calendar_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-62">
<createTable tableName="order_version">
<column name="id" type="BIGINT">
@ -949,6 +1011,7 @@
<column name="ownerscenario" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-63">
<createTable tableName="planning_data">
<column name="planning_data_id" type="BIGINT">
@ -958,6 +1021,7 @@
<column name="progress_by_num_hours" type="DECIMAL(19,2)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-64">
<createTable tableName="profile_roles">
<column name="profile_id" type="BIGINT">
@ -966,6 +1030,7 @@
<column name="elt" type="VARCHAR(255)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-65">
<createTable tableName="profile_table">
<column name="id" type="BIGINT">
@ -979,6 +1044,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-66">
<createTable tableName="quality_form">
<column name="id" type="BIGINT">
@ -994,6 +1060,7 @@
<column name="advance_type_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-67">
<createTable tableName="quality_form_items">
<column name="quality_form_id" type="BIGINT">
@ -1007,6 +1074,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-68">
<createTable tableName="resource">
<column name="id" type="BIGINT">
@ -1027,6 +1095,7 @@
<column name="base_calendar_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-69">
<createTable tableName="resource_allocation">
<column name="id" type="BIGINT">
@ -1042,6 +1111,7 @@
<column name="assignment_function" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-70">
<createTable tableName="resource_calendar">
<column name="base_calendar_id" type="BIGINT">
@ -1052,6 +1122,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-71">
<createTable tableName="resources_cost_category_assignment">
<column name="id" type="BIGINT">
@ -1069,6 +1140,7 @@
<column name="resource_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-72">
<createTable tableName="roles_table">
<column name="user_id" type="BIGINT">
@ -1077,6 +1149,7 @@
<column name="elt" type="VARCHAR(255)"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-73">
<createTable tableName="scenario">
<column name="id" type="BIGINT">
@ -1091,6 +1164,7 @@
<column name="predecessor" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-74">
<createTable tableName="scenario_orders">
<column name="order_id" type="BIGINT">
@ -1104,6 +1178,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-75">
<createTable tableName="scheduling_data_for_version">
<column name="id" type="BIGINT">
@ -1116,6 +1191,7 @@
<column name="order_element_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-76">
<createTable tableName="scheduling_states_by_order_version">
<column name="order_element_id" type="BIGINT">
@ -1129,6 +1205,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-77">
<createTable tableName="sigmoid_function">
<column name="assignment_function_id" type="BIGINT">
@ -1136,6 +1213,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-78">
<createTable tableName="specific_day_assignments_container">
<column name="id" type="BIGINT">
@ -1152,6 +1230,7 @@
<column name="duration_in_last_day" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-79">
<createTable tableName="specific_resource_allocation">
<column name="resource_allocation_id" type="BIGINT">
@ -1160,6 +1239,7 @@
<column name="resource" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-80">
<createTable tableName="stretches">
<column name="assignment_function_id" type="BIGINT">
@ -1179,6 +1259,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-81">
<createTable tableName="stretches_function">
<column name="assignment_function_id" type="BIGINT">
@ -1187,6 +1268,7 @@
<column name="type" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-82">
<createTable tableName="subcontracted_task_data">
<column name="id" type="BIGINT">
@ -1208,6 +1290,7 @@
<column name="state" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-83">
<createTable tableName="sum_charged_hours">
<column name="id" type="BIGINT">
@ -1220,6 +1303,7 @@
<column name="indirect_charged_hours" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-84">
<createTable tableName="task">
<column name="task_element_id" type="BIGINT">
@ -1234,6 +1318,7 @@
<column name="priority" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-85">
<createTable tableName="task_element">
<column name="id" type="BIGINT">
@ -1260,6 +1345,7 @@
<column name="position_in_parent" type="INTEGER"/>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-86">
<createTable tableName="task_group">
<column name="task_element_id" type="BIGINT">
@ -1267,6 +1353,7 @@
</column>
</createTable>
</changeSet>
<changeSet author="mrego" id="initial-database-creation-87">
<createTable tableName="task_milestone">
<column name="task_element_id" type="BIGINT">

View file

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="resize-precision-in-planning_data" author="dpino">
<comment>Resize precision for 'progress_by_duration' and 'progress_by_num_hours' fields</comment>
@ -32,7 +33,8 @@
</changeSet>
<changeSet id="rename start_constraint_type in task and task milestone" author="ogonzalez">
<comment>Caused by renaming org.libreplan.business.planner.entities.TaskPositionConstraint.startConstraintType</comment>
<comment>Caused by renaming
org.libreplan.business.planner.entities.TaskPositionConstraint.startConstraintType</comment>
<renameColumn tableName="task" oldColumnName="start_constraint_type"
newColumnName="constraint_type" columnDataType="INTEGER" />
<renameColumn tableName="task_milestone"
@ -57,7 +59,8 @@
</changeSet>
<changeSet id="remove-stretches-with-amountWorkPercentage-equal-100" author="dpino">
<comment>Removes all stretches which amountWorkPercentage value is 100 as now these stretches will be created automatically and never stored into DB</comment>
<comment>Removes all stretches which amountWorkPercentage value is 100 as now these stretches will be created
automatically and never stored into DB</comment>
<sql>
DELETE FROM stretches WHERE amount_work_percentage = 1.00;
</sql>

View file

@ -1,14 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<include file="src/main/resources/db.changelog-database.xml"/>
<include file="src/main/resources/db.changelog-initial.xml"/>
<include file="src/main/resources/db.changelog-1.0.xml"/>
<include file="src/main/resources/db.changelog-1.1.xml"/>
<include file="src/main/resources/db.changelog-1.2.xml"/>
<include file="src/main/resources/db.changelog-1.3.xml"/>
<include file="src/main/resources/db.changelog-1.4.xml"/>
<include file="src/main/resources/db.changelog-1.5.xml"/>
<include file="db.changelog-database.xml"/>
<include file="db.changelog-initial.xml"/>
<include file="db.changelog-1.0.xml"/>
<include file="db.changelog-1.1.xml"/>
<include file="db.changelog-1.2.xml"/>
<include file="db.changelog-1.3.xml"/>
<include file="db.changelog-1.4.xml"/>
<include file="db.changelog-1.5.xml"/>
</databaseChangeLog>

View file

@ -1,6 +1,6 @@
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

View file

@ -4,8 +4,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
@ -21,8 +21,9 @@
<!-- Hibernate Session Factory. -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:configLocation="classpath:/libreplan-business-hibernate.cfg.xml">
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="classpath:/libreplan-business-hibernate.cfg.xml">
<property name="mappingResources">
<list>
<value>
@ -109,7 +110,7 @@
<!-- Spring Transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!-- Enable configuration of transactional behavior based on annotations -->
@ -123,20 +124,20 @@
<bean id="registry" class="org.libreplan.business.common.Registry" factory-method="getInstance" />
<bean id="criterionRequirementOrderElementHandler"
class="org.libreplan.business.orders.entities.CriterionRequirementOrderElementHandler"
factory-method="getInstance" />
class="org.libreplan.business.orders.entities.CriterionRequirementOrderElementHandler"
factory-method="getInstance" />
<bean id="versionInformation"
class="org.libreplan.business.common.VersionInformation"
factory-method="getInstance"
lazy-init="false">
class="org.libreplan.business.common.VersionInformation"
factory-method="getInstance"
lazy-init="false">
<property name="projectVersion" value="${project.version}"/>
</bean>
<bean id="configuration"
class="org.libreplan.business.common.Configuration"
factory-method="getInstance"
lazy-init="false">
class="org.libreplan.business.common.Configuration"
factory-method="getInstance"
lazy-init="false">
<property name="defaultPasswordsControl" value="${default.passwordsControl}"/>
<property name="exampleUsersDisabled" value="${default.exampleUsersDisabled}"/>
<property name="emailSendingEnabled" value="${default.emailSendingEnabled}"/>

View file

@ -1,138 +1,140 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.advance.entities" default-access="field">
<!-- AdvanceType -->
<class name="AdvanceType" table="advance_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- AdvanceType -->
<class name="AdvanceType" table="advance_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="unitName" access="field" unique="true" column="unit_name" />
<property name="defaultMaxValue" access="field" scale="4" column="default_max_value" />
<property name="updatable" access="field"/>
<property name="unitPrecision" access="field" scale="4" column="unit_precision" />
<property name="active" access="field"/>
<property name="percentage" access="field"/>
<property name="qualityForm" access="field" column="quality_form" />
<property name="readOnly" column="read_only" />
<version name="version" access="property" type="long" />
</class>
<property name="unitName" access="field" unique="true" column="unit_name" />
<!-- AdvanceAssignment -->
<class name="AdvanceAssignment" table="advance_assignment">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<property name="defaultMaxValue" access="field" scale="4" column="default_max_value" />
<version name="version" access="property" type="long" />
<property name="updatable" access="field"/>
<property name="reportGlobalAdvance" access="field" column="report_global_advance" />
<property name="unitPrecision" access="field" scale="4" column="unit_precision" />
<!-- Not indexed -->
<many-to-one name="advanceType" class="AdvanceType" column="advance_type_id"/>
<property name="active" access="field"/>
<joined-subclass name="DirectAdvanceAssignment" table="direct_advance_assignment">
<key column="advance_assignment_id"/>
<property name="percentage" access="field"/>
<property name="qualityForm" access="field" column="quality_form" />
<property name="readOnly" column="read_only" />
</class>
<!-- AdvanceAssignment -->
<class name="AdvanceAssignment" table="advance_assignment">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="reportGlobalAdvance" access="field" column="report_global_advance" />
<!-- Not indexed -->
<many-to-one name="advanceType" class="AdvanceType" column="advance_type_id"/>
<joined-subclass name="DirectAdvanceAssignment" table="direct_advance_assignment">
<key column="advance_assignment_id"/>
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="direct_order_element_id" index="idx_direct_advance_assigment_on_order_element"/>
<property name="maxValue" access="field" scale="2" column="max_value" />
<set name="advanceMeasurements" cascade="all,delete-orphan" inverse="true" access="field"
sort="org.libreplan.business.advance.entities.AdvanceMeasurementComparator" >
<key column="advance_assignment_id" />
<one-to-many class="org.libreplan.business.advance.entities.AdvanceMeasurement"/>
</set>
<!-- Not indexed -->
<set name="nonCalculatedConsolidations" cascade="none" inverse="true" access="field">
<key column="dir_advance_assignment_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.NonCalculatedConsolidation" />
</set>
</joined-subclass>
<joined-subclass name="IndirectAdvanceAssignment" table="indirect_advance_assignment">
<key column="advance_assignment_id"/>
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="indirect_order_element_id" index="idx_indirect_advance_assigment_on_order_element"/>
<!-- Not indexed -->
<set name="calculatedConsolidations" cascade="none" inverse="true" access="field">
<key column="ind_advance_assignment_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.CalculatedConsolidation" />
</set>
</joined-subclass>
</class>
<!-- AdvanceMeasurement -->
<class name="AdvanceMeasurement" table="advance_measurement">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="date" access="field"/>
<property name="value" scale="2" access="field" />
<many-to-one name="advanceAssignment" class="AdvanceAssignment" column="advance_assignment_id" access="field" />
<property name="communicationDate" access="field" column="communication_date" />
<!-- Not indexed -->
<set name="nonCalculatedConsolidatedValues" access="field" cascade="none" inverse="true" batch-size="10">
<key column="advance_measurement_id" />
<one-to-many
class="org.libreplan.business.planner.entities.consolidations.NonCalculatedConsolidatedValue" />
</set>
</class>
<class name="AdvanceAssignmentTemplate" table="advance_assignment_template">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- Not indexed -->
<many-to-one name="advanceType" class="AdvanceType" column="advance_type_id" />
<!-- Indexed -->
<many-to-one name="orderElement"
class="org.libreplan.business.orders.entities.OrderElement"
column="direct_order_element_id"
index="idx_direct_advance_assigment_on_order_element"/>
<many-to-one name="template" class="org.libreplan.business.templates.entities.OrderElementTemplate"
column="order_element_template_id" index="idx_advance_assigment_template_on_template"/>
<property name="reportGlobalAdvance" access="field" column="report_global_advance" />
<property name="maxValue" access="field" scale="2" column="max_value" />
<set name="advanceMeasurements"
cascade="all,delete-orphan"
inverse="true"
access="field"
sort="org.libreplan.business.advance.entities.AdvanceMeasurementComparator" >
<key column="advance_assignment_id" />
<one-to-many class="org.libreplan.business.advance.entities.AdvanceMeasurement"/>
</set>
</class>
<!-- Not indexed -->
<set name="nonCalculatedConsolidations"
cascade="none"
inverse="true"
access="field">
<key column="dir_advance_assignment_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.NonCalculatedConsolidation" />
</set>
</joined-subclass>
<joined-subclass name="IndirectAdvanceAssignment" table="indirect_advance_assignment">
<key column="advance_assignment_id"/>
<!-- Indexed -->
<many-to-one name="orderElement"
class="org.libreplan.business.orders.entities.OrderElement"
column="indirect_order_element_id"
index="idx_indirect_advance_assigment_on_order_element"/>
<!-- Not indexed -->
<set name="calculatedConsolidations"
cascade="none"
inverse="true"
access="field">
<key column="ind_advance_assignment_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.CalculatedConsolidation" />
</set>
</joined-subclass>
</class>
<!-- AdvanceMeasurement -->
<class name="AdvanceMeasurement" table="advance_measurement">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="date" access="field"/>
<property name="value" scale="2" access="field" />
<many-to-one name="advanceAssignment" class="AdvanceAssignment" column="advance_assignment_id" access="field" />
<property name="communicationDate" access="field" column="communication_date" />
<!-- Not indexed -->
<set name="nonCalculatedConsolidatedValues" access="field" cascade="none" inverse="true" batch-size="10">
<key column="advance_measurement_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.NonCalculatedConsolidatedValue" />
</set>
</class>
<class name="AdvanceAssignmentTemplate" table="advance_assignment_template">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- Not indexed -->
<many-to-one name="advanceType" class="AdvanceType" column="advance_type_id" />
<!-- Indexed -->
<many-to-one name="template"
class="org.libreplan.business.templates.entities.OrderElementTemplate"
column="order_element_template_id"
index="idx_advance_assigment_template_on_template"/>
<property name="reportGlobalAdvance" access="field" column="report_global_advance" />
<property name="maxValue" access="field" scale="2" column="max_value" />
</class>
</hibernate-mapping>

View file

@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field"
package="org.libreplan.business.calendars.entities">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.libreplan.business.calendars.entities">
<!-- BaseCalendar -->
<class name="BaseCalendar" table="base_calendar">
<cache usage="read-write"/>
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -17,11 +18,9 @@
<property name="name" access="field"/>
<property name="codeAutogenerated" access="field"
column="code_autogenerated" />
<property name="codeAutogenerated" access="field" column="code_autogenerated" />
<property name="lastSequenceCode" access="field"
column="last_sequence_code" />
<property name="lastSequenceCode" access="field" column="last_sequence_code" />
<!-- Index created in a database-object section -->
<set name="exceptions" access="field" cascade="all-delete-orphan" batch-size="10" lazy="false">
@ -46,19 +45,19 @@
<joined-subclass name="ResourceCalendar" table="resource_calendar" lazy="false">
<key column="base_calendar_id" />
<property name="capacity" not-null="true" />
<one-to-one name="resource"
class="org.libreplan.business.resources.entities.Resource"
access="field" property-ref="calendar" />
<one-to-one name="resource" class="org.libreplan.business.resources.entities.Resource" access="field"
property-ref="calendar" />
</joined-subclass>
</class>
<!-- CalendarException -->
<class name="CalendarException" table="calendar_exception">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
@ -67,9 +66,9 @@
<component name="capacity" class="org.libreplan.business.calendars.entities.Capacity">
<property name="standardEffort" column="standard_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"></property>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="allowedExtraEffort" column="allowed_extra_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"></property>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<!-- Not indexed -->
<many-to-one name="type" cascade="none"
@ -80,16 +79,16 @@
<!-- CalendarExceptionType -->
<class name="CalendarExceptionType" table="calendar_exception_type">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="codeAutogenerated" access="field" not-null="true"
column="code_autogenerated" />
<property name="codeAutogenerated" access="field" not-null="true" column="code_autogenerated" />
<property name="name" unique="true" />
@ -98,25 +97,26 @@
<property name="color">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.calendars.entities.CalendarExceptionTypeColor</param>
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</property>
<component name="capacity" class="org.libreplan.business.calendars.entities.Capacity">
<property name="standardEffort" column="standard_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"></property>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="allowedExtraEffort" column="allowed_extra_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"></property>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
</class>
<!-- CalendarData -->
<class name="CalendarData" table="calendar_data">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
@ -125,10 +125,12 @@
<key column="base_calendar_id"/>
<index column="day_id" type="integer" />
<composite-element class="org.libreplan.business.calendars.entities.Capacity">
<property name="standardEffort" column="standard_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="allowedExtraEffort" column="allowed_extra_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</composite-element>
</map>
@ -141,7 +143,7 @@
<!-- CalendarAvailability -->
<class name="CalendarAvailability" table="calendar_availability">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -160,16 +162,16 @@
<database-object>
<create>CREATE INDEX idx_calendar_exception_on_base_calendar ON calendar_exception (base_calendar_id)</create>
<drop>DROP INDEX idx_calendar_exception_on_base_calendar</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
<!-- Index to boost the search of CalendarData that hang from a BaseCalendar -->
<database-object>
<create>CREATE INDEX idx_calendar_data_on_base_calendar ON calendar_data (base_calendar_id)</create>
<drop>DROP INDEX idx_calendar_data_on_base_calendar</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
</hibernate-mapping>

View file

@ -1,70 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field"
package="org.libreplan.business.common.entities">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.libreplan.business.common.entities">
<!-- Configuration -->
<class name="Configuration" table="configuration">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- Not indexed -->
<many-to-one name="defaultCalendar" cascade="none"
column="configuration_id" />
<many-to-one name="defaultCalendar" cascade="none" column="configuration_id" />
<property name="companyCode" column="company_code" />
<property name="generateCodeForCostCategory" not-null="true"
column="generate_code_for_cost_category" />
<property name="generateCodeForCostCategory" not-null="true" column="generate_code_for_cost_category" />
<property name="generateCodeForCalendarExceptionType" not-null="true"
column="generate_code_for_calendar_exception_type" />
<property name="generateCodeForWorkReportType" not-null="true"
column="generate_code_for_work_report_type" />
<property name="generateCodeForCriterion" not-null="true"
column="generate_code_for_criterion" />
<property name="generateCodeForLabel" not-null="true"
column="generate_code_for_label" />
<property name="generateCodeForWorkReport" not-null="true"
column="generate_code_for_work_report" />
<property name="generateCodeForResources" not-null="true"
column="generate_code_for_resources" />
column="generate_code_for_calendar_exception_type" />
<property name="generateCodeForWorkReportType" not-null="true" column="generate_code_for_work_report_type" />
<property name="generateCodeForCriterion" not-null="true" column="generate_code_for_criterion" />
<property name="generateCodeForLabel" not-null="true" column="generate_code_for_label" />
<property name="generateCodeForWorkReport" not-null="true" column="generate_code_for_work_report" />
<property name="generateCodeForResources" not-null="true" column="generate_code_for_resources" />
<property name="generateCodeForTypesOfWorkHours" not-null="true"
column="generate_code_for_types_of_work_hours" />
column="generate_code_for_types_of_work_hours" />
<property name="generateCodeForMaterialCategories" not-null="true"
column="generate_code_for_material_categories" />
<property name="generateCodeForUnitTypes" not-null="true"
column="generate_code_for_unit_types" />
<property name="generateCodeForBaseCalendars" not-null="true"
column="generate_code_for_base_calendars" />
<property name="generateCodeForExpenseSheets" not-null="true"
column="generate_code_for_expense_sheets" />
<property name="monteCarloMethodTabVisible" not-null="true"
column="monte_carlo_method_tab_visible" />
<property name="changedDefaultAdminPassword" not-null="true"
column="changed_default_admin_password" />
<property name="changedDefaultWsreaderPassword" not-null="true"
column="changed_default_wsreader_password" />
<property name="changedDefaultWswriterPassword" not-null="true"
column="changed_default_wswriter_password" />
column="generate_code_for_material_categories" />
<property name="generateCodeForUnitTypes" not-null="true" column="generate_code_for_unit_types" />
<property name="generateCodeForBaseCalendars" not-null="true" column="generate_code_for_base_calendars" />
<property name="generateCodeForExpenseSheets" not-null="true" column="generate_code_for_expense_sheets" />
<property name="monteCarloMethodTabVisible" not-null="true" column="monte_carlo_method_tab_visible" />
<property name="changedDefaultAdminPassword" not-null="true" column="changed_default_admin_password" />
<property name="changedDefaultWsreaderPassword" not-null="true" column="changed_default_wsreader_password" />
<property name="changedDefaultWswriterPassword" not-null="true" column="changed_default_wswriter_password" />
<property name="changedDefaultWssubcontractingPassword" not-null="true"
column="changed_default_wssubcontracting_password" />
<property name="changedDefaultManagerPassword" not-null="true"
column="changed_default_manager_password" />
column="changed_default_wssubcontracting_password" />
<property name="changedDefaultManagerPassword" not-null="true" column="changed_default_manager_password" />
<property name="changedDefaultHresourcesPassword" not-null="true"
column="changed_default_hresources_password" />
column="changed_default_hresources_password" />
<property name="changedDefaultOutsourcingPassword" not-null="true"
column="changed_default_outsourcing_password" />
<property name="changedDefaultReportsPassword" not-null="true"
column="changed_default_reports_password" />
<property name="autocompleteLogin" not-null="true"
column="enabled_autocomplete_login" />
<property name="checkNewVersionEnabled" not-null="true"
column="check_new_version_enabled" />
<property name="allowToGatherUsageStatsEnabled" not-null="true"
column="allow_to_gather_usage_stats_enabled" />
column="changed_default_outsourcing_password" />
<property name="changedDefaultReportsPassword" not-null="true" column="changed_default_reports_password" />
<property name="autocompleteLogin" not-null="true" column="enabled_autocomplete_login" />
<property name="checkNewVersionEnabled" not-null="true" column="check_new_version_enabled" />
<property name="allowToGatherUsageStatsEnabled" not-null="true" column="allow_to_gather_usage_stats_enabled" />
<property name="progressType" column="progress_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.common.entities.ProgressType</param>
@ -72,15 +64,12 @@
</property>
<property name="companyLogoURL" column="company_logo_url" />
<property name="scenariosVisible" not-null="true"
column="scenarios_visible" />
<property name="scenariosVisible" not-null="true" column="scenarios_visible" />
<property name="currencyCode" not-null="true" column="currency_code" />
<property name="currencySymbol" not-null="true" column="currency_symbol" />
<many-to-one name="personalTimesheetsTypeOfWorkHours" cascade="none"
column="personal_timesheets_type_of_work_hours" />
column="personal_timesheets_type_of_work_hours" />
<property name="personalTimesheetsPeriodicity" column="personal_timesheets_periodicity">
<type name="org.hibernate.type.EnumType">
@ -88,17 +77,11 @@
</type>
</property>
<many-to-one name="budgetDefaultTypeOfWorkHours" cascade="none"
column="automatic_budget_type_of_work_hours" />
<property name="enabledAutomaticBudget" not-null="true"
column="automatic_budget_enabled" />
<many-to-one name="budgetDefaultTypeOfWorkHours" cascade="none" column="automatic_budget_type_of_work_hours" />
<property name="enabledAutomaticBudget" not-null="true" column="automatic_budget_enabled" />
<property name="maxUsers" column="max_users" />
<property name="maxResources" column="max_resources" />
<property name="secondsPlanningWarning" not-null="true"
column="seconds_planning_warning" />
<property name="secondsPlanningWarning" not-null="true" column="seconds_planning_warning" />
<component name="ldapConfiguration" class="org.libreplan.business.common.entities.LDAPConfiguration">
<property name="ldapHost" column="ldap_host"/>
@ -118,10 +101,8 @@
<set name="configurationRolesLdap" table="configuration_roles_ldap" lazy="false" batch-size="10">
<key column="id_configuration" />
<composite-element class="ConfigurationRolesLDAP">
<property name="roleLdap" column="role_ldap"
not-null="true" />
<property name="roleLibreplan" column="role_libreplan"
not-null="true" />
<property name="roleLdap" column="role_ldap" not-null="true" />
<property name="roleLibreplan" column="role_libreplan" not-null="true" />
</composite-element>
</set>

View file

@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field"
package="org.libreplan.business.common.entities">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.libreplan.business.common.entities">
<class name="Connector" table="connector">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -19,8 +20,7 @@
<list-index column="connector_property_position" />
<composite-element class="ConnectorProperty">
<property name="key" column="property_key"
not-null="true" />
<property name="key" column="property_key" not-null="true" />
<property name="value" column="property_value" />
</composite-element>
</list>

View file

@ -1,15 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field"
package="org.libreplan.business.common.entities">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.libreplan.business.common.entities">
<!-- EntitySequence -->
<class name="EntitySequence" table="entity_sequence">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<id name="id" column="id" type="java.lang.Long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="entityName" column="entity_name">
@ -17,9 +19,13 @@
<param name="enumClass">org.libreplan.business.common.entities.EntityNameEnum</param>
</type>
</property>
<property name="prefix" />
<property name="lastValue" column="last_value" />
<property name="numberOfDigits" column="number_of_digits" />
<property name="active" />
</class>

View file

@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field"
package="org.libreplan.business.common.entities">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.libreplan.business.common.entities">
<class name="JobSchedulerConfiguration" table="job_scheduler_configuration">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -13,14 +14,20 @@
<version name="version" access="property" type="long" />
<property name="jobGroup" column="job_group" not-null="true" />
<property name="jobName" column="job_name" not-null="true" />
<property name="cronExpression" column="cron_expression" not-null="true" />
<property name="jobClassName" access="field" column="job_class_name" not-null="true">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.common.entities.JobClassNameEnum</param>
</type>
</property>
<property name="connectorName" column="connector_name" />
<property name="schedule" column="schedule" />
</class>

View file

@ -1,16 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.email.entities" default-access="field">
<class name="org.libreplan.business.common.entities.Limits" abstract="true" table="limits">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<property name="type" column="type"/>
<property name="value" column="value" type="integer"/>
</class>

View file

@ -1,105 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.costcategories.entities" default-access="field">
<!-- CostCategory -->
<class name="CostCategory" table="cost_category">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- CostCategory -->
<class name="CostCategory" table="cost_category">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" unique="true"/>
<property name="codeAutogenerated" not-null="true" access="field"
column="code_autogenerated" />
<property name="lastHourCostSequenceCode" not-null="true" access="field"
column="last_hour_cost_sequence_code" />
<property name="enabled"/>
<version name="version" access="property" type="long" />
<!-- Indexed the other side -->
<set name="hourCosts" inverse="true" cascade="all-delete-orphan" batch-size="10">
<key column="cost_category_id"/>
<one-to-many class="HourCost"/>
</set>
</class>
<property name="code" access="property" not-null="true" unique="true"/>
<!-- HourCost -->
<class name="HourCost" table="hour_cost">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="name" unique="true"/>
<property name="code" access="property" not-null="true" unique="true"/>
<property name="priceCost" column="price_cost" />
<property name="codeAutogenerated" not-null="true" access="field" column="code_autogenerated" />
<property name="initDate" column="init_date" />
<property name="lastHourCostSequenceCode" not-null="true" access="field"
column="last_hour_cost_sequence_code" />
<property name="endDate" column="end_date" />
<property name="enabled"/>
<many-to-one name="type" class="TypeOfWorkHours" column="type_of_work_hours_id" />
<!-- Indexed the other side -->
<set name="hourCosts" inverse="true" cascade="all-delete-orphan" batch-size="10">
<key column="cost_category_id"/>
<one-to-many class="HourCost"/>
</set>
</class>
<!-- Indexed -->
<many-to-one name="category"
class="CostCategory"
column="cost_category_id"
index="idx_hour_cost_on_category"/>
<!-- HourCost -->
<class name="HourCost" table="hour_cost">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
</class>
<version name="version" access="property" type="long" />
<!-- TypeOfWorkHours -->
<class name="TypeOfWorkHours" table="type_of_work_hours">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" unique="true"/>
<property name="priceCost" column="price_cost" />
<property name="code" unique="true"/>
<property name="initDate" column="init_date" />
<property name="defaultPrice" column="default_price" />
<property name="endDate" column="end_date" />
<property name="enabled"/>
<many-to-one name="type" class="TypeOfWorkHours" column="type_of_work_hours_id" />
<property name="codeAutogenerated" not-null="true"
column="code_autogenerated" />
<!-- Indexed -->
<many-to-one name="category" class="CostCategory" column="cost_category_id" index="idx_hour_cost_on_category"/>
</class>
</class>
<!-- ResourcesCostCategoryAssignment -->
<class name="ResourcesCostCategoryAssignment" table="resources_cost_category_assignment">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- TypeOfWorkHours -->
<class name="TypeOfWorkHours" table="type_of_work_hours">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="code" access="property" not-null="true" unique="true"/>
<version name="version" access="property" type="long" />
<property name="initDate" column="init_date" />
<property name="name" unique="true"/>
<property name="endDate" column="end_date" />
<property name="code" unique="true"/>
<!-- Not Indexed -->
<many-to-one name="costCategory"
class="CostCategory"
column="cost_category_id"/>
<property name="defaultPrice" column="default_price" />
<!-- Indexed -->
<many-to-one name="resource"
class="org.libreplan.business.resources.entities.Resource"
column="resource_id"
index="idx_resource_costcategory_assigment_on_resource"/>
<property name="enabled"/>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
</class>
<!-- ResourcesCostCategoryAssignment -->
<class name="ResourcesCostCategoryAssignment" table="resources_cost_category_assignment">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="initDate" column="init_date" />
<property name="endDate" column="end_date" />
<!-- Not Indexed -->
<many-to-one name="costCategory" class="CostCategory" column="cost_category_id"/>
<!-- Indexed -->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource" column="resource_id"
index="idx_resource_costcategory_assigment_on_resource"/>
</class>
</class>
</hibernate-mapping>

View file

@ -1,11 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.email.entities" default-access="field">
<class name="org.libreplan.business.email.entities.EmailTemplate" abstract="true" table="email_template">
<class name="org.libreplan.business.email.entities.EmailTemplate" table="email_template">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
@ -27,10 +29,10 @@
</class>
<class name="EmailNotification" abstract="true" table="notification_queue" dynamic-insert="true">
<class name="EmailNotification" table="notification_queue" dynamic-insert="true">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>

View file

@ -1,32 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.expensesheet.entities"
default-access="field">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.expensesheet.entities" default-access="field">
<!-- ExpenseSheetLine -->
<class name="ExpenseSheetLine" table="expense_sheet_line">
<cache usage="nonstrict-read-write" />
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true"
unique="true" />
<property name="code" access="property" not-null="true" unique="true" />
<property name="value" access="field" column="value" />
<property name="concept" access="field" column="concept" />
<property name="date" access="field" column="date" />
<many-to-one name="orderElement" column="order_element_id"
class="org.libreplan.business.orders.entities.OrderElement" />
class="org.libreplan.business.orders.entities.OrderElement" />
<many-to-one name="resource" column="resource_id"
class="org.libreplan.business.resources.entities.Resource" />
<many-to-one name="resource" column="resource_id" class="org.libreplan.business.resources.entities.Resource" />
<many-to-one name="expenseSheet" class="ExpenseSheet"
column="expense_sheet_id" index="idx_expense_sheet_line" />
column="expense_sheet_id" index="idx_expense_sheet_line" />
</class>
@ -34,17 +35,16 @@
<class name="ExpenseSheet" table="expense_sheet">
<cache usage="nonstrict-read-write" />
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true"
unique="true" />
<property name="code" access="property" not-null="true" unique="true" />
<property name="codeAutogenerated" not-null="true"
column="code_autogenerated" />
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="firstExpense" access="field" column="first_expense" />
@ -52,19 +52,16 @@
<property name="total" access="field" column="total" />
<property name="description" access="field" column="description"
type="text" />
<property name="description" access="field" column="description" type="text" />
<property name="lastExpenseSheetLineSequenceCode" access="field"
column="last_expense_sheet_line_sequence_code" />
column="last_expense_sheet_line_sequence_code" />
<!-- Indexed the other side -->
<set name="expenseSheetLines" inverse="true" cascade="all,delete-orphan"
access="field"
sort="org.libreplan.business.expensesheet.entities.ExpenseSheetLineComparator">
<set name="expenseSheetLines" inverse="true" cascade="all,delete-orphan" access="field"
sort="org.libreplan.business.expensesheet.entities.ExpenseSheetLineComparator">
<key column="expense_sheet_id" />
<one-to-many
class="org.libreplan.business.expensesheet.entities.ExpenseSheetLine" />
<one-to-many class="org.libreplan.business.expensesheet.entities.ExpenseSheetLine" />
</set>
<property name="personal" />

View file

@ -1,81 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.externalcompanies.entities" default-access="field">
<!-- ExternalCompany -->
<class name="ExternalCompany" table="external_company">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- ExternalCompany -->
<class name="ExternalCompany" table="external_company">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="name" unique="true" />
<version name="version" access="property" type="long" />
<property name="nif" unique="true" />
<property name="name" unique="true" />
<property name="client" />
<property name="nif" unique="true" />
<property name="subcontractor" />
<property name="client" />
<property name="interactsWithApplications"
column="interacts_with_applications" />
<property name="subcontractor" />
<property name="appURI" column="app_uri" />
<property name="interactsWithApplications" column="interacts_with_applications" />
<property name="ourCompanyLogin" column="our_company_login" />
<property name="appURI" column="app_uri" />
<property name="ourCompanyPassword" column="our_company_password" />
<property name="ourCompanyLogin" column="our_company_login" />
<!-- Not indexed, navigation from User to this is not even implemented -->
<many-to-one name="companyUser" class="org.libreplan.business.users.entities.User"
column="company_user" />
</class>
<property name="ourCompanyPassword" column="our_company_password" />
<!-- CustomerCommunication -->
<class name="CustomerCommunication" table="customer_communication">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- Not indexed, navigation from User to this is not even implemented -->
<many-to-one name="companyUser" class="org.libreplan.business.users.entities.User" column="company_user" />
</class>
<property name="deadline" access="field"/>
<property name="communicationType" access="field" column="communication_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.externalcompanies.entities.CommunicationType</param>
</type>
</property>
<property name="communicationDate" access="field" column="communication_date" />
<property name="reviewed" access="field" column="reviewed" />
<many-to-one name="order" class="org.libreplan.business.orders.entities.Order" column="order_id" />
</class>
<!-- CustomerCommunication -->
<class name="CustomerCommunication" table="customer_communication">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<!-- DeadlineCommunication -->
<class name="DeadlineCommunication" table="deadline_communication">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<version name="version" access="property" type="long" />
<property name="saveDate" access="field" column="save_date"/>
<property name="deliverDate" access="field" column="deliver_date" />
</class>
<property name="deadline" access="field"/>
<property name="communicationType" access="field" column="communication_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.externalcompanies.entities.CommunicationType</param>
</type>
</property>
<property name="communicationDate" access="field" column="communication_date" />
<property name="reviewed" access="field" column="reviewed" />
<many-to-one name="order" class="org.libreplan.business.orders.entities.Order" column="order_id" />
</class>
<!-- DeadlineCommunication -->
<class name="DeadlineCommunication" table="deadline_communication">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="saveDate" access="field" column="save_date"/>
<property name="deliverDate" access="field" column="deliver_date" />
</class>
<!-- EndDateCommunication -->
<class name="EndDateCommunication" table="end_date_communication">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="endDate" access="field" column="end_date"/>
<property name="saveDate" access="field" column="save_date"/>
<property name="communicationDate" access="field" column="communication_date" />
</class>
<!-- EndDateCommunication -->
<class name="EndDateCommunication" table="end_date_communication">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="endDate" access="field" column="end_date"/>
<property name="saveDate" access="field" column="save_date"/>
<property name="communicationDate" access="field" column="communication_date" />
</class>
</hibernate-mapping>

View file

@ -1,56 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.labels.entities" default-access="field">
<!-- Label -->
<class name="Label" table="label">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<properties name="nameAndType" unique="true">
<property name="name" />
<!-- Indexed -->
<many-to-one name="type" class="LabelType"
column="label_type_id"
index="idx_label_on_label_type"/>
</properties>
<set name="orderElements" table="order_element_label" cascade="none" inverse="true" batch-size="10">
<key column="label_id" not-null="false"/>
<many-to-many column="order_element_id" class="org.libreplan.business.orders.entities.OrderElement"/>
</set>
</class>
<!-- LabelType -->
<class name="LabelType" table="label_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" unique="true"/>
<property name="codeAutogenerated" not-null="true"
column="code_autogenerated" />
<property name="lastLabelSequenceCode" access="field"
column="last_label_sequence_code" />
<!-- Indexed the other side -->
<set name="labels" inverse="false" cascade="all-delete-orphan" batch-size="10">
<!-- Label -->
<class name="Label" table="label">
<cache usage="nonstrict-read-write"/>
<key column="label_type_id"/>
<one-to-many class="Label"/>
</set>
</class>
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<properties name="nameAndType" unique="true">
<property name="name" />
<!-- Indexed -->
<many-to-one name="type" class="LabelType" column="label_type_id" index="idx_label_on_label_type"/>
</properties>
<set name="orderElements" table="order_element_label" cascade="none" inverse="true" batch-size="10">
<key column="label_id" not-null="false"/>
<many-to-many column="order_element_id" class="org.libreplan.business.orders.entities.OrderElement"/>
</set>
</class>
<!-- LabelType -->
<class name="LabelType" table="label_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" unique="true"/>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="lastLabelSequenceCode" access="field" column="last_label_sequence_code" />
<!-- Indexed the other side -->
<set name="labels" inverse="false" cascade="all-delete-orphan" batch-size="10">
<cache usage="nonstrict-read-write"/>
<key column="label_type_id"/>
<one-to-many class="Label"/>
</set>
</class>
</hibernate-mapping>

View file

@ -1,9 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.logs.entities" default-access="field">
<class name="IssueLog" table="issue_log">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -56,7 +59,7 @@
<class name="RiskLog" table="risk_log">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>

View file

@ -1,143 +1,136 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.materials.entities" default-access="field">
<!-- Material -->
<class name="Material" table="material">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- Material -->
<class name="Material" table="material">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" unique="true" not-null="true"/>
<property name="code" unique="true" not-null="true"/>
<property name="description"/>
<property name="description"/>
<property name="defaultUnitPrice" column="default_unit_price" />
<property name="defaultUnitPrice" column="default_unit_price" />
<!-- Not indexed -->
<many-to-one name="unitType" class="UnitType" column="unit_type" />
<!-- Not indexed -->
<many-to-one name="unitType" class="UnitType" column="unit_type" />
<property name="disabled"/>
<property name="disabled"/>
<!-- Indexed -->
<many-to-one name="category"
class="MaterialCategory"
column="category_id"
index="idx_material_on_category"/>
<!-- Indexed -->
<many-to-one name="category" class="MaterialCategory" column="category_id" index="idx_material_on_category"/>
</class>
</class>
<!-- UnitType -->
<class name="UnitType" table="unit_type">
<cache usage="nonstrict-read-write"/>
<!-- UnitType -->
<class name="UnitType" table="unit_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="code" access="property" not-null="true" unique="true"/>
<property name="measure" access="field"/>
<property name="codeAutogenerated" not-null="true"
column="code_autogenerated" />
<version name="version" access="property" type="long" />
</class>
<property name="code" access="property" not-null="true" unique="true"/>
<property name="measure" access="field"/>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<!-- MaterialCategory -->
<class name="MaterialCategory" table="material_category">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
</class>
<property name="code" access="property" not-null="true" unique="true"/>
<!-- MaterialCategory -->
<class name="MaterialCategory" table="material_category">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="name" />
<version name="version" access="property" type="long" />
<property name="codeAutogenerated" not-null="true"
column="code_autogenerated" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="lastMaterialSequenceCode" access="field" not-null="true"
column="last_material_sequence_code" />
<property name="name" />
<!-- Indexed the other side -->
<set name="subcategories" inverse="true" cascade="all-delete-orphan" batch-size="10">
<key column="parent_id"/>
<one-to-many class="MaterialCategory"/>
</set>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<!-- Indexed -->
<many-to-one name="parent"
class="MaterialCategory"
column="parent_id"
index="idx_material_category_on_parent"/>
<property name="lastMaterialSequenceCode" access="field" not-null="true" column="last_material_sequence_code" />
<!-- Indexed the other side -->
<set name="materials" inverse="true" cascade="all-delete-orphan" batch-size="10">
<key column="category_id"/>
<one-to-many class="Material"/>
</set>
<!-- Indexed the other side -->
<set name="subcategories" inverse="true" cascade="all-delete-orphan" batch-size="10">
<key column="parent_id"/>
<one-to-many class="MaterialCategory"/>
</set>
</class>
<!-- Indexed -->
<many-to-one name="parent" class="MaterialCategory" column="parent_id" index="idx_material_category_on_parent"/>
<!-- MaterialAssignment -->
<class name="MaterialAssignment" table="material_assigment">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- Indexed the other side -->
<set name="materials" inverse="true" cascade="all-delete-orphan" batch-size="10">
<key column="category_id"/>
<one-to-many class="Material"/>
</set>
<component name="materialInfo">
<property name="units" />
<property name="unitPrice" column="unit_price" />
<many-to-one name="material" class="Material" column="material_id" />
</component>
</class>
<property name="estimatedAvailability" column="estimated_availability" />
<!-- MaterialAssignment -->
<class name="MaterialAssignment" table="material_assigment">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="status">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.materials.entities.MaterialStatusEnum</param>
</type>
</property>
<version name="version" access="property" type="long" />
<!-- Indexed. -->
<many-to-one name="orderElement"
class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id"
index="idx_material_assigment_on_order_element"/>
<component name="materialInfo">
<property name="units" />
<property name="unitPrice" column="unit_price" />
<many-to-one name="material" class="Material" column="material_id" />
</component>
</class>
<property name="estimatedAvailability" column="estimated_availability" />
<class name="MaterialAssignmentTemplate" table="material_assigment_template">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="status">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.materials.entities.MaterialStatusEnum</param>
</type>
</property>
<component name="materialInfo">
<property name="units" />
<property name="unitPrice" column="unit_price" />
<many-to-one name="material" class="Material" column="material_id" />
</component>
<!-- Indexed. -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id" index="idx_material_assigment_on_order_element"/>
<!-- Indexed -->
<many-to-one name="orderElementTemplate"
class="org.libreplan.business.templates.entities.OrderElementTemplate"
column="order_element_template_id"
index="idx_material_assigment_template_on_order_element"/>
</class>
</class>
<class name="MaterialAssignmentTemplate" table="material_assigment_template">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<component name="materialInfo">
<property name="units" />
<property name="unitPrice" column="unit_price" />
<many-to-one name="material" class="Material" column="material_id" />
</component>
<!-- Indexed -->
<many-to-one name="orderElementTemplate" class="org.libreplan.business.templates.entities.OrderElementTemplate"
column="order_element_template_id" index="idx_material_assigment_template_on_order_element"/>
</class>
</hibernate-mapping>

View file

@ -1,22 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.orders.entities" default-access="field">
<class name="OrderElement" table="order_element" abstract="true">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<component name="infoComponent" class="org.libreplan.business.orders.entities.InfoComponentWithCode">
<property name="name" access="field" />
<property name="description" access="field" type="text" />
<property name="code" access="field" />
</component>
<property name="initDate" access="field" column="init_date" />
<property name="deadline" access="field" />
<property name="lastAdvanceMeausurementForSpreading" access="field"
column="last_advance_meausurement_for_spreading" />
<property name="dirtyLastAdvanceMeasurementForSpreading" access="field"
column="dirty_last_advance_measurement_for_spreading" />
@ -33,7 +42,7 @@
<!-- Indexed the other side -->
<set name="criterionRequirements" access="field" cascade="all,delete-orphan" inverse="true" batch-size="10">
<key column="order_element_id" not-null="false"></key>
<key column="order_element_id" not-null="false"/>
<one-to-many class="org.libreplan.business.requirements.entities.CriterionRequirement"/>
</set>
@ -51,62 +60,58 @@
<!-- Inverse navigation from OrderElement to OrderLineGroup -->
<!-- Indexed -->
<many-to-one name="parent"
access="field"
cascade="all"
class="org.libreplan.business.orders.entities.OrderLineGroup"
index="idx_order_element_on_parent"
<many-to-one name="parent" access="field" cascade="all"
class="org.libreplan.business.orders.entities.OrderLineGroup" index="idx_order_element_on_parent"
lazy="false" />
<many-to-one name="template"
access="field"
cascade="none"
<many-to-one name="template" access="field" cascade="none"
class="org.libreplan.business.templates.entities.OrderElementTemplate"
index="idx_order_element_on_template"/>
<property name="externalCode" access="field" column="external_code" />
<map name="schedulingDatasForVersion" table="scheduling_states_by_order_version"
cascade="all-delete-orphan">
<key column="order_element_id"></key>
<map name="schedulingDatasForVersion" table="scheduling_states_by_order_version" cascade="all-delete-orphan">
<key column="order_element_id"/>
<map-key-many-to-many column="order_version_id"
class="org.libreplan.business.scenarios.entities.OrderVersion" />
<many-to-many class="SchedulingDataForVersion"
column="scheduling_state_for_version_id" />
<many-to-many class="SchedulingDataForVersion" column="scheduling_state_for_version_id" />
</map>
<one-to-one name="sumChargedEffort" class="SumChargedEffort"
cascade="delete" property-ref="orderElement" />
<one-to-one name="sumChargedEffort" class="SumChargedEffort" cascade="delete" property-ref="orderElement" />
<one-to-one name="sumExpenses" class="SumExpenses"
cascade="delete" property-ref="orderElement" />
<one-to-one name="sumExpenses" class="SumExpenses" cascade="delete" property-ref="orderElement" />
<joined-subclass name="OrderLineGroup" table="order_line_group">
<key column="order_element_id"></key>
<joined-subclass name="OrderLineGroup" table="order_line_group">
<key column="order_element_id"/>
<!-- Indexed the other side -->
<list name="children" access="field" cascade="all">
<key column="parent" not-null="false"></key>
<index column="position_in_container"></index>
<key column="parent" not-null="false"/>
<index column="position_in_container"/>
<one-to-many class="OrderElement" />
</list>
<!-- Indexed the other side -->
<set name="indirectAdvanceAssignments" access="field" cascade="all,delete-orphan" inverse="true" batch-size="10">
<set name="indirectAdvanceAssignments" access="field" cascade="all,delete-orphan" inverse="true"
batch-size="10">
<key column="indirect_order_element_id" />
<one-to-many class="org.libreplan.business.advance.entities.IndirectAdvanceAssignment" />
</set>
<joined-subclass name="Order" table="order_table">
<key column="order_element_id"></key>
<key column="order_element_id"/>
<property name="responsible" access="field" />
<property name="dependenciesConstraintsHavePriority"
column="dependencies_constraints_have_priority" access="field" />
<property name="codeAutogenerated" column="code_autogenerated"
<property name="dependenciesConstraintsHavePriority" column="dependencies_constraints_have_priority"
access="field" />
<property name="codeAutogenerated" column="code_autogenerated" access="field" />
<property name="lastOrderElementSequenceCode" column="last_order_element_sequence_code"
access="field" />
<property name="lastOrderElementSequenceCode"
column="last_order_element_sequence_code" access="field" />
<property name="workBudget" column="work_budget" access="field" />
<property name="materialsBudget" column="materials_budget" access="field" />
@ -125,12 +130,15 @@
<param name="enumClass">org.libreplan.business.orders.entities.Order$SchedulingMode</param>
</type>
</property>
<!-- extra column to hold projects hours- and budget- margin -->
<property name="hoursMargin" column="hours_margin" access="field" />
<property name="budgetMargin" column="budget_margin" access="field" />
<!-- Not indexed -->
<many-to-one name="customer" access="field" class="org.libreplan.business.externalcompanies.entities.ExternalCompany"/>
<many-to-one name="customer" access="field"
class="org.libreplan.business.externalcompanies.entities.ExternalCompany"/>
<!-- Not indexed -->
<many-to-one name="calendar" column="base_calendar_id" cascade="none"
@ -145,6 +153,7 @@
<key column="order_id" />
<map-key-many-to-many column="scenario_id"
class="org.libreplan.business.scenarios.entities.Scenario" />
<many-to-many column="order_version_id"
class="org.libreplan.business.scenarios.entities.OrderVersion"/>
</map>
@ -170,16 +179,15 @@
</joined-subclass>
<joined-subclass name="OrderLine" table="order_line">
<key column="order_element_id"></key>
<key column="order_element_id"/>
<!-- Indexed the other side -->
<set name="hoursGroups" access="field" cascade="all,delete-orphan" inverse="true" batch-size="10">
<key column="parent_order_line" not-null="false"></key>
<key column="parent_order_line" not-null="false"/>
<one-to-many class="HoursGroup" />
</set>
<property name="lastHoursGroupSequenceCode"
column="last_hours_group_sequence_code" access="field" />
<property name="lastHoursGroupSequenceCode" column="last_hours_group_sequence_code" access="field" />
<property name="budget" scale="2" access="field" />
</joined-subclass>
@ -187,10 +195,11 @@
<class name="HoursGroup" table="hours_group">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="field" not-null="true" unique="true" />
@ -198,7 +207,7 @@
<property name="resourceType" access="field" column="resource_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.resources.entities.ResourceEnum</param>
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</property>
@ -208,7 +217,7 @@
<!-- Indexed the other side -->
<set name="criterionRequirements" access="field" cascade="save-update,delete-orphan" inverse="true" batch-size="10">
<key column="hours_group_id" not-null="false"></key>
<key column="hours_group_id" not-null="false"/>
<one-to-many class="org.libreplan.business.requirements.entities.CriterionRequirement"/>
</set>
@ -226,18 +235,23 @@
<class name="SchedulingDataForVersion" table="scheduling_data_for_version">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="schedulingStateType" access="field" column="scheduling_state_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.orders.entities.SchedulingState$Type</param>
</type>
</property>
<many-to-one name="orderElement" column="order_element_id" lazy="false"></many-to-one>
<one-to-one name="taskSource" class="TaskSource" cascade="delete" access="field" property-ref="schedulingData" />
<many-to-one name="orderElement" column="order_element_id" lazy="false"/>
<one-to-one name="taskSource" class="TaskSource" cascade="delete" access="field"
property-ref="schedulingData" />
</class>
<class name="TaskSource" table="task_source">
@ -246,55 +260,57 @@
<param name="property">task</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<many-to-one name="schedulingData" class="SchedulingDataForVersion"
cascade="none" unique="true" access="field" lazy="false" />
<one-to-one name="task" class="org.libreplan.business.planner.entities.TaskElement"
constrained="true" cascade="delete" access="field" lazy="false"/>
<set name="hoursGroups" table="task_source_hours_groups" cascade="none" inverse="false" access="field" batch-size="10">
<key column="task_source_id"></key>
<version name="version" access="property" type="long" />
<many-to-one name="schedulingData" class="SchedulingDataForVersion" cascade="none" unique="true" access="field"
lazy="false" />
<one-to-one name="task" class="org.libreplan.business.planner.entities.TaskElement" constrained="true"
cascade="delete" access="field" lazy="false"/>
<set name="hoursGroups" table="task_source_hours_groups" cascade="none" inverse="false" access="field"
batch-size="10">
<key column="task_source_id"/>
<many-to-many class="HoursGroup" column="hours_group_id"/>
</set>
</class>
<class name="SumChargedEffort" table="sum_charged_effort">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<many-to-one name="orderElement" column="order_element"
class="OrderElement" cascade="none" unique="true" />
<many-to-one name="orderElement" column="order_element" class="OrderElement" cascade="none" unique="true" />
<property name="directChargedEffort" access="field"
column="direct_charged_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
<property name="indirectChargedEffort" access="field"
column="indirect_charged_effort"
<property name="directChargedEffort" access="field" column="direct_charged_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
<property name="firstTimesheetDate" access="field"
column="first_timesheet_date" />
<property name="lastTimesheetDate" access="field"
column="last_timesheet_date" />
<property name="finishedTimesheets"
column="finished_timesheets" />
<property name="indirectChargedEffort" access="field" column="indirect_charged_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
<property name="firstTimesheetDate" access="field" column="first_timesheet_date" />
<property name="lastTimesheetDate" access="field" column="last_timesheet_date" />
<property name="finishedTimesheets" column="finished_timesheets" />
</class>
<class name="SumExpenses" table="sum_expenses">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<many-to-one name="orderElement" column="order_element_id" cascade="none" unique="true"
class="OrderElement" />
<many-to-one name="orderElement" column="order_element_id" cascade="none" unique="true" class="OrderElement" />
<property name="totalDirectExpenses" access="field" column="total_direct_expenses"/>
<property name="totalIndirectExpenses" access="field" column="total_indirect_expenses"/>
@ -302,13 +318,17 @@
<class name="OrderSyncInfo" table="order_sync_info">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="lastSyncDate" column="last_sync_date" access="field" not-null="true"/>
<property name="key" access="field" not-null="true"/>
<property name="connectorName" column="connector_name" access="field" not-null="true"/>
<many-to-one name="order" class="Order">
@ -316,9 +336,9 @@
</many-to-one>
</class>
<class name="OrderFile" abstract="true" table="files">
<class name="OrderFile" table="files">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -329,11 +349,10 @@
<property name="date" column="date"/>
<many-to-one name="uploader"
class="org.libreplan.business.users.entities.User" column="uploader" lazy="false"/>
<many-to-one name="uploader" class="org.libreplan.business.users.entities.User" column="uploader" lazy="false"/>
<many-to-one name="parent"
class="org.libreplan.business.orders.entities.OrderElement" column="parent" lazy="false"/>
<many-to-one name="parent" class="org.libreplan.business.orders.entities.OrderElement" column="parent"
lazy="false"/>
</class>

View file

@ -1,90 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities.consolidations" default-access="field">
<class name="ConsolidatedValue" table="consolidated_value">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<discriminator column="consolidated_value_type" type="string"/>
<version name="version" access="property" type="long" />
<property name="date" access="field"/>
<property name="value" scale="2" access="field" />
<component name="taskEndDate" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="task_end_date" />
<property name="effortDuration" column="task_end_date_effort_duration"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<subclass name="NonCalculatedConsolidatedValue" discriminator-value="non_calculated">
<!-- Indexed -->
<many-to-one name="consolidation" class="NonCalculatedConsolidation"
column="consolidation_id" access="field"
index="idx_non_calculated_consolidated_value_on_non_calculated_consolidation" />
<many-to-one name="consolidation" class="NonCalculatedConsolidation" column="consolidation_id"
access="field" index="idx_non_calculated_consolidated_value_on_non_calculated_consolidation" />
<!-- Not indexed -->
<many-to-one name="advanceMeasurement" class="org.libreplan.business.advance.entities.AdvanceMeasurement"
column="advance_measurement_id" access="field" />
column="advance_measurement_id" access="field" />
</subclass>
<subclass name="CalculatedConsolidatedValue" discriminator-value="calculated">
<!-- Indexed -->
<many-to-one name="consolidation" class="CalculatedConsolidation"
column="consolidation_id" access="field"
index="idx_calculated_consolidated_value_on_calculated_consolidation" />
<many-to-one name="consolidation" class="CalculatedConsolidation" column="consolidation_id" access="field"
index="idx_calculated_consolidated_value_on_calculated_consolidation" />
</subclass>
</class>
</class>
<class name="Consolidation" table="consolidation">
<class name="Consolidation" table="consolidation">
<id name="id" column="id" type="long" access="property">
<generator class="foreign">
<param name="property">task</param>
</generator>
</id>
<discriminator column="consolidation_type" type="string"/>
<version name="version" access="property" type="long" />
<one-to-one name="task" class="org.libreplan.business.planner.entities.Task" constrained="true"/>
<subclass name="NonCalculatedConsolidation" discriminator-value="non_calculated">
<!-- Not indexed -->
<many-to-one name="directAdvanceAssignment" column="dir_advance_assignment_id" access="field"
class="org.libreplan.business.advance.entities.DirectAdvanceAssignment" />
class="org.libreplan.business.advance.entities.DirectAdvanceAssignment" />
<!-- Indexed on the other side -->
<set name="consolidatedValues"
access="field"
cascade="all,delete-orphan"
inverse="true"
sort="org.libreplan.business.planner.entities.consolidations.ConsolidatedValueComparator">
<set name="consolidatedValues" access="field" cascade="all,delete-orphan" inverse="true"
sort="org.libreplan.business.planner.entities.consolidations.ConsolidatedValueComparator">
<key column="consolidation_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.NonCalculatedConsolidatedValue" />
</set>
</subclass>
<subclass name="CalculatedConsolidation" discriminator-value="calculated">
<!-- Not indexed -->
<many-to-one name="indirectAdvanceAssignment" column="ind_advance_assignment_id" access="field"
class="org.libreplan.business.advance.entities.IndirectAdvanceAssignment"/>
class="org.libreplan.business.advance.entities.IndirectAdvanceAssignment"/>
<!-- Indexed on the other side -->
<set name="consolidatedValues"
access="field"
cascade="all,delete-orphan"
inverse="true"
sort="org.libreplan.business.planner.entities.consolidations.ConsolidatedValueComparator">
<set name="consolidatedValues" access="field" cascade="all,delete-orphan" inverse="true"
sort="org.libreplan.business.planner.entities.consolidations.ConsolidatedValueComparator">
<key column="consolidation_id" />
<one-to-many class="org.libreplan.business.planner.entities.consolidations.CalculatedConsolidatedValue" />
</set>
</subclass>
</class>

View file

@ -1,42 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities"
default-access="field">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities" default-access="field">
<!-- ResourceAllocation -->
<class name="ResourceAllocation" table="resource_allocation">
<id name="id" column="id" type="long" access="property">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="resourcesPerDay" type="org.libreplan.business.workingday.hibernate.ResourcesPerDayType"
column="resources_per_day" />
column="resources_per_day" />
<property name="intendedResourcesPerDay" type="org.libreplan.business.workingday.hibernate.ResourcesPerDayType"
column="intended_resources_per_day" />
column="intended_resources_per_day" />
<property name="intendedTotalHours" column="intended_total_hours" />
<property name="intendedTotalAssignment" access="field"
column="intended_total_assignment"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="intendedTotalAssignment" access="field" column="intended_total_assignment"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="intendedNonConsolidatedEffort" access="field"
column="intended_non_consolidated_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="intendedNonConsolidatedEffort" access="field" column="intended_non_consolidated_effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<!-- Indexed -->
<many-to-one class="Task" name="task" column="task" index="idx_resource_allocation_on_task"/>
<!-- It is not included index, navigation from assigment function to
ResourceAllocation not useful
-->
<many-to-one class="AssignmentFunction" name="assignmentFunction"
column="assignment_function" not-null="false"
cascade="all" lazy="false" />
<!-- It is not included index, navigation from assignment function to ResourceAllocation not useful -->
<many-to-one class="AssignmentFunction" name="assignmentFunction" column="assignment_function" not-null="false"
cascade="all" lazy="false" />
<set name="derivedAllocations" cascade="all-delete-orphan" inverse="true">
<key column="resource_allocation_id" />
@ -52,8 +48,7 @@
<joined-subclass name="SpecificResourceAllocation" table="specific_resource_allocation">
<key column="resource_allocation_id" />
<many-to-one name="resource"
class="org.libreplan.business.resources.entities.Resource" />
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource" />
<set name="specificDayAssignmentsContainers" cascade="all-delete-orphan">
<key column="resource_allocation_id" />
@ -85,31 +80,36 @@
<class name="SpecificDayAssignmentsContainer" table="specific_day_assignments_container">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- natural-id use has to be discarded due to:
Resource allocation and scenario should be an unique key.
natural-id could be used for that but was discarded due to:
https://forum.hibernate.org/viewtopic.php?p=2372348
<!--
natural-id use has to be discarded due to:
Resource allocation and scenario should be an unique key.
natural-id could be used for that but was discarded due to:
https://forum.hibernate.org/viewtopic.php?p=2372348
-->
<many-to-one name="resourceAllocation" column="resource_allocation_id"/>
<many-to-one name="scenario" />
<component name="intraDayStart" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="start_date" />
<property name="effortDuration" column="duration_start_in_first_day"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<component name="intraDayEnd" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="end_date" />
<property name="effortDuration" column="duration_in_last_day"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<set name="dayAssignments" cascade="all-delete-orphan">
@ -120,31 +120,35 @@
<class name="GenericDayAssignmentsContainer" table="generic_day_assignments_container">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- natural-id use has to be discarded due to:
Resource allocation and scenario should be an unique key.
natural-id could be used for that but was discarded due to:
https://forum.hibernate.org/viewtopic.php?p=2372348
<!--
natural-id use has to be discarded due to:
Resource allocation and scenario should be an unique key.
natural-id could be used for that but was discarded due to:
https://forum.hibernate.org/viewtopic.php?p=2372348
-->
<many-to-one name="resourceAllocation" column="resource_allocation_id"/>
<many-to-one name="scenario" />
<component name="intraDayStart" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="start_date" />
<property name="effortDuration" column="duration_start_in_first_day"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<component name="intraDayEnd" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="end_date" />
<property name="effortDuration" column="duration_in_last_day"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<set name="dayAssignments" cascade="all-delete-orphan">
@ -155,15 +159,18 @@
<class name="DerivedDayAssignmentsContainer" table="derived_day_assignments_container">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- natural-id use has to be discarded due to:
Resource allocation and scenario should be an unique key.
natural-id could be used for that but was discarded due to:
https://forum.hibernate.org/viewtopic.php?p=2372348
<!--
natural-id use has to be discarded due to:
Resource allocation and scenario should be an unique key.
natural-id could be used for that but was discarded due to:
https://forum.hibernate.org/viewtopic.php?p=2372348
-->
<many-to-one name="resourceAllocation" column="derived_allocation_id"/>
<many-to-one name="scenario" />
@ -174,18 +181,23 @@
</class>
<!-- LimitingResourceQueueElement -->
<class name="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement" table="limiting_resource_queue_element">
<class name="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement"
table="limiting_resource_queue_element">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<many-to-one name="resourceAllocation" column="resource_allocation_id" cascade="all" not-null="false" unique="true" />
<many-to-one name="resourceAllocation" column="resource_allocation_id" cascade="all" not-null="false"
unique="true" />
<!-- Indexed -->
<many-to-one name="limitingResourceQueue" column="limiting_resource_queue_id" index="idx_resource_queue_element_on_resource_queue"/>
<many-to-one name="limitingResourceQueue" column="limiting_resource_queue_id"
index="idx_resource_queue_element_on_resource_queue"/>
<property name="earlierStartDateBecauseOfGantt" column="earlier_start_date_because_of_gantt" />
@ -203,15 +215,13 @@
<property name="hour" column="end_hour" />
</component>
<!-- Indexed the other side. Useful to browse the output dependencies of
a LimitingResourceQueueElement -->
<!-- Indexed the other side. Useful to browse the output dependencies of a LimitingResourceQueueElement -->
<set name="dependenciesAsOrigin" cascade="none" lazy="false">
<key column="origin_queue_element_id"/>
<one-to-many class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueDependency"/>
</set>
<!-- Indexed the other side. Useful to browse the input dependencies of
a LimitingResourceQueueElement -->
<!-- Indexed the other side. Useful to browse the input dependencies of a LimitingResourceQueueElement -->
<set name="dependenciesAsDestiny" cascade="none" lazy="false">
<key column="destiny_queue_element_id"/>
<one-to-many class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueDependency"/>
@ -223,7 +233,7 @@
<class name="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueDependency"
table="limiting_resource_queue_dependency">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -236,49 +246,46 @@
<!-- Indexed -->
<many-to-one name="hasAsOrigin" cascade="none"
class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement"
column="origin_queue_element_id"
not-null="false"
index="idx_queue_dependency_on_origin_queue">
class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement"
column="origin_queue_element_id" not-null="false" index="idx_queue_dependency_on_origin_queue">
</many-to-one>
<!-- Indexed -->
<many-to-one name="hasAsDestiny" cascade="none"
class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement"
column="destiny_queue_element_id"
not-null="false"
index="idx_queue_dependency_on_destiny_queue"
class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement"
column="destiny_queue_element_id" not-null="false" index="idx_queue_dependency_on_destiny_queue"
>
</many-to-one>
<one-to-one name="ganttDependency"
class="Dependency"
property-ref="queueDependency">
<one-to-one name="ganttDependency" class="Dependency" property-ref="queueDependency">
</one-to-one>
</class>
<!-- DayAssignment -->
<class name="DayAssignment" table="day_assignment">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<discriminator column="day_assignment_type" type="string"/>
<version name="version" access="property" type="long" />
<property name="duration" not-null="true"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<property name="consolidated" access="field"/>
<property name="day"/>
<!-- Not indexed. It is not indexed because it is regarded that to navigate
from a resource to all his DayAssigments is not useful -->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource"
column="resource_id" not-null="true">
<!--
Not indexed.
It is not indexed because it is regarded that to navigate from a resource to all his DayAssigments is not useful
-->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource" column="resource_id"
not-null="true">
</many-to-one>
<!-- SpecificDayAssignment -->
@ -290,6 +297,7 @@
<subclass name="GenericDayAssignment" discriminator-value="generic_day">
<many-to-one name="container" column="generic_container_id" />
</subclass>
<subclass name="DerivedDayAssignment" discriminator-value="derived_day">
<many-to-one name="container" column="derived_container_id" />
</subclass>
@ -298,10 +306,11 @@
<!-- AssignmentFunction -->
<class name="AssignmentFunction" table="assignment_function">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<joined-subclass name="StretchesFunction" table="stretches_function">
@ -316,15 +325,18 @@
<property name="amountWorkPercentage" not-null="true" column="amount_work_percentage" />
</composite-element>
</list>
<property name="type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.planner.entities.StretchesFunctionTypeEnum</param>
</type>
</property>
</joined-subclass>
<joined-subclass name="SigmoidFunction" table="sigmoid_function">
<key column="assignment_function_id" />
</joined-subclass>
<joined-subclass name="ManualFunction" table="manual_function">
<key column="assignment_function_id" />
</joined-subclass>
@ -332,15 +344,18 @@
<class name="DerivedAllocation" table="derived_allocation">
<id name="id" type="long" access="property" >
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<many-to-one class="ResourceAllocation" column="resource_allocation_id"
name="derivedFrom" />
<many-to-one class="ResourceAllocation" column="resource_allocation_id" name="derivedFrom" />
<many-to-one class="org.libreplan.business.resources.entities.MachineWorkersConfigurationUnit"
name="configurationUnit" not-null="true"/>
name="configurationUnit" not-null="true"/>
<set name="derivedDayAssignmentsContainers" cascade="all-delete-orphan">
<key column="derived_allocation_id" />
<one-to-many class="DerivedDayAssignmentsContainer"/>

View file

@ -1,51 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities"
default-access="field">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities" default-access="field">
<!-- SubcontractorCommunication -->
<class name="SubcontractorCommunication" table="subcontractor_communication">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="communicationType" access="field"
column="communication_type">
<property name="communicationType" access="field" column="communication_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">
org.libreplan.business.externalcompanies.entities.CommunicationType
</param>
<param name="enumClass">org.libreplan.business.externalcompanies.entities.CommunicationType</param>
</type>
</property>
<property name="communicationDate" access="field"
column="communication_date" />
<property name="communicationDate" access="field" column="communication_date" />
<property name="reviewed" access="field" column="reviewed" />
<many-to-one name="subcontractedTaskData"
class="org.libreplan.business.planner.entities.SubcontractedTaskData"
column="subcontracted_task_data" />
<many-to-one name="subcontractedTaskData" class="org.libreplan.business.planner.entities.SubcontractedTaskData"
column="subcontracted_task_data" />
<list name="subcontractorCommunicationValues" table="subcontractor_communication_values">
<key column="subcontractor_communication_id" />
<index column="idx" />
<composite-element
class="org.libreplan.business.planner.entities.SubcontractorCommunicationValue">
<composite-element class="org.libreplan.business.planner.entities.SubcontractorCommunicationValue">
<property name="date" access="field" />
<property name="progress" access="field" />
</composite-element>
</list>
</class>
<class name="SubcontractorDeliverDate" table="subcontractor_deliver_date">
<id name="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="saveDate" access="field" column="save_date" />
<property name="subcontractorDeliverDate" access="field" column="subcontractor_deliver_date" />
<property name="communicationDate" access="field" column="communication_date" />
</class>

View file

@ -1,79 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities"
default-access="field">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.planner.entities" default-access="field">
<class name="TaskElement" table="task_element">
<id name="id" column="id" type="long" access="property">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="name" />
<property name="notes" type="text" />
<component name="startDate"
class="org.libreplan.business.workingday.IntraDayDate">
<component name="startDate" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="start_date" not-null="true" />
<property name="effortDuration" column="start_day_duration"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<component name="endDate" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="end_date" not-null="true" />
<property name="effortDuration" column="end_day_duration"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
<property name="deadline"/>
<property name="advancePercentage" column="advance_percentage" access="field" scale="4"/>
<property name="sumOfAssignedEffort" column="sum_of_assigned_effort" access="field"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
<!-- Indexed -->
<many-to-one name="parent" class="TaskGroup" cascade="none" column="parent"
index="idx_task_element_on_task_group" lazy="false" />
index="idx_task_element_on_task_group" lazy="false" />
<one-to-one name="taskSource" cascade="delete" />
<!-- Indexed on the other side -->
<set name="dependenciesWithThisOrigin" cascade="all">
<key column="origin"></key>
<key column="origin"/>
<one-to-many class="Dependency" />
</set>
<!-- Not indexed -->
<set name="dependenciesWithThisDestination" cascade="all">
<key column="destination"></key>
<key column="destination"/>
<one-to-many class="Dependency" />
</set>
<!-- Not indexed -->
<many-to-one name="calendar" column="base_calendar_id" cascade="none"
class="org.libreplan.business.calendars.entities.BaseCalendar"/>
class="org.libreplan.business.calendars.entities.BaseCalendar"/>
<property name="updatedFromTimesheets"
column="updated_from_timesheets" />
<property name="updatedFromTimesheets" column="updated_from_timesheets" />
<joined-subclass name="Task" table="task">
<key column="task_element_id"></key>
<key column="task_element_id"/>
<property name="calculatedValue" column="calculated_value">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.planner.entities.CalculatedValue</param>
</type>
</property>
<component name="positionConstraint">
<property name="constraintType" column="constraint_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.planner.entities.PositionConstraintType</param>
</type>
</property>
<component name="constraintDate"
class="org.libreplan.business.workingday.IntraDayDate">
<component name="constraintDate" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="constraint_date" />
<property name="effortDuration" column="constraint_date_effort_duration"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
</component>
@ -85,8 +96,8 @@
</type>
</property>
<one-to-one name="consolidation" class="org.libreplan.business.planner.entities.consolidations.Consolidation"
cascade="all"/>
<one-to-one name="consolidation"
class="org.libreplan.business.planner.entities.consolidations.Consolidation" cascade="all"/>
<!-- Indexed on the other side -->
<set name="resourceAllocations" cascade="all-delete-orphan" lazy="false">
@ -95,29 +106,28 @@
</set>
<!-- Already indexed because it's unique -->
<many-to-one name="subcontractedTaskData"
column="subcontrated_task_data_id"
unique="true" cascade="all" lazy="false" />
<many-to-one name="subcontractedTaskData" column="subcontrated_task_data_id" unique="true" cascade="all"
lazy="false" />
<property name="priority" />
</joined-subclass>
<joined-subclass name="TaskGroup" table="task_group">
<key column="task_element_id"></key>
<key column="task_element_id"/>
<one-to-one name="planningData" class="PlanningData" cascade="all" />
<!-- Indexed on the other side -->
<list name="taskElements" cascade="all">
<key column="parent" not-null="false"></key>
<index column="position_in_parent"></index>
<key column="parent" not-null="false"/>
<index column="position_in_parent"/>
<one-to-many class="TaskElement" />
</list>
</joined-subclass>
<joined-subclass name="TaskMilestone" table="task_milestone">
<key column="task_element_id"></key>
<key column="task_element_id"/>
<component name="startConstraint">
<property name="constraintType" column="constraint_type">
@ -125,12 +135,12 @@
<param name="enumClass">org.libreplan.business.planner.entities.PositionConstraintType</param>
</type>
</property>
<component name="constraintDate"
class="org.libreplan.business.workingday.IntraDayDate">
<component name="constraintDate" class="org.libreplan.business.workingday.IntraDayDate">
<property name="date" column="constraint_date" />
<property name="effortDuration" column="constraint_date_effort_duration"
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
type="org.libreplan.business.workingday.hibernate.EffortDurationType"/>
</component>
</component>
</joined-subclass>
@ -145,11 +155,15 @@
<param name="property">rootTask</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<one-to-one name="rootTask" class="TaskGroup" constrained="true"
cascade="all" lazy="false" />
<one-to-one name="rootTask" class="TaskGroup" constrained="true" cascade="all" lazy="false" />
<property name="progressAllByNumHours" column="progress_all_by_num_hours" scale="6" />
<property name="progressByDuration" column="progress_by_duration" scale="6" />
<property name="progressByNumHours" column="progress_by_num_hours" scale="6" />
</class>
@ -157,25 +171,20 @@
<class name="Dependency" table="dependency">
<id name="id" type="long" access="property">
<generator class="hilo"></generator>
<generator class="increment"/>
</id>
<version name="version" access="property" type="long" />
<!-- Indexed -->
<many-to-one class="TaskElement" name="origin"
column="origin"
index="idx_dependency_on_task_element_origin" />
<many-to-one class="TaskElement" name="origin" column="origin" index="idx_dependency_on_task_element_origin" />
<!-- Not indexed, navigation in that direction is not useful -->
<many-to-one class="TaskElement" name="destination"
column="destination" />
<many-to-one class="TaskElement" name="destination" column="destination" />
<!-- Not indexed, relation from the other side is one-to-one -->
<many-to-one class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueDependency"
cascade="all"
name="queueDependency"
column="queue_dependency"
unique="false" />
cascade="all" name="queueDependency" column="queue_dependency" unique="false" />
<property name="type">
<type name="org.hibernate.type.EnumType">
@ -188,26 +197,33 @@
<!-- SubcontractedTaskData -->
<class name="SubcontractedTaskData" table="subcontracted_task_data">
<id name="id" type="long" access="property">
<generator class="hilo"></generator>
<generator class="increment"/>
</id>
<version name="version" access="property" type="long" />
<!-- Not indexed, navigation from ExternalCompany to this is not even implemented -->
<many-to-one name="externalCompany" class="org.libreplan.business.externalcompanies.entities.ExternalCompany"
column="external_company" />
column="external_company" />
<one-to-one name="task" class="Task"
property-ref="subcontractedTaskData" lazy="false"/>
<one-to-one name="task" class="Task" property-ref="subcontractedTaskData" lazy="false"/>
<property name="subcontratationDate" column="subcontratation_date" />
<property name="subcontractCommunicationDate" column="subcontract_communication_date" />
<property name="workDescription" column="work_description" />
<property name="subcontractPrice" column="subcontract_price"/>
<property name="subcontractedCode" column="subcontracted_code"/>
<property name="nodeWithoutChildrenExported" column="node_without_children_exported" />
<property name="labelsExported" column="labels_exported" />
<property name="materialAssignmentsExported" column="material_assignments_exported" />
<property name="hoursGroupsExported" column="hours_groups_exported" />
<property name="state" >
@ -217,21 +233,17 @@
</property>
<set name="requiredDeliveringDates" inverse="false" cascade="all-delete-orphan" access="field"
sort="org.libreplan.business.externalcompanies.entities.DeliverDateComparator">
sort="org.libreplan.business.externalcompanies.entities.DeliverDateComparator">
<key column="subcontracted_task_data_id" />
<one-to-many class="org.libreplan.business.planner.entities.SubcontractorDeliverDate" />
</set>
<set name="subcontractorCommunications" inverse="true" cascade="delete" access="field">
<key column="subcontracted_task_data" />
<one-to-many class="org.libreplan.business.planner.entities.SubcontractorCommunication" />
</set>
<set name="endDatesCommunicatedFromSubcontractor" inverse="false" cascade="all-delete-orphan" access="field"
sort="org.libreplan.business.externalcompanies.entities.EndDateCommunicationComparator">
sort="org.libreplan.business.externalcompanies.entities.EndDateCommunicationComparator">
<key column="subcontracted_task_data_id" />
<one-to-many class="org.libreplan.business.externalcompanies.entities.EndDateCommunication" />
</set>
</class>
</hibernate-mapping>

View file

@ -1,93 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.qualityforms.entities" default-access="field">
<!-- QualityForm -->
<class name="QualityForm" table="quality_form">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- QualityForm -->
<class name="QualityForm" table="quality_form">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="name" access="field" unique="true"/>
<property name="description" access="field"/>
<version name="version" access="property" type="long" />
<property name="qualityFormType" column="quality_form_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.qualityforms.entities.QualityFormType</param>
</type>
</property>
<property name="name" access="field" unique="true"/>
<!-- Index created in a database-object section -->
<list name="qualityFormItems" table="quality_form_items">
<key column="quality_form_id"/>
<index column="idx"/>
<composite-element class="org.libreplan.business.qualityforms.entities.QualityFormItem">
<property name="description" access="field"/>
<property name="qualityFormType" column="quality_form_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.qualityforms.entities.QualityFormType</param>
</type>
</property>
<!-- Index created in a database-object section -->
<list name="qualityFormItems" table="quality_form_items">
<key column="quality_form_id"/>
<index column="idx"/>
<composite-element class="org.libreplan.business.qualityforms.entities.QualityFormItem">
<property name="name" access="field"/>
<property name="percentage" access="field"/>
<property name="position" access="field"/>
</composite-element>
</list>
</composite-element>
</list>
<property name="reportAdvance" access="field" column="report_advance" />
<property name="reportAdvance" access="field" column="report_advance" />
<many-to-one name="advanceType" column="advance_type_id"
class="org.libreplan.business.advance.entities.AdvanceType" />
<many-to-one name="advanceType" column="advance_type_id"
class="org.libreplan.business.advance.entities.AdvanceType" />
</class>
</class>
<!-- TaskQualityForm -->
<class name="TaskQualityForm" table="task_quality_form">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- TaskQualityForm -->
<class name="TaskQualityForm" table="task_quality_form">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<many-to-one name="qualityForm" class="QualityForm" column="quality_form_id"/>
<version name="version" access="property" type="long" />
<!-- Indexed -->
<many-to-one name="orderElement"
class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id"
index="idx_taskquality_form_on_order_element"/>
<many-to-one name="qualityForm" class="QualityForm" column="quality_form_id"/>
<!-- Index created in a database-object section -->
<list name="taskQualityFormItems" table="task_quality_form_items">
<key column="task_quality_form_id"/>
<index column="idx"/>
<composite-element class="org.libreplan.business.qualityforms.entities.TaskQualityFormItem">
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id" index="idx_taskquality_form_on_order_element"/>
<!-- Index created in a database-object section -->
<list name="taskQualityFormItems" table="task_quality_form_items">
<key column="task_quality_form_id"/>
<index column="idx"/>
<composite-element class="org.libreplan.business.qualityforms.entities.TaskQualityFormItem">
<property name="name" access="field"/>
<property name="percentage" access="field"/>
<property name="position" access="field"/>
<property name="passed" access="field"/>
<property name="date" access="field"/>
</composite-element>
</list>
</composite-element>
</list>
<property name="reportAdvance" access="field" column="report_advance" />
<property name="reportAdvance" access="field" column="report_advance" />
</class>
</class>
<!-- Index to boost the search of QualityFormItems inside a QualityForm -->
<database-object>
<create>CREATE INDEX idx_quality_form_on_quality_form_items
ON quality_form_items (quality_form_id)</create>
<drop>DROP INDEX idx_quality_form_on_quality_form_items</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
</database-object>
<!-- Index to boost the search of QualityFormItems inside a QualityForm -->
<database-object>
<create>CREATE INDEX idx_quality_form_on_quality_form_items ON quality_form_items (quality_form_id)</create>
<drop>DROP INDEX idx_quality_form_on_quality_form_items</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
<!-- Index to boost the search of TaskQualityFormItems inside a TaskQualityForm -->
<database-object>
<create>CREATE INDEX idx_task_quality_form_on_task_quality_form_items
ON task_quality_form_items (task_quality_form_id)</create>
<drop>DROP INDEX idx_task_quality_form_on_task_quality_form_items</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
</database-object>
<!-- Index to boost the search of TaskQualityFormItems inside a TaskQualityForm -->
<database-object>
<create>CREATE INDEX idx_task_quality_form_on_task_quality_form_items
ON task_quality_form_items (task_quality_form_id)</create>
<drop>DROP INDEX idx_task_quality_form_on_task_quality_form_items</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
</hibernate-mapping>

View file

@ -1,53 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.requirements.entities">
<class name="CriterionRequirement" table="criterion_requirement">
<id access="property" name="id" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<class name="CriterionRequirement" table="criterion_requirement">
<discriminator column="criterion_requirement_type" type="string"/>
<id access="property" name="id" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version access="property" name="version" type="long"/>
<discriminator column="criterion_requirement_type" type="string"/>
<!-- Inverse navigation from CriterionRequirement to HoursGroup -->
<!-- Indexed -->
<many-to-one class="org.libreplan.business.orders.entities.HoursGroup"
column="hours_group_id"
name="hoursGroup"
index="idx_criterion_requirement_on_hours_group" />
<version access="property" name="version" type="long"/>
<!-- Inverse navigation from CriterionRequirement to HoursGroup -->
<!-- Indexed -->
<many-to-one class="org.libreplan.business.orders.entities.HoursGroup" column="hours_group_id" name="hoursGroup"
index="idx_criterion_requirement_on_hours_group" />
<!-- Inverse navigation from CriterionRequirement to OrderElement -->
<!-- Indexed -->
<many-to-one class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id"
name="orderElement"
index="idx_criterion_requirement_on_order_element" />
<!-- Inverse navigation from CriterionRequirement to OrderElement -->
<!-- Indexed -->
<many-to-one class="org.libreplan.business.orders.entities.OrderElement" column="order_element_id"
name="orderElement" index="idx_criterion_requirement_on_order_element" />
<!-- Inverse navigation from CriterionRequirement to OrderTemplateElement -->
<many-to-one class="org.libreplan.business.templates.entities.OrderElementTemplate" column="order_element_template_id" name="orderElementTemplate"/>
<!-- Inverse navigation from CriterionRequirement to OrderTemplateElement -->
<many-to-one class="org.libreplan.business.templates.entities.OrderElementTemplate"
column="order_element_template_id" name="orderElementTemplate"/>
<!-- Inverse navigation from CriterionRequirement to Criterion -->
<!-- Not indexed. Other side navigation not useful -->
<many-to-one class="org.libreplan.business.resources.entities.Criterion" column="criterion_id" name="criterion"/>
<!-- Inverse navigation from CriterionRequirement to Criterion -->
<!-- Not indexed. Other side navigation not useful -->
<many-to-one class="org.libreplan.business.resources.entities.Criterion" column="criterion_id"
name="criterion"/>
<subclass discriminator-value="direct" name="DirectCriterionRequirement">
<set access="field" name="children" cascade="delete-orphan" inverse="true" batch-size="10">
<subclass discriminator-value="direct" name="DirectCriterionRequirement">
<set access="field" name="children" cascade="delete-orphan" inverse="true" batch-size="10">
<key column="parent"/>
<one-to-many class="IndirectCriterionRequirement"/>
</set>
</subclass>
<key column="parent"/>
<one-to-many class="IndirectCriterionRequirement"/>
</set>
</subclass>
<subclass discriminator-value="indirect" name="IndirectCriterionRequirement">
<many-to-one class="DirectCriterionRequirement" column="parent" name="parent"/>
<property access="field" name="valid"/>
</subclass>
<subclass discriminator-value="indirect" name="IndirectCriterionRequirement">
<many-to-one class="DirectCriterionRequirement" column="parent" name="parent"/>
<property access="field" name="valid"/>
</subclass>
</class>
</class>
</hibernate-mapping>

View file

@ -1,244 +1,268 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.libreplan.business.resources.entities">
<class name="Resource" table="resource">
<cache usage="read-write"/>
<id name="id" access="property" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<class name="Resource" table="resource">
<cache usage="read-write"/>
<id name="id" access="property" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<!--
IMPORTANT: type="long" must be specified (otherwise,
Hibernate infers type="integer".
-->
<version name="version" access="property" type="long" />
<!-- IMPORTANT: type="long" must be specified (otherwise, Hibernate infers type="integer"). -->
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="code" access="property" not-null="true" unique="true"/>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="resourceType" column="resource_type" not-null="true">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.resources.entities.ResourceType</param>
<param name="type">12</param>
</type>
</property>
<property name="resourceType" column="resource_type" not-null="true">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.resources.entities.ResourceType</param>
<param name="useNamed">true</param>
</type>
</property>
<!-- It is appropiate the index by the foreign key in the many-to-one side -->
<set access="field" cascade="all-delete-orphan" inverse="true" name="criterionSatisfactions">
<cache usage="read-write"/>
<key column="resource" not-null="true"/>
<one-to-many class="CriterionSatisfaction"/>
</set>
<!-- It is appropriate the index by the foreign key in the many-to-one side -->
<set access="field" cascade="all-delete-orphan" inverse="true" name="criterionSatisfactions">
<cache usage="read-write"/>
<key column="resource" not-null="true"/>
<one-to-many class="CriterionSatisfaction"/>
</set>
<!-- Assess the need of this mapping. It seems very heavy and should not be used. Remove it ¿?-->
<set access="field" inverse="true" name="dayAssignments">
<key column="resource_id" not-null="true"/>
<one-to-many class="org.libreplan.business.planner.entities.DayAssignment"/>
</set>
<!-- Assess the need of this mapping. It seems very heavy and should not be used. Remove it ?-->
<set access="field" inverse="true" name="dayAssignments">
<key column="resource_id" not-null="true"/>
<one-to-many class="org.libreplan.business.planner.entities.DayAssignment"/>
</set>
<!-- Not indexed. Navigation from calendars to all the resources which have that calendar
associated not used -->
<many-to-one name="calendar" access="field" cascade="all"
class="org.libreplan.business.calendars.entities.ResourceCalendar"
column="base_calendar_id" unique="true" />
<!-- Not indexed. Navigation from calendars to all the resources which have that calendar associated not used -->
<many-to-one name="calendar" access="field" cascade="all"
class="org.libreplan.business.calendars.entities.ResourceCalendar"
column="base_calendar_id" unique="true" />
<!-- Indexed in the other side -->
<set name="resourcesCostCategoryAssignments" inverse="true" cascade="all-delete-orphan">
<key column="resource_id"/>
<one-to-many class="org.libreplan.business.costcategories.entities.ResourcesCostCategoryAssignment"/>
</set>
<!-- Indexed in the other side -->
<set name="resourcesCostCategoryAssignments" inverse="true" cascade="all-delete-orphan">
<key column="resource_id"/>
<one-to-many class="org.libreplan.business.costcategories.entities.ResourcesCostCategoryAssignment"/>
</set>
<one-to-one name="limitingResourceQueue" property-ref="resource" cascade="all" />
<one-to-one name="limitingResourceQueue" property-ref="resource" cascade="all" />
<joined-subclass name="org.libreplan.business.resources.entities.Worker" table="worker">
<key column="worker_id"/>
<property name="firstName" column="first_name" />
<property name="surname"/>
<property name="nif"/>
<joined-subclass name="org.libreplan.business.resources.entities.Worker" table="worker">
<key column="worker_id"/>
<property name="firstName" column="first_name" />
<property name="surname"/>
<property name="nif"/>
<many-to-one name="user" cascade="save-update" access="property" lazy="false"
class="org.libreplan.business.users.entities.User"
column="user_id" unique="true" />
<many-to-one name="user" cascade="save-update" access="property" lazy="false"
class="org.libreplan.business.users.entities.User" column="user_id" unique="true" />
<joined-subclass name="org.libreplan.business.resources.entities.VirtualWorker" table="virtual_worker">
<key column="virtual_worker_id"/>
<property name="observations"/>
</joined-subclass>
<joined-subclass name="org.libreplan.business.resources.entities.VirtualWorker" table="virtual_worker">
<key column="virtual_worker_id"/>
<property name="observations"/>
</joined-subclass>
</joined-subclass>
<joined-subclass name="org.libreplan.business.resources.entities.Machine" table="machine">
<joined-subclass name="org.libreplan.business.resources.entities.Machine" table="machine">
<key column="machine_id"/>
<property name="name"/>
<property name="description"/>
<set inverse="true" name="configurationUnits" cascade="all-delete-orphan">
<key column="machine" not-null="true" />
<one-to-many
class="MachineWorkersConfigurationUnit" />
</set>
<key column="machine_id"/>
<property name="name"/>
<property name="description"/>
</joined-subclass>
</class>
<set inverse="true" name="configurationUnits" cascade="all-delete-orphan">
<key column="machine" not-null="true" />
<one-to-many class="MachineWorkersConfigurationUnit" />
</set>
<!-- LimitingResourceQueue -->
<class name="LimitingResourceQueue" table="limiting_resource_queue">
<id name="id" access="property" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
</joined-subclass>
</class>
<many-to-one name="resource" column="resource_id" not-null="false" unique="true" />
<!-- LimitingResourceQueue -->
<class name="LimitingResourceQueue" table="limiting_resource_queue">
<id name="id" access="property" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<!-- Indexed the other side -->
<set name="limitingResourceQueueElements" cascade="all-delete-orphan" inverse="true"
sort="org.libreplan.business.resources.entities.LimitingResourceQueueElementComparator">
<key column="limiting_resource_queue_id" not-null="true" />
<one-to-many class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement" />
</set>
<version name="version" access="property" type="long" />
</class>
<many-to-one name="resource" column="resource_id" not-null="false" unique="true" />
<!-- Criterion -->
<class name="Criterion" table="criterion">
<cache usage="nonstrict-read-write"/>
<id name="id" access="property" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property access="field" name="name"/>
<property access="field" name="predefinedCriterionInternalName" not-null="false"
column="predefined_criterion_internal_name" />
<property access="field" name="active"/>
<many-to-one access="field" name="type" lazy="false" column="id_criterion_type" not-null="true" />
<many-to-one access="field" name="costCategory" lazy="false" column="id_cost_category" not-null="false" />
<!-- Indexed the other side -->
<set name="limitingResourceQueueElements" cascade="all-delete-orphan" inverse="true"
sort="org.libreplan.business.resources.entities.LimitingResourceQueueElementComparator">
<key column="limiting_resource_queue_id" not-null="true" />
<one-to-many class="org.libreplan.business.planner.limiting.entities.LimitingResourceQueueElement" />
</set>
<!-- Indexed. It is probable to navigate from a criterion
to its children criteria -->
<many-to-one name="parent" column="parent" access="field" not-null="false"
index="idx_criterion_on_parent"/>
</class>
<!-- Indexed the other side -->
<set name="children" access="field" lazy="false" cascade="save-update">
<key column="parent" not-null="false"></key>
<one-to-many class="Criterion"/>
</set>
<!-- Assess the removal of this mapping. It is not used frequently. It is not
included index in the many-to-one side -->
<set name="criterionRequirements" access="field">
<key column="criterion_id" not-null="false"></key>
<one-to-many class="org.libreplan.business.requirements.entities.CriterionRequirement"/>
</set>
<properties name="nameAndType" unique="true">
<property access="field" name="name" insert="false" update="false"/>
<property access="field" name="typeId" insert="false" update="false"
column="id_criterion_type"/>
</properties>
</class>
<!-- CriterionSatisfaction -->
<class name="CriterionSatisfaction" table="criterion_satisfaction">
<cache usage="read-write"/>
<id name="id" access="property" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property access="field" name="startDate" not-null="true" column="start_date" />
<property access="field" name="finishDate" column="finish_date" />
<property access="field" name="isDeleted" column="is_deleted" />
<!-- Indexed. It is not probable to ask for the criterion satisfactions of a criterion -->
<many-to-one access="field" name="criterion" not-null="true"/>
<!-- Iindexed. It is useful to know the criterion satisfactoions of a resource -->
<many-to-one access="field" name="resource" not-null="true" index="idx_criterion_satisfaction_on_resource" column="resource" />
</class>
<!-- CriterionType -->
<class name="CriterionType" table="criterion_type">
<cache usage="nonstrict-read-write"/>
<id name="id" access="property" type="long">
<generator class="hilo"/>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" unique="true"/>
<property name="predefinedTypeInternalName" not-null="false"
column="predefined_type_internal_name" />
<property name="description"/>
<property name="allowSimultaneousCriterionsPerResource"
column="allow_simultaneous_criterions_per_resource" />
<property name="allowHierarchy"
column="allow_hierarchy" />
<property name="lastCriterionSequenceCode" access="field"
column="last_criterion_sequence_code" />
<property name="enabled"/>
<property name="codeAutogenerated" not-null="true"
column="code_autogenerated" />
<property name="resource">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.resources.entities.ResourceEnum</param>
</type>
</property>
<!-- Indexed the other side-->
<set name="criterions" cascade="all,delete-orphan" inverse="true">
<!-- Criterion -->
<class name="Criterion" table="criterion">
<cache usage="nonstrict-read-write"/>
<key column="id_criterion_type" />
<one-to-many class="Criterion" />
</set>
</class>
<id name="id" access="property" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property access="field" name="name"/>
<property access="field" name="predefinedCriterionInternalName" not-null="false"
column="predefined_criterion_internal_name" />
<property access="field" name="active"/>
<many-to-one access="field" name="type" lazy="false" column="id_criterion_type" not-null="true" />
<many-to-one access="field" name="costCategory" lazy="false" column="id_cost_category" not-null="false" />
<!-- Indexed. It is probable to navigate from a criterion to its children criteria -->
<many-to-one name="parent" column="parent" access="field" not-null="false" index="idx_criterion_on_parent"/>
<!-- Indexed the other side -->
<set name="children" access="field" lazy="false" cascade="save-update">
<key column="parent" not-null="false"/>
<one-to-many class="Criterion"/>
</set>
<!--
Assess the removal of this mapping.
It is not used frequently.
It is not included index in the many-to-one side
-->
<set name="criterionRequirements" access="field">
<key column="criterion_id" not-null="false"/>
<one-to-many class="org.libreplan.business.requirements.entities.CriterionRequirement"/>
</set>
<properties name="nameAndType" unique="true">
<property access="field" name="name" insert="false" update="false"/>
<property access="field" name="typeId" insert="false" update="false" column="id_criterion_type"/>
</properties>
</class>
<!-- CriterionSatisfaction -->
<class name="CriterionSatisfaction" table="criterion_satisfaction">
<cache usage="read-write"/>
<id name="id" access="property" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property access="field" name="startDate" not-null="true" column="start_date" />
<property access="field" name="finishDate" column="finish_date" />
<property access="field" name="isDeleted" column="is_deleted" />
<!-- Indexed. It is not probable to ask for the criterion satisfactions of a criterion -->
<many-to-one access="field" name="criterion" not-null="true"/>
<!-- Indexed. It is useful to know the criterion satisfactions of a resource -->
<many-to-one access="field" name="resource" not-null="true" index="idx_criterion_satisfaction_on_resource"
column="resource" />
</class>
<!-- CriterionType -->
<class name="CriterionType" table="criterion_type">
<cache usage="nonstrict-read-write"/>
<id name="id" access="property" type="long">
<generator class="increment"/>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" unique="true"/>
<property name="predefinedTypeInternalName" not-null="false" column="predefined_type_internal_name" />
<property name="description"/>
<property name="allowSimultaneousCriterionsPerResource" column="allow_simultaneous_criterions_per_resource" />
<property name="allowHierarchy" column="allow_hierarchy" />
<property name="lastCriterionSequenceCode" access="field" column="last_criterion_sequence_code" />
<property name="enabled"/>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="resource">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.resources.entities.ResourceEnum</param>
</type>
</property>
<!-- Indexed the other side-->
<set name="criterions" cascade="all,delete-orphan" inverse="true">
<cache usage="nonstrict-read-write"/>
<key column="id_criterion_type" />
<one-to-many class="Criterion" />
</set>
</class>
<!-- MachineWorkersConfigurationUnit -->
<class name="MachineWorkersConfigurationUnit" table="machine_workers_configuration_unit">
<id name="id" access="property" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property access="field" name="name" not-null="true"/>
<property access="field" name="alpha" not-null="true"/>
<many-to-one access="field" name="machine" class="Machine" not-null="true"/>
<set name="requiredCriterions" table="machine_configuration_unit_required_criterions" inverse="false">
<key column="id" not-null="false" />
<many-to-many class="org.libreplan.business.resources.entities.Criterion" column="criterion_id"/>
</set>
<set inverse="true" name="workerAssignments" cascade="all-delete-orphan">
<key column="configuration_id" />
<one-to-many
class="MachineWorkerAssignment" />
</set>
<!-- MachineWorkersConfigurationUnit -->
<class name="MachineWorkersConfigurationUnit" table="machine_workers_configuration_unit">
<id name="id" access="property" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
</class>
<version name="version" access="property" type="long" />
<!-- MachineWorkerAssignment -->
<class name="MachineWorkerAssignment" table="machine_worker_assignment">
<id name="id" access="property" type="long">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property access="field" name="startDate" column="start_date" />
<property access="field" name="finishDate" column="finish_date" />
<many-to-one access="field" name="machineWorkersConfigurationUnit" class="MachineWorkersConfigurationUnit" column="configuration_id" not-null="true"/>
<many-to-one access="field" name="worker" class="Worker" column="worker_id" />
</class>
<property access="field" name="name" not-null="true"/>
<property access="field" name="alpha" not-null="true"/>
<many-to-one access="field" name="machine" class="Machine" not-null="true"/>
<set name="requiredCriterions" table="machine_configuration_unit_required_criterions" inverse="false">
<key column="id" not-null="false" />
<many-to-many class="org.libreplan.business.resources.entities.Criterion" column="criterion_id"/>
</set>
<set inverse="true" name="workerAssignments" cascade="all-delete-orphan">
<key column="configuration_id" />
<one-to-many class="MachineWorkerAssignment" />
</set>
</class>
<!-- MachineWorkerAssignment -->
<class name="MachineWorkerAssignment" table="machine_worker_assignment">
<id name="id" access="property" type="long">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property access="field" name="startDate" column="start_date" />
<property access="field" name="finishDate" column="finish_date" />
<many-to-one access="field" name="machineWorkersConfigurationUnit" class="MachineWorkersConfigurationUnit"
column="configuration_id" not-null="true"/>
<many-to-one access="field" name="worker" class="Worker" column="worker_id" />
</class>
</hibernate-mapping>

View file

@ -1,21 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.scenarios.entities"
default-access="field">
<!-- Scenario -->
<class name="Scenario" table="scenario">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="name" />
<property name="description" />
<property name="lastNotOwnedReassignationsTimeStamp"
column="last_not_owned_reassignations_time_stamp" />
<property name="lastNotOwnedReassignationsTimeStamp" column="last_not_owned_reassignations_time_stamp" />
<map name="orders" table="scenario_orders" lazy="false" cascade="save-update">
<key column="scenario_id" />
@ -31,13 +34,15 @@
<!-- OrderVersion -->
<class name="OrderVersion" table="order_version">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="modificationByOwnerTimestamp"
column="modification_by_owner_timestamp" />
<property name="modificationByOwnerTimestamp" column="modification_by_owner_timestamp" />
<many-to-one name="ownerScenario" class="Scenario" />
</class>

View file

@ -1,22 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.templates.entities" default-access="field">
<class name="OrderElementTemplate" abstract="true" table="order_element_template">
<id name="id" access="property" type="long">
<generator class="hilo" >
<generator class="increment" >
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<component name="infoComponent" class="org.libreplan.business.orders.entities.InfoComponent">
<property name="name" access="field" />
<property name="description" access="field" type="text" />
</component>
<property name="startAsDaysFromBeginning"
column="start_as_days_from_beginning" />
<property name="deadlineAsDaysFromBeginning"
column="deadline_as_days_from_beginning" />
<property name="startAsDaysFromBeginning" column="start_as_days_from_beginning" />
<property name="deadlineAsDaysFromBeginning" column="deadline_as_days_from_beginning" />
<property name="schedulingStateType" access="field" column="scheduling_state_type">
<type name="org.hibernate.type.EnumType">
@ -25,10 +29,9 @@
</property>
<!-- Indexed -->
<many-to-one name="parent"
access="field"
class="org.libreplan.business.templates.entities.OrderLineGroupTemplate"
index="idx_order_element_template_on_parent"/>
<many-to-one name="parent" access="field"
class="org.libreplan.business.templates.entities.OrderLineGroupTemplate"
index="idx_order_element_template_on_parent"/>
<!-- Indexed the other side -->
<set name="criterionRequirements" cascade="all-delete-orphan" inverse="true">
@ -59,19 +62,21 @@
</set>
<joined-subclass name="OrderLineGroupTemplate" table="order_line_group_template">
<key column="group_template_id"></key>
<key column="group_template_id"/>
<list name="children" access="field" cascade="all">
<key column="parent" not-null="false"></key>
<index column="position_in_container"></index>
<key column="parent" not-null="false"/>
<index column="position_in_container"/>
<!-- Indexed the other side -->
<one-to-many class="OrderElementTemplate" />
</list>
<joined-subclass name="OrderTemplate" table="order_template">
<key column="order_template_id"></key>
<key column="order_template_id"/>
<!-- Not indexed -->
<many-to-one name="calendar" column="base_calendar_id" cascade="none"
class="org.libreplan.business.calendars.entities.BaseCalendar"/>
class="org.libreplan.business.calendars.entities.BaseCalendar"/>
</joined-subclass>
</joined-subclass>
@ -84,8 +89,7 @@
<one-to-many class="org.libreplan.business.orders.entities.HoursGroup" />
</set>
<property name="lastHoursGroupSequenceCode" access="field"
column="last_hours_group_sequence_code" />
<property name="lastHoursGroupSequenceCode" access="field" column="last_hours_group_sequence_code" />
<property name="budget" scale="2" access="field" />
</joined-subclass>

View file

@ -1,42 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.users.entities"
default-access="field">
<!--
IMPORTANT: The default name for User's table ("User") is not valid
for some databases (e.g. PostgreSQL).
-->
<hibernate-mapping package="org.libreplan.business.users.entities" default-access="field">
<!-- IMPORTANT: The default name for User's table ("User") is not valid for some databases (e.g. PostgreSQL). -->
<class name="User" table="user_table">
<!--
IMPORTANT: type="long" must be specified (otherwise,
Hibernate infers type="integer".
-->
<!-- IMPORTANT: type="long" must be specified (otherwise, Hibernate infers type="integer"). -->
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="loginName" not-null="true" unique="true" column="login_name" />
<property name="password" />
<property name="email"/>
<property name="disabled"/>
<property name="librePlanUser" column="libreplan_user" not-null="true"/>
<property name="applicationLanguage" column="application_language">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.settings.entities.Language</param>
</type>
</property>
<property name="expandCompanyPlanningViewCharts" not-null="true"
column="expand_company_planning_view_charts" />
<property name="expandOrderPlanningViewCharts" not-null="true"
column="expand_order_planning_view_charts" />
<property name="expandResourceLoadViewCharts" not-null="true"
column="expand_resource_load_view_charts" />
<property name="expandCompanyPlanningViewCharts" not-null="true" column="expand_company_planning_view_charts" />
<property name="expandOrderPlanningViewCharts" not-null="true" column="expand_order_planning_view_charts" />
<property name="expandResourceLoadViewCharts" not-null="true" column="expand_resource_load_view_charts" />
<property name="firstName" column="first_name"/>
<property name="lastName" column="last_name"/>
<!-- Index created in a database-object section -->
@ -45,8 +47,7 @@
<element column="role">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.users.entities.UserRole</param>
<!-- 12 is java.sql.Types.VARCHAR -->
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</element>
</set>
@ -54,14 +55,12 @@
<!-- Index created in a database-object section -->
<set name="profiles" table="user_profiles">
<key column="user_id"/>
<many-to-many column="profile_id"
class="org.libreplan.business.users.entities.Profile"/>
<many-to-many column="profile_id" class="org.libreplan.business.users.entities.Profile"/>
</set>
<many-to-one name="lastConnectedScenario"
class="org.libreplan.business.scenarios.entities.Scenario" />
<one-to-one name="worker" property-ref="user"
class="org.libreplan.business.resources.entities.Worker" />
<many-to-one name="lastConnectedScenario" class="org.libreplan.business.scenarios.entities.Scenario" />
<one-to-one name="worker" property-ref="user" class="org.libreplan.business.resources.entities.Worker" />
<property name="projectsFilterPeriodSince" column="projects_filter_period_since"/>
@ -71,24 +70,23 @@
<property name="resourcesLoadFilterPeriodTo" column="resources_load_filter_period_to"/>
<many-to-one name="projectsFilterLabel" cascade="none" lazy="false"
column="projects_filter_label_id" />
<many-to-one name="projectsFilterLabel" cascade="none" lazy="false" column="projects_filter_label_id" />
<many-to-one name="resourcesLoadFilterCriterion" cascade="none"
lazy="false" column="resources_load_filter_criterion_id" />
<many-to-one name="resourcesLoadFilterCriterion" cascade="none" lazy="false"
column="resources_load_filter_criterion_id" />
</class>
<class name="Profile" table="profile_table">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="profileName" not-null="true" unique="true"
column="profile_name" />
<property name="profileName" not-null="true" unique="true" column="profile_name" />
<!-- Index created in a database-object section -->
<set name="roles" table="profile_roles">
@ -96,8 +94,7 @@
<element column="role">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.users.entities.UserRole</param>
<!-- 12 is java.sql.Types.VARCHAR -->
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</element>
</set>
@ -105,7 +102,7 @@
<class name="OrderAuthorization" table="order_authorization">
<id name="id" access="property" type="long">
<generator class="hilo">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
@ -117,8 +114,7 @@
<property name="authorizationType" not-null="true" column="authorization_type">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.users.entities.OrderAuthorizationType</param>
<!-- 12 is java.sql.Types.VARCHAR -->
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</property>
@ -138,24 +134,23 @@
<database-object>
<create>CREATE INDEX idx_user_on_user_roles ON user_roles (user_id)</create>
<drop>DROP INDEX idx_user_on_user_roles</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
<!-- Index to boost the search of roles inside profiles -->
<database-object>
<create>CREATE INDEX idx_profile_on_profile_roles ON profile_roles (profile_id)</create>
<drop>DROP INDEX idx_profile_on_profile_roles</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
<!-- Index to boost the search of profiles inside users -->
<database-object>
<create>CREATE INDEX idx_user_on_user_profiles ON user_profiles (user_id)</create>
<drop>DROP INDEX idx_user_on_user_profiles</drop>
<dialect-scope name="org.hibernate.dialect.PostgreSQLDialect" />
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect" />
<dialect-scope name="org.hibernate.dialect.PostgreSQL9Dialect" />
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
</hibernate-mapping>

View file

@ -1,191 +1,192 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.libreplan.business.workreports.entities" default-access="field">
<!-- WorkReportType -->
<class name="WorkReportType" table="work_report_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- WorkReportType -->
<class name="WorkReportType" table="work_report_type">
<cache usage="nonstrict-read-write"/>
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="name" access="field" unique="true"/>
<property name="code" access="field" unique="true"/>
<property name="dateIsSharedByLines" access="field"
column="date_is_shared_by_lines" />
<property name="resourceIsSharedInLines" access="field"
column="resource_is_shared_in_lines" />
<property name="orderElementIsSharedInLines" access="field"
column="order_element_is_shared_in_lines" />
<property name="codeAutogenerated" access="field" not-null="true"
column="code_autogenerated" />
<property name="name" access="field" unique="true"/>
<property name="hoursManagement" column="hours_management">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.workreports.entities.HoursManagementEnum</param>
</type>
</property>
<property name="code" access="field" unique="true"/>
<!-- Not indexed -->
<set name="workReportLabelTypeAssigments" cascade="all-delete-orphan" batch-size="10">
<key column="work_report_type_id"/>
<one-to-many class="WorkReportLabelTypeAssigment"/>
</set>
<property name="dateIsSharedByLines" access="field" column="date_is_shared_by_lines" />
<!-- Not indexed -->
<set name="headingFields" table="heading_field" batch-size="10">
<key column="heading_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionField">
<property name="resourceIsSharedInLines" access="field" column="resource_is_shared_in_lines" />
<property name="orderElementIsSharedInLines" access="field" column="order_element_is_shared_in_lines" />
<property name="codeAutogenerated" access="field" not-null="true" column="code_autogenerated" />
<property name="hoursManagement" column="hours_management">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.libreplan.business.workreports.entities.HoursManagementEnum</param>
</type>
</property>
<!-- Not indexed -->
<set name="workReportLabelTypeAssigments" cascade="all-delete-orphan" batch-size="10">
<key column="work_report_type_id"/>
<one-to-many class="WorkReportLabelTypeAssigment"/>
</set>
<!-- Not indexed -->
<set name="headingFields" table="heading_field" batch-size="10">
<key column="heading_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionField">
<property name="fieldName"/>
<property name="length"/>
<property name="positionNumber"/>
</composite-element>
</set>
</composite-element>
</set>
<!-- Not indexed -->
<set name="lineFields" table="line_field" batch-size="10">
<key column="heading_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionField">
<!-- Not indexed -->
<set name="lineFields" table="line_field" batch-size="10">
<key column="heading_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionField">
<property name="fieldName"/>
<property name="length"/>
<property name="positionNumber"/>
</composite-element>
</set>
</composite-element>
</set>
</class>
</class>
<!-- WorkReport -->
<class name="WorkReport" table="work_report">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- WorkReport -->
<class name="WorkReport" table="work_report">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="code" access="property" not-null="true" unique="true"/>
<property name="date"/>
<property name="date"/>
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="codeAutogenerated" not-null="true" column="code_autogenerated" />
<property name="lastWorkReportLineSequenceCode" access="field" column="last_work_report_line_sequence_code" />
<property name="lastWorkReportLineSequenceCode" access="field" column="last_work_report_line_sequence_code" />
<!-- Not indexed -->
<many-to-one name="workReportType" class="WorkReportType" column="ork_report_type_id" not-null="true"/>
<!-- Not indexed -->
<many-to-one name="workReportType" class="WorkReportType" column="ork_report_type_id" not-null="true"/>
<!-- Indexed -->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource" column="resource_id"
index="idx_resource_on_work_report" />
<!-- Indexed -->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource" column="resource_id"
index="idx_resource_on_work_report" />
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id" index="idx_order_element_on_work_report" />
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id" index="idx_order_element_on_work_report" />
<!-- Not indexed -->
<set name="labels" table="workreports_labels" batch-size="10">
<key column="work_report_id"/>
<many-to-many column="label_id"
class="org.libreplan.business.labels.entities.Label"/>
</set>
<!-- Not indexed -->
<set name="labels" table="workreports_labels" batch-size="10">
<key column="work_report_id"/>
<many-to-many column="label_id"
class="org.libreplan.business.labels.entities.Label"/>
</set>
<!-- Indexed on the other side -->
<set name="workReportLines" cascade="all-delete-orphan" inverse="true" batch-size="10" fetch="join">
<key column="work_report_id"/>
<one-to-many class="WorkReportLine"/>
</set>
<!-- Indexed on the other side -->
<set name="workReportLines" cascade="all-delete-orphan" inverse="true" batch-size="10" lazy="false">
<key column="work_report_id"/>
<one-to-many class="WorkReportLine"/>
</set>
<!-- Not indexed -->
<set name="descriptionValues" table="description_values" batch-size="10">
<key column="description_value_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionValue">
<!-- Not indexed -->
<set name="descriptionValues" table="description_values" batch-size="10">
<key column="description_value_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionValue">
<property name="fieldName"/>
<property name="value"/>
</composite-element>
</set>
</class>
</composite-element>
</set>
</class>
<!-- WorkReportLine -->
<class name="WorkReportLine" table="work_report_line">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<!-- WorkReportLine -->
<class name="WorkReportLine" table="work_report_line">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="code" access="property" not-null="true" unique="true"/>
<version name="version" access="property" type="long" />
<property name="effort" access="field" column="effort" type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
<property name="date" access="field"/>
<property name="clockStart" access="field"
type="org.jadira.usertype.dateandtime.joda.PersistentLocalTimeAsMillisInteger"
column="clock_start" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="clockFinish" access="field"
type="org.jadira.usertype.dateandtime.joda.PersistentLocalTimeAsMillisInteger"
column="clock_finish" />
<property name="effort" access="field" column="effort"
type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
<!-- Indexed -->
<many-to-one name="workReport" class="org.libreplan.business.workreports.entities.WorkReport"
column="work_report_id"
index="idx_work_report_on_work_report_line" />
<property name="date" access="field"/>
<!-- Indexed -->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource"
column="resource_id" not-null="true"
index="idx_resource_on_work_report_line" />
<property name="clockStart" access="field"
type="org.jadira.usertype.dateandtime.joda.PersistentLocalTimeAsMillisInteger" column="clock_start" />
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id" not-null="true"
index="idx_order_element_on_work_report_line" />
<property name="clockFinish" access="field"
type="org.jadira.usertype.dateandtime.joda.PersistentLocalTimeAsMillisInteger" column="clock_finish" />
<!-- Indexed -->
<many-to-one name="typeOfWorkHours" class="org.libreplan.business.costcategories.entities.TypeOfWorkHours"
column="type_work_hours_id" not-null="true"
index="idx_type_of_work_hours_on_work_report_line" />
<!-- Indexed -->
<many-to-one name="workReport" class="org.libreplan.business.workreports.entities.WorkReport"
column="work_report_id" index="idx_work_report_on_work_report_line" />
<!-- Not indexed -->
<set name="labels" table="workreportslines_labels" batch-size="10">
<key column="work_report_line_id"/>
<many-to-many column="label_id"
class="org.libreplan.business.labels.entities.Label"/>
</set>
<!-- Indexed -->
<many-to-one name="resource" class="org.libreplan.business.resources.entities.Resource"
column="resource_id" not-null="true" index="idx_resource_on_work_report_line" />
<!-- Not indexed -->
<set name="descriptionValues" table="description_values_in_line" batch-size="10">
<key column="description_value_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionValue">
<!-- Indexed -->
<many-to-one name="orderElement" class="org.libreplan.business.orders.entities.OrderElement"
column="order_element_id" not-null="true" index="idx_order_element_on_work_report_line" />
<!-- Indexed -->
<many-to-one name="typeOfWorkHours" class="org.libreplan.business.costcategories.entities.TypeOfWorkHours"
column="type_work_hours_id" not-null="true" index="idx_type_of_work_hours_on_work_report_line" />
<!-- Not indexed -->
<set name="labels" table="workreportslines_labels" batch-size="10">
<key column="work_report_line_id"/>
<many-to-many column="label_id"
class="org.libreplan.business.labels.entities.Label"/>
</set>
<!-- Not indexed -->
<set name="descriptionValues" table="description_values_in_line" batch-size="10">
<key column="description_value_id"/>
<composite-element class="org.libreplan.business.workreports.valueobjects.DescriptionValue">
<property name="fieldName" column="field_name" />
<property name="value"/>
</composite-element>
</set>
</composite-element>
</set>
<property name="finished" />
<property name="finished" />
</class>
</class>
<class name="WorkReportLabelTypeAssigment" table="work_report_label_type_assigment">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<class name="WorkReportLabelTypeAssigment" table="work_report_label_type_assigment">
<id name="id" type="long" access="property">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="labelsSharedByLines" column="labels_shared_by_lines" />
<property name="positionNumber" column="position_number" />
<property name="labelsSharedByLines" column="labels_shared_by_lines" />
<property name="positionNumber" column="position_number" />
<!-- Not indexed -->
<many-to-one name="labelType" class="org.libreplan.business.labels.entities.LabelType" column="label_type_id" />
<!-- Not indexed -->
<many-to-one name="labelType" class="org.libreplan.business.labels.entities.LabelType" column="label_type_id" />
<!-- Not indexed -->
<many-to-one name="defaultLabel" class="org.libreplan.business.labels.entities.Label" column="label_id" />
<!-- Not indexed -->
<many-to-one name="defaultLabel" class="org.libreplan.business.labels.entities.Label" column="label_id" />
</class>
</class>
</hibernate-mapping>

View file

@ -37,7 +37,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
@ContextConfiguration(locations = {
BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
public class AdvanceTypeTest {
@ -48,10 +49,11 @@ public class AdvanceTypeTest {
@Transactional
public void typeNameMustBeUniqueInDB() {
String repeatedName = "bla";
AdvanceType advanceType = AdvanceType.create(repeatedName, new BigDecimal(
5), false, new BigDecimal(1), true, false);
AdvanceType other = AdvanceType.create(repeatedName, new BigDecimal(4),
false, new BigDecimal(2), true, false);
AdvanceType advanceType =
AdvanceType.create(repeatedName, new BigDecimal(5), false, new BigDecimal(1), true, false);
AdvanceType other = AdvanceType.create(repeatedName, new BigDecimal(4), false, new BigDecimal(2), true, false);
dao.save(advanceType);
dao.save(other);
dao.flush();

View file

@ -88,9 +88,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
@ContextConfiguration(locations = {
BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
/*
/**
* @author Diego Pino García <dpino@igalia.com>
*/
public class OrderElementDAOTest {
@ -143,6 +144,7 @@ public class OrderElementDAOTest {
private OrderLine createValidOrderLine() {
String unique = UUID.randomUUID().toString();
return createValidOrderLine(unique, unique);
}
@ -150,11 +152,13 @@ public class OrderElementDAOTest {
Order order = createValidOrder();
OrderLine orderLine = createStandAloneLine(name, code);
order.add(orderLine);
return orderLine;
}
private OrderLine createStandAloneLine() {
String uniqueCode = UUID.randomUUID().toString();
return createStandAloneLine(uniqueCode, uniqueCode);
}
@ -162,13 +166,14 @@ public class OrderElementDAOTest {
OrderLine orderLine = OrderLine.create();
orderLine.setName(name);
orderLine.setCode(code);
return orderLine;
}
private OrderLineGroup createValidOrderLineGroup() {
String unique = UUID.randomUUID().toString();
OrderLineGroup result = createValidOrderLineGroup(unique, unique);
return result;
return createValidOrderLineGroup(unique, unique);
}
private OrderLineGroup createValidOrderLineGroup(String name, String code) {
@ -181,6 +186,7 @@ public class OrderElementDAOTest {
orderLineGroup.add(line);
line.setName(UUID.randomUUID().toString());
line.setCode(UUID.randomUUID().toString());
return orderLineGroup;
}
@ -192,11 +198,11 @@ public class OrderElementDAOTest {
BaseCalendar basicCalendar = BaseCalendarTest.createBasicCalendar();
calendarDAO.save(basicCalendar);
order.setCalendar(basicCalendar);
OrderVersion orderVersion = ResourceAllocationDAOTest
.setupVersionUsing(scenarioManager, order);
OrderVersion orderVersion = ResourceAllocationDAOTest.setupVersionUsing(scenarioManager, order);
orderElementDAO.save(order);
orderElementDAO.flush();
order.useSchedulingDataFor(orderVersion);
return order;
}
@ -213,36 +219,31 @@ public class OrderElementDAOTest {
public void testFindUniqueByCode() throws InstanceNotFoundException {
OrderLine orderLine = createValidOrderLine();
orderElementDAO.save(orderLine);
orderLine.setCode(((Long) orderLine.getId()).toString());
orderLine.setCode(orderLine.getId().toString());
orderElementDAO.save(orderLine);
OrderLine found = (OrderLine) orderElementDAO
.findUniqueByCode(orderLine
.getCode());
OrderLine found = (OrderLine) orderElementDAO.findUniqueByCode(orderLine.getCode());
assertTrue(found != null && found.getCode().equals(orderLine.getCode()));
}
@Test
@Transactional
public void testFindUniqueByCodeAndOrderLineGroup()
throws InstanceNotFoundException {
public void testFindUniqueByCodeAndOrderLineGroup() throws InstanceNotFoundException {
// Create OrderLineGroupLine
OrderLineGroup orderLineGroup = createValidOrderLineGroup();
orderElementDAO.save(orderLineGroup.getOrder());
orderElementDAO.flush();
orderLineGroup.setCode(((Long) orderLineGroup.getId()).toString());
orderLineGroup.setCode(orderLineGroup.getId().toString());
orderElementDAO.save(orderLineGroup.getOrder());
// Create OrderLineGroup
OrderLine orderLine = createStandAloneLine();
orderElementDAO.save(orderLine);
orderLine.setCode(((Long) orderLine.getId()).toString());
orderLine.setCode(orderLine.getId().toString());
orderLineGroup.add(orderLine);
OrderLine found = (OrderLine) orderElementDAO
.findUniqueByCodeAndParent(
orderLineGroup, orderLine.getCode());
OrderLine found = (OrderLine) orderElementDAO.findUniqueByCodeAndParent(orderLineGroup, orderLine.getCode());
assertTrue(found != null && found.getCode().equals(orderLine.getCode()));
}
@ -252,8 +253,7 @@ public class OrderElementDAOTest {
// Create OrderLineGroupLine
Order order = createValidOrder();
List<OrderElement> list = orderElementDAO.findByCodeAndParent(null,
order.getCode());
List<OrderElement> list = orderElementDAO.findByCodeAndParent(null, order.getCode());
assertFalse(list.isEmpty());
}
@ -263,11 +263,11 @@ public class OrderElementDAOTest {
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException,
InstanceNotFoundException {
OrderLine orderLine = createValidOrderLine();
OrderElementTest.addAvanceAssignmentWithMeasurement(orderLine,
PredefinedAdvancedTypes.UNITS.getType(), new BigDecimal(1000),
new BigDecimal(400), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(
orderLine, PredefinedAdvancedTypes.UNITS.getType(), new BigDecimal(1000), new BigDecimal(400), true);
orderElementDAO.save(orderLine);
orderElementDAO.flush();
@ -278,12 +278,12 @@ public class OrderElementDAOTest {
Set<DirectAdvanceAssignment> directAdvanceAssignments = found.getDirectAdvanceAssignments();
assertThat(directAdvanceAssignments.size(), equalTo(1));
SortedSet<AdvanceMeasurement> advanceMeasurements = directAdvanceAssignments
.iterator().next().getAdvanceMeasurements();
SortedSet<AdvanceMeasurement> advanceMeasurements =
directAdvanceAssignments.iterator().next().getAdvanceMeasurements();
assertThat(advanceMeasurements.size(), equalTo(1));
assertThat(advanceMeasurements.iterator().next().getValue(),
equalTo(new BigDecimal(400)));
assertThat(advanceMeasurements.iterator().next().getValue(), equalTo(new BigDecimal(400)));
}
@Test
@ -292,33 +292,28 @@ public class OrderElementDAOTest {
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException,
InstanceNotFoundException {
Order order = createValidOrder();
OrderVersion orderVersion = order.getOrderVersionFor(scenarioManager
.getCurrent());
OrderElement orderElement = OrderElementTest
.givenOrderLineGroupWithTwoOrderLines(orderVersion,
2000, 3000);
OrderVersion orderVersion = order.getOrderVersionFor(scenarioManager.getCurrent());
OrderElement orderElement = OrderElementTest.givenOrderLineGroupWithTwoOrderLines(orderVersion, 2000, 3000);
order.add(orderElement);
List<OrderElement> children = orderElement.getChildren();
AdvanceType advanceType = PredefinedAdvancedTypes.UNITS.getType();
OrderElementTest.addAvanceAssignmentWithMeasurement(children.get(0),
advanceType,
new BigDecimal(1000), new BigDecimal(100), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(
children.get(0), advanceType, new BigDecimal(1000), new BigDecimal(100), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(children.get(1),
advanceType,
new BigDecimal(1000), new BigDecimal(300), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(
children.get(1), advanceType, new BigDecimal(1000), new BigDecimal(300), true);
orderElementDAO.save(orderElement);
orderElementDAO.flush();
assertTrue(orderElementDAO.exists(orderElement.getId()));
OrderLineGroup found = (OrderLineGroup) orderElementDAO
.find(orderElement.getId());
OrderLineGroup found = (OrderLineGroup) orderElementDAO.find(orderElement.getId());
assertThat(found.getDirectAdvanceAssignments().size(), equalTo(0));
assertThat(found.getIndirectAdvanceAssignments().size(), equalTo(2));
@ -326,15 +321,12 @@ public class OrderElementDAOTest {
Set<DirectAdvanceAssignment> directAdvanceAssignments = found.getChildren().get(0).getDirectAdvanceAssignments();
assertThat(directAdvanceAssignments.size(), equalTo(1));
DirectAdvanceAssignment directAdvanceAssignment = directAdvanceAssignments
.iterator().next();
assertThat(directAdvanceAssignment.getMaxValue(),
equalTo(new BigDecimal(1000)));
DirectAdvanceAssignment directAdvanceAssignment = directAdvanceAssignments.iterator().next();
assertThat(directAdvanceAssignment.getMaxValue(), equalTo(new BigDecimal(1000)));
SortedSet<AdvanceMeasurement> advanceMeasurements = directAdvanceAssignment.getAdvanceMeasurements();
assertThat(advanceMeasurements.size(), equalTo(1));
assertThat(advanceMeasurements.iterator().next().getValue(),
equalTo(new BigDecimal(100)));
assertThat(advanceMeasurements.iterator().next().getValue(), equalTo(new BigDecimal(100)));
}
@Test
@ -343,11 +335,11 @@ public class OrderElementDAOTest {
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException,
InstanceNotFoundException {
OrderLine orderLine = createValidOrderLine();
OrderElementTest.addAvanceAssignmentWithMeasurement(orderLine,
PredefinedAdvancedTypes.UNITS.getType(), new BigDecimal(1000),
new BigDecimal(400), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(
orderLine, PredefinedAdvancedTypes.UNITS.getType(), new BigDecimal(1000), new BigDecimal(400), true);
orderElementDAO.save(orderLine);
orderElementDAO.flush();
@ -373,24 +365,22 @@ public class OrderElementDAOTest {
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException,
InstanceNotFoundException {
Order order = createValidOrder();
OrderVersion orderVersion = order.getOrderVersionFor(scenarioManager
.getCurrent());
OrderElement orderElement = OrderElementTest
.givenOrderLineGroupWithTwoOrderLines(orderVersion, 2000, 3000);
OrderVersion orderVersion = order.getOrderVersionFor(scenarioManager.getCurrent());
OrderElement orderElement = OrderElementTest.givenOrderLineGroupWithTwoOrderLines(orderVersion, 2000, 3000);
order.add(orderElement);
order.useSchedulingDataFor(order.getOrderVersionFor(scenarioManager
.getCurrent()));
order.useSchedulingDataFor(order.getOrderVersionFor(scenarioManager.getCurrent()));
List<OrderElement> children = orderElement.getChildren();
AdvanceType advanceType = PredefinedAdvancedTypes.UNITS.getType();
OrderElementTest.addAvanceAssignmentWithMeasurement(children.get(0),
advanceType, new BigDecimal(1000), new BigDecimal(100), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(
children.get(0), advanceType, new BigDecimal(1000), new BigDecimal(100), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(children.get(1),
advanceType, new BigDecimal(1000), new BigDecimal(300), true);
OrderElementTest.addAvanceAssignmentWithMeasurement(
children.get(1), advanceType, new BigDecimal(1000), new BigDecimal(300), true);
orderElementDAO.save(orderElement);
orderElementDAO.flush();
@ -403,23 +393,20 @@ public class OrderElementDAOTest {
orderElementDAO.flush();
try {
found = (OrderLineGroup) orderElementDAO.find(id);
orderElementDAO.find(id);
fail("It should throw an exception");
} catch (InstanceNotFoundException e) {
// ok
// OK
}
}
@Test
@Transactional
public void testSaveAndRemoveTaskQualityForm() {
OrderElement orderElement = OrderElementTest
.givenOrderLineGroupWithTwoOrderLines(2000, 3000);
QualityForm qualityForm = QualityForm.create(UUID.randomUUID()
.toString(), UUID.randomUUID().toString());
OrderElement orderElement = OrderElementTest.givenOrderLineGroupWithTwoOrderLines(2000, 3000);
QualityForm qualityForm = QualityForm.create(UUID.randomUUID().toString(), UUID.randomUUID().toString());
TaskQualityForm taskQualityForm = orderElement
.addTaskQualityForm(qualityForm);
TaskQualityForm taskQualityForm = orderElement.addTaskQualityForm(qualityForm);
assertThat(orderElement.getTaskQualityForms().size(), equalTo(1));
orderElement.removeTaskQualityForm(taskQualityForm);
@ -439,14 +426,14 @@ public class OrderElementDAOTest {
orderElement.addTaskQualityForm(null);
fail("It should throw an exception");
} catch (NullPointerException e) {
// ok
// OK
}
try {
orderElement.addTaskQualityForm(qualityForm);
fail("It should throw an exception");
} catch (ValidationException e) {
// ok
// OK
}
}
@ -456,20 +443,16 @@ public class OrderElementDAOTest {
OrderLine orderLine = createValidOrderLine();
orderLine.setSumChargedEffort(SumChargedEffort.create(orderLine));
orderLine.getSumChargedEffort().addDirectChargedEffort(
EffortDuration.hours(8));
orderLine.getSumChargedEffort().addIndirectChargedEffort(
EffortDuration.hours(10));
orderLine.getSumChargedEffort().addDirectChargedEffort(EffortDuration.hours(8));
orderLine.getSumChargedEffort().addIndirectChargedEffort(EffortDuration.hours(10));
orderElementDAO.save(orderLine);
OrderElement orderLineCopy = orderElementDAO.find(orderLine.getId());
assertEquals(orderLine.getSumChargedEffort().getId(),
orderLineCopy.getSumChargedEffort().getId());
assertEquals(orderLine.getSumChargedEffort().getId(), orderLineCopy.getSumChargedEffort().getId());
assertEquals(orderLineCopy.getSumChargedEffort()
.getTotalChargedEffort(), EffortDuration.hours(18));
assertEquals(orderLineCopy.getSumChargedEffort().getTotalChargedEffort(), EffortDuration.hours(18));
}
private Label givenStoredLabel() {
@ -496,8 +479,7 @@ public class OrderElementDAOTest {
OrderLine orderLine3 = createValidOrderLine();
orderElementDAO.save(orderLine3);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(Collections.singleton(label), null);
List<OrderElement> orderELements = orderElementDAO.findByLabelsAndCriteria(Collections.singleton(label), null);
assertEquals(1, orderELements.size());
assertEquals(orderLine1.getId(), orderELements.get(0).getId());
@ -513,27 +495,26 @@ public class OrderElementDAOTest {
orderLine1.addLabel(label1);
orderLine1.addLabel(label2);
orderElementDAO.save(orderLine1);
OrderLine orderLine2 = createValidOrderLine();
orderElementDAO.save(orderLine2);
OrderLine orderLine3 = createValidOrderLine();
orderLine3.addLabel(label2);
orderElementDAO.save(orderLine3);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(Collections.singleton(label1), null);
List<OrderElement> orderELements = orderElementDAO.findByLabelsAndCriteria(Collections.singleton(label1), null);
assertEquals(1, orderELements.size());
assertEquals(orderLine1.getId(), orderELements.get(0).getId());
orderELements = orderElementDAO.findByLabelsAndCriteria(
Collections.singleton(label2), null);
orderELements = orderElementDAO.findByLabelsAndCriteria(Collections.singleton(label2), null);
assertEquals(2, orderELements.size());
for (OrderElement each : orderELements) {
assertTrue(each.getId().equals(orderLine1.getId())
|| each.getId().equals(orderLine3.getId()));
assertTrue(each.getId().equals(orderLine1.getId()) || each.getId().equals(orderLine3.getId()));
}
orderELements = orderElementDAO.findByLabelsAndCriteria(
new HashSet<Label>(Arrays.asList(label1, label2)), null);
orderELements = orderElementDAO.findByLabelsAndCriteria(new HashSet<>(Arrays.asList(label1, label2)), null);
assertEquals(1, orderELements.size());
assertEquals(orderLine1.getId(), orderELements.get(0).getId());
}
@ -550,18 +531,15 @@ public class OrderElementDAOTest {
child.addLabel(label2);
orderElementDAO.save(orderLineGroup);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(Collections.singleton(label1), null);
List<OrderElement> orderELements = orderElementDAO.findByLabelsAndCriteria(Collections.singleton(label1), null);
assertEquals(1, orderELements.size());
assertEquals(orderLineGroup.getId(), orderELements.get(0).getId());
orderELements = orderElementDAO.findByLabelsAndCriteria(
Collections.singleton(label2), null);
orderELements = orderElementDAO.findByLabelsAndCriteria(Collections.singleton(label2), null);
assertEquals(1, orderELements.size());
assertEquals(child.getId(), orderELements.get(0).getId());
orderELements = orderElementDAO.findByLabelsAndCriteria(
new HashSet<Label>(Arrays.asList(label1, label2)), null);
orderELements = orderElementDAO.findByLabelsAndCriteria(new HashSet<>(Arrays.asList(label1, label2)), null);
assertEquals(0, orderELements.size());
}
@ -585,16 +563,15 @@ public class OrderElementDAOTest {
Criterion criterion = givenStoredCriterion();
OrderLine orderLine1 = createValidOrderLine();
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(
criterion));
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(criterion));
orderElementDAO.save(orderLine1);
OrderLine orderLine2 = createValidOrderLine();
orderElementDAO.save(orderLine2);
OrderLine orderLine3 = createValidOrderLine();
orderElementDAO.save(orderLine3);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(null, Collections.singleton(criterion));
List<OrderElement> orderELements =
orderElementDAO.findByLabelsAndCriteria(null, Collections.singleton(criterion));
assertEquals(1, orderELements.size());
assertEquals(orderLine1.getId(), orderELements.get(0).getId());
@ -607,33 +584,33 @@ public class OrderElementDAOTest {
Criterion criterion2 = givenStoredCriterion();
OrderLine orderLine1 = createValidOrderLine();
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(
criterion1));
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(
criterion2));
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(criterion1));
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(criterion2));
orderElementDAO.save(orderLine1);
OrderLine orderLine2 = createValidOrderLine();
orderElementDAO.save(orderLine2);
OrderLine orderLine3 = createValidOrderLine();
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(
criterion2));
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(criterion2));
orderElementDAO.save(orderLine3);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(null, Collections.singleton(criterion1));
List<OrderElement> orderELements =
orderElementDAO.findByLabelsAndCriteria(null, Collections.singleton(criterion1));
assertEquals(1, orderELements.size());
assertEquals(orderLine1.getId(), orderELements.get(0).getId());
orderELements = orderElementDAO.findByLabelsAndCriteria(null,
Collections.singleton(criterion2));
orderELements = orderElementDAO.findByLabelsAndCriteria(null, Collections.singleton(criterion2));
assertEquals(2, orderELements.size());
for (OrderElement each : orderELements) {
assertTrue(each.getId().equals(orderLine1.getId())
|| each.getId().equals(orderLine3.getId()));
assertTrue(each.getId().equals(orderLine1.getId()) || each.getId().equals(orderLine3.getId()));
}
orderELements = orderElementDAO.findByLabelsAndCriteria(null,
new HashSet<Criterion>(Arrays.asList(criterion1, criterion2)));
orderELements =
orderElementDAO.findByLabelsAndCriteria(null, new HashSet<>(Arrays.asList(criterion1, criterion2)));
assertEquals(1, orderELements.size());
assertEquals(orderLine1.getId(), orderELements.get(0).getId());
@ -646,25 +623,24 @@ public class OrderElementDAOTest {
Criterion criterion2 = givenStoredCriterion();
OrderLineGroup orderLineGroup = createValidOrderLineGroup();
orderLineGroup.addCriterionRequirement(new DirectCriterionRequirement(
criterion1));
orderLineGroup.addCriterionRequirement(new DirectCriterionRequirement(criterion1));
OrderElement child = orderLineGroup.getChildren().get(0);
child.addCriterionRequirement(new DirectCriterionRequirement(criterion2));
orderElementDAO.save(orderLineGroup);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(null,
Collections.singleton(criterion1));
List<OrderElement> orderELements =
orderElementDAO.findByLabelsAndCriteria(null, Collections.singleton(criterion1));
assertEquals(1, orderELements.size());
assertEquals(orderLineGroup.getId(), orderELements.get(0).getId());
orderELements = orderElementDAO.findByLabelsAndCriteria(null,
Collections.singleton(criterion2));
orderELements = orderElementDAO.findByLabelsAndCriteria(null, Collections.singleton(criterion2));
assertEquals(1, orderELements.size());
assertEquals(child.getId(), orderELements.get(0).getId());
orderELements = orderElementDAO.findByLabelsAndCriteria(null,
new HashSet<Criterion>(Arrays.asList(criterion1, criterion2)));
orderELements =
orderElementDAO.findByLabelsAndCriteria(null, new HashSet<>(Arrays.asList(criterion1, criterion2)));
assertEquals(0, orderELements.size());
}
@ -678,19 +654,17 @@ public class OrderElementDAOTest {
orderLine1.addLabel(label);
orderElementDAO.save(orderLine1);
OrderLine orderLine2 = createValidOrderLine();
orderLine2.addCriterionRequirement(new DirectCriterionRequirement(
criterion));
orderLine2.addCriterionRequirement(new DirectCriterionRequirement(criterion));
orderElementDAO.save(orderLine2);
OrderLine orderLine3 = createValidOrderLine();
orderLine3.addLabel(label);
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(
criterion));
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(criterion));
orderElementDAO.save(orderLine3);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(Collections.singleton(label),
Collections.singleton(criterion));
List<OrderElement> orderELements =
orderElementDAO.findByLabelsAndCriteria(Collections.singleton(label), Collections.singleton(criterion));
assertEquals(1, orderELements.size());
assertEquals(orderLine3.getId(), orderELements.get(0).getId());
}
@ -705,47 +679,39 @@ public class OrderElementDAOTest {
OrderLine orderLine1 = createValidOrderLine();
orderLine1.addLabel(label1);
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(
criterion2));
orderLine1.addCriterionRequirement(new DirectCriterionRequirement(criterion2));
orderElementDAO.save(orderLine1);
OrderLine orderLine2 = createValidOrderLine();
orderLine2.addLabel(label2);
orderLine2.addCriterionRequirement(new DirectCriterionRequirement(
criterion1));
orderLine2.addCriterionRequirement(new DirectCriterionRequirement(criterion1));
orderElementDAO.save(orderLine2);
OrderLine orderLine3 = createValidOrderLine();
orderLine3.addLabel(label1);
orderLine3.addLabel(label2);
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(
criterion1));
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(
criterion2));
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(criterion1));
orderLine3.addCriterionRequirement(new DirectCriterionRequirement(criterion2));
orderElementDAO.save(orderLine3);
List<OrderElement> orderELements = orderElementDAO
.findByLabelsAndCriteria(Collections.singleton(label2),
Collections.singleton(criterion1));
.findByLabelsAndCriteria(Collections.singleton(label2), Collections.singleton(criterion1));
assertEquals(2, orderELements.size());
for (OrderElement each : orderELements) {
assertTrue(each.getId().equals(orderLine2.getId())
|| each.getId().equals(orderLine3.getId()));
assertTrue(each.getId().equals(orderLine2.getId()) || each.getId().equals(orderLine3.getId()));
}
orderELements = orderElementDAO
.findByLabelsAndCriteria(Collections.singleton(label1),
Collections.singleton(criterion2));
.findByLabelsAndCriteria(Collections.singleton(label1), Collections.singleton(criterion2));
assertEquals(2, orderELements.size());
for (OrderElement each : orderELements) {
assertTrue(each.getId().equals(orderLine1.getId())
|| each.getId().equals(orderLine3.getId()));
assertTrue(each.getId().equals(orderLine1.getId()) || each.getId().equals(orderLine3.getId()));
}
orderELements = orderElementDAO
.findByLabelsAndCriteria(
new HashSet<Label>(Arrays.asList(label1, label2)),
new HashSet<Criterion>(Arrays.asList(criterion1,
criterion2)));
orderELements = orderElementDAO.findByLabelsAndCriteria(
new HashSet<>(Arrays.asList(label1, label2)), new HashSet<>(Arrays.asList(criterion1, criterion2)));
assertEquals(1, orderELements.size());
assertEquals(orderLine3.getId(), orderELements.get(0).getId());
}

View file

@ -48,7 +48,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
@ContextConfiguration(locations = {
BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
public class CriterionsBootstrapTest {
@ -79,8 +80,7 @@ public class CriterionsBootstrapTest {
private void cleanCriteria() {
try {
List<org.libreplan.business.resources.entities.Resource> resources = resourceDAO
.findAll();
List<org.libreplan.business.resources.entities.Resource> resources = resourceDAO.findAll();
for (org.libreplan.business.resources.entities.Resource resource : resources) {
resourceDAO.remove(resource.getId());
}
@ -100,10 +100,11 @@ public class CriterionsBootstrapTest {
}
private List<Criterion> getSomePredefinedCriterions() {
List<Criterion> result = new ArrayList<Criterion>();
List<Criterion> result = new ArrayList<>();
for (CategoryCriteria category : CategoryCriteria.values()) {
result.add(category.criterion());
}
return result;
}
@ -128,7 +129,7 @@ public class CriterionsBootstrapTest {
}
private void remove(Criterion criterion) {
if (criterionDAO.existsByNameAndType(criterion)) {
if ( criterionDAO.existsByNameAndType(criterion) ) {
criterionDAO.removeByNameAndType(criterion);
}
}

View file

@ -46,7 +46,6 @@ import org.junit.runner.RunWith;
import org.libreplan.business.IDataBootstrap;
import org.libreplan.business.calendars.entities.ResourceCalendar;
import org.libreplan.business.common.IAdHocTransactionService;
import org.libreplan.business.common.IOnTransaction;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.common.exceptions.ValidationException;
import org.libreplan.business.resources.daos.ICriterionDAO;
@ -72,7 +71,8 @@ import org.springframework.transaction.annotation.Transactional;
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
@ContextConfiguration(locations = {
BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
public class ResourceDAOTest {
@ -118,15 +118,16 @@ public class ResourceDAOTest {
sessionFactory.getCurrentSession().evict(resource);
Resource foundResource = resourceDAO.find(resource.getId());
assertNotSame(resource, foundResource);
assertNotNull(foundResource.getCalendar());
assertThat(foundResource.getCalendar().getId(),
equalTo(resourceCalendar.getId()));
assertThat(foundResource.getCalendar().getId(), equalTo(resourceCalendar.getId()));
}
private ResourceCalendar givenValidResourceCalendar() {
ResourceCalendar resourceCalendar = ResourceCalendar.create();
resourceCalendar.setName("Calendar");
return resourceCalendar;
}
@ -135,6 +136,7 @@ public class ResourceDAOTest {
worker.setFirstName("First name");
worker.setSurname("Surname");
worker.setNif("NIF" + UUID.randomUUID().toString());
return worker;
}
@ -143,8 +145,8 @@ public class ResourceDAOTest {
public void testResourceIsRelatedWithAllCriterions() {
Collection<Criterion> criterions = createCriterions();
createAndSaveResourceSatisfyingAllCriterions(criterions);
List<Resource> result = resourcesSearcher.searchBoth()
.byCriteria(criterions).execute();
List<Resource> result = resourcesSearcher.searchBoth().byCriteria(criterions).execute();
assertNotNull(result);
assertEquals(1, result.size());
}
@ -152,56 +154,43 @@ public class ResourceDAOTest {
@Test
public void theHierarchyOfCriterionsIsConsidered() {
final Criterion[] parentCriteron = { null };
Resource worker = transactionService
.runOnTransaction(new IOnTransaction<Resource>() {
@Override
public Resource execute() {
Worker result = givenValidWorker();
CriterionType type = createCriterionType("testType");
Criterion parent = createCriterion("parent", type);
parentCriteron[0] = parent;
Criterion child = createCriterion("child", type);
child.setParent(parent);
addSatisfactionsOn(result,
Interval.from(new LocalDate(1970, 1, 1)), child);
return result;
}
Resource worker = transactionService.runOnTransaction(() -> {
Worker result = givenValidWorker();
CriterionType type = createCriterionType("testType");
Criterion parent = createCriterion("parent", type);
parentCriteron[0] = parent;
Criterion child = createCriterion("child", type);
child.setParent(parent);
addSatisfactionsOn(result, Interval.from(new LocalDate(1970, 1, 1)), child);
return result;
});
final Criterion parent = transactionService
.runOnReadOnlyTransaction(new IOnTransaction<Criterion>() {
@Override
public Criterion execute() {
return criterionDAO
.findExistingEntity(parentCriteron[0].getId());
}
});
List<Resource> resources = transactionService
.runOnReadOnlyTransaction(new IOnTransaction<List<Resource>>() {
final Criterion parent = transactionService.runOnReadOnlyTransaction(() ->
criterionDAO.findExistingEntity(parentCriteron[0].getId()));
List<Resource> resources = transactionService.runOnReadOnlyTransaction(() ->
resourcesSearcher.searchBoth().byCriteria(Collections.singleton(parent)).execute());
@Override
public List<Resource> execute() {
return resourcesSearcher.searchBoth()
.byCriteria(Collections.singleton(parent))
.execute();
}
});
assertThat(resources.size(), equalTo(1));
Resource resource = resources.get(0);
assertThat(resource.getId(), equalTo(worker.getId()));
}
private Collection<Criterion> createCriterions() {
List<Criterion> result = new ArrayList<Criterion>();
List<Criterion> result = new ArrayList<>();
CriterionType type = createCriterionType("criterionTypeTest");
result.add(createCriterion("criterion1", type));
result.add(createCriterion("criterion2", type));
return result;
}
private CriterionType createCriterionType(String name) {
CriterionType result = CriterionType.create(name, "");
criterionTypeDAO.save(result);
return result;
}
@ -212,23 +201,22 @@ public class ResourceDAOTest {
private Criterion createCriterion(String name, CriterionType type) {
Criterion result = Criterion.create(name, type);
criterionDAO.save(result);
return result;
}
private Worker createAndSaveResourceSatisfyingAllCriterions(final Collection<Criterion> criterions) {
Worker result = givenValidWorker();
Interval interval = Interval.range(new LocalDate(1970, 1, 1), null);
addSatisfactionsOn(result, interval,
criterions.toArray(new Criterion[] {}));
addSatisfactionsOn(result, interval, criterions.toArray(new Criterion[criterions.size()]));
return result;
}
private void addSatisfactionsOn(Worker worker, Interval interval,
final Criterion... criterions) {
Set<CriterionSatisfaction> satisfactions = new HashSet<CriterionSatisfaction>();
private void addSatisfactionsOn(Worker worker, Interval interval, final Criterion... criterions) {
Set<CriterionSatisfaction> satisfactions = new HashSet<>();
for (Criterion each : criterions) {
satisfactions.add(CriterionSatisfaction.create(each, worker,
interval));
satisfactions.add(CriterionSatisfaction.create(each, worker, interval));
}
worker.addSatisfactions(satisfactions);
resourceDAO.save(worker);
@ -243,25 +231,20 @@ public class ResourceDAOTest {
// Modify criterions collection
criterions.add(createCriterion("criterion3"));
List<Resource> result = resourcesSearcher.searchBoth()
.byCriteria(criterions).execute();
List<Resource> result = resourcesSearcher.searchBoth().byCriteria(criterions).execute();
assertNotNull(result);
assertThat(result.size(), not(equalTo(1)));
}
private User givenStoredUser() {
return transactionService
.runOnAnotherTransaction(new IOnTransaction<User>() {
return transactionService.runOnAnotherTransaction(() -> {
User user = User.create("login" + UUID.randomUUID(), "password", "");
userDAO.save(user);
user.dontPoseAsTransientObjectAnymore();
@Override
public User execute() {
User user = User.create("login" + UUID.randomUUID(),
"password", "");
userDAO.save(user);
user.dontPoseAsTransientObjectAnymore();
return user;
}
});
return user;
});
}
@Test(expected = ValidationException.class)
@ -269,24 +252,20 @@ public class ResourceDAOTest {
public void testWorkerBoundToUserAlreadyBound() {
final User user = givenStoredUser();
transactionService.runOnAnotherTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
Worker worker1 = givenValidWorker();
worker1.setUser(user);
resourceDAO.save(worker1);
return null;
}
transactionService.runOnAnotherTransaction(() -> {
Worker worker1 = givenValidWorker();
worker1.setUser(user);
resourceDAO.save(worker1);
return null;
});
transactionService.runOnAnotherTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
Worker worker2 = givenValidWorker();
worker2.setUser(user);
resourceDAO.save(worker2);
return null;
}
transactionService.runOnAnotherTransaction(() -> {
Worker worker2 = givenValidWorker();
worker2.setUser(user);
resourceDAO.save(worker2);
return null;
});
}

View file

@ -52,8 +52,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
@Test
@Transactional
public void checkInvalidNameWorkReportType()
throws ValidationException {
public void checkInvalidNameWorkReportType() throws ValidationException {
WorkReportType workReportType = createValidWorkReportType();
workReportType.setName("");
try {
@ -107,7 +106,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
@Test
@Transactional
public void checkIfCodeWorkReportTypeIsUnique() throws ValidationException {
String code = new String("A");
String code = "A";
WorkReportType workReportTypeA = createValidWorkReportType();
workReportTypeA.setCode(code);
workReportTypeDAO.save(workReportTypeA);
@ -179,7 +178,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
}
@ -195,14 +194,14 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
descriptionFieldHead.setFieldName(null);
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
descriptionFieldHead.setFieldName("XXX");
@ -225,14 +224,14 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
descriptionFieldHead.setLength(0);
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
descriptionFieldHead.setLength(1);
@ -272,7 +271,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
}
@ -287,7 +286,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
}
@ -313,7 +312,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
}
@ -339,7 +338,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
}
@ -365,7 +364,7 @@ public class WorkReportTypeTest extends AbstractWorkReportTest {
try {
workReportTypeDAO.save(workReportType);
fail("It should throw an exception");
} catch (ValidationException e) {
} catch (ValidationException ignored) {
}
}
}

View file

@ -1,25 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field">
<class name="org.libreplan.business.test.workingday.hibernate.EntityContainingResourcePerDay"
table="entity_containing_resource_per_day">
<id name="id">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<property name="resourcesPerDay" type="org.libreplan.business.workingday.hibernate.ResourcesPerDayType"
column="resources_per_day" />
</class>
<class name="org.libreplan.business.test.workingday.hibernate.EntityContainingResourcePerDay"
table="entity_containing_resource_per_day">
<id name="id">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="resourcesPerDay" type="org.libreplan.business.workingday.hibernate.ResourcesPerDayType"
column="resources_per_day" />
</class>
<class name="org.libreplan.business.test.workingday.hibernate.EntityContainingEffortDuration"
table="entity_containing_effort_duration">
<id name="id">
<generator class="increment">
<param name="max_lo">100</param>
</generator>
</id>
<property name="duration" type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
</class>
<class name="org.libreplan.business.test.workingday.hibernate.EntityContainingEffortDuration"
table="entity_containing_effort_duration">
<id name="id">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<property name="duration" type="org.libreplan.business.workingday.hibernate.EffortDurationType" />
</class>
</hibernate-mapping>

View file

@ -1,6 +1,7 @@
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">${hibernate.dialect}</property>

View file

@ -1,27 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="dataSourceReal"
class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"
p:driverClass="${jdbcDriver.className}"
p:jdbcUrl="${testDataSource.url}"
p:username="${testDataSource.user}"
p:password="${testDataSource.password}"
p:maxConnectionsPerPartition="10"
p:minConnectionsPerPartition="4"
p:partitionCount="3"/>
class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"
p:driverClass="${jdbcDriver.className}"
p:jdbcUrl="${testDataSource.url}"
p:username="${testDataSource.user}"
p:password="${testDataSource.password}"
p:maxConnectionsPerPartition="10"
p:minConnectionsPerPartition="4"
p:partitionCount="3"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy"
p:targetDataSource-ref="dataSourceReal" />
class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy"
p:targetDataSource-ref="dataSourceReal" />
<!-- Hibernate Session Factory. -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="classpath:/libreplan-business-hibernate-test.cfg.xml">
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="classpath:/libreplan-business-hibernate-test.cfg.xml">
<!--
FIXME: ideally this chunk of XML should be only in
@ -71,9 +73,6 @@
<value>
org/libreplan/business/costcategories/entities/CostCategories.hbm.xml
</value>
<value>
TestEntities.hbm.xml
</value>
<value>
org/libreplan/business/qualityforms/entities/QualityForms.hbm.xml
</value>
@ -95,6 +94,9 @@
<value>
org/libreplan/business/expensesheets/entities/ExpenseSheets.hbm.xml
</value>
<value>
TestEntities.hbm.xml
</value>
</list>
</property>

View file

@ -43,9 +43,8 @@ import org.libreplan.importers.tim.RosterResponseDTO;
/**
* Client to interact with Tim SOAP server.
*
* This client creates SOAP message, makes connection to the SOAP server and
* sends the request. It is also the task of this client to convert the
* response(xml document) to java objects
* This client creates SOAP message, makes connection to the SOAP server and sends the request.
* It is also the task of this client to convert the response(xml document) to java objects.
*
* @author Miciele Ghiorghis <m.ghiorghis@antoniusziekenhuis.nl>
*/
@ -68,8 +67,8 @@ public class TimSoapClient {
* @throws JAXBException
* if unable to marshal the clazz
*/
private static <T> SOAPMessage createRequest(T clazz, String userName,
String password) throws SOAPException, JAXBException {
private static <T> SOAPMessage createRequest(
T clazz, String userName, String password) throws SOAPException, JAXBException {
SOAPMessage message = createMessage();
@ -81,6 +80,7 @@ public class TimSoapClient {
marshal(clazz, soapBody);
message.saveChanges();
return message;
}
@ -93,8 +93,8 @@ public class TimSoapClient {
*/
private static SOAPMessage createMessage() throws SOAPException {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
return message;
return messageFactory.createMessage();
}
/**
@ -107,12 +107,10 @@ public class TimSoapClient {
* @param password
* the password
*/
private static void addAuthorization(SOAPMessage message, String username,
String password) {
private static void addAuthorization(SOAPMessage message, String username, String password) {
String encodeUserInfo = username + ":" + password;
encodeUserInfo = Base64Utility.encode(encodeUserInfo.getBytes());
message.getMimeHeaders().setHeader("Authorization",
"Basic " + encodeUserInfo);
message.getMimeHeaders().setHeader("Authorization", "Basic " + encodeUserInfo);
}
/**
@ -124,11 +122,11 @@ public class TimSoapClient {
* @return the SOAP envelope
* @throws SOAPException
*/
private static SOAPEnvelope createEnvelope(SOAPPart soapPart)
throws SOAPException {
private static SOAPEnvelope createEnvelope(SOAPPart soapPart) throws SOAPException {
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
addNamespaceDeclaration(soapEnvelope);
setEncodingStyle(soapEnvelope);
return soapEnvelope;
}
@ -140,16 +138,11 @@ public class TimSoapClient {
* the SOAP envelope
* @throws SOAPException
*/
private static void addNamespaceDeclaration(SOAPEnvelope soapEnvelope)
throws SOAPException {
soapEnvelope.addNamespaceDeclaration("xsd",
"http://www.w3.org/2001/XMLSchema");
soapEnvelope.addNamespaceDeclaration("xsi",
"http://www.w3.org/2001/XMLSchema-instance");
soapEnvelope.addNamespaceDeclaration("enc",
"http://schemas.xmlsoap.org/soap/encoding/");
soapEnvelope.addNamespaceDeclaration("env",
"http://schemas.xmlsoap.org/soap/envelop/");
private static void addNamespaceDeclaration(SOAPEnvelope soapEnvelope) throws SOAPException {
soapEnvelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
soapEnvelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
soapEnvelope.addNamespaceDeclaration("enc", "http://schemas.xmlsoap.org/soap/encoding/");
soapEnvelope.addNamespaceDeclaration("env", "http://schemas.xmlsoap.org/soap/envelop/");
}
@ -161,10 +154,8 @@ public class TimSoapClient {
* the SOAP envelope
* @throws SOAPException
*/
private static void setEncodingStyle(SOAPEnvelope soapEnvelope)
throws SOAPException {
soapEnvelope
.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
private static void setEncodingStyle(SOAPEnvelope soapEnvelope) throws SOAPException {
soapEnvelope.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
}
/**
@ -178,8 +169,7 @@ public class TimSoapClient {
* @throws JAXBException
* if marshaling failed
*/
private static <T> void marshal(T clazz, SOAPBody soapBody)
throws JAXBException {
private static <T> void marshal(T clazz, SOAPBody soapBody) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(clazz, soapBody);
@ -198,15 +188,16 @@ public class TimSoapClient {
* if unmarshal failed
*/
@SuppressWarnings("unchecked")
private static <T> T unmarshal(Class<T> clazz, SOAPBody soapBody)
throws JAXBException {
private static <T> T unmarshal(Class<T> clazz, SOAPBody soapBody) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Node bindElement = (Node) soapBody.getFirstChild();
while (bindElement.getNodeType() != Node.ELEMENT_NODE) {
bindElement = (Node) bindElement.getNextSibling();
}
return unmarshaller.unmarshal(bindElement, clazz).getValue();
}
@ -221,15 +212,14 @@ public class TimSoapClient {
* @throws SOAPException
* if unable to send request
*/
private static SOAPMessage sendRequest(String url, SOAPMessage message)
throws SOAPException {
private static SOAPMessage sendRequest(String url, SOAPMessage message) throws SOAPException {
SOAPConnection connection = null;
SOAPMessage response = null;
try {
connection = createConnection();
response = connection.call(message, url);
} finally {
if (connection != null) {
if ( connection != null ) {
closeConnection(connection);
}
}
@ -245,10 +235,9 @@ public class TimSoapClient {
* if unable to create connection
*/
private static SOAPConnection createConnection() throws SOAPException {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory
.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
return connection;
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
return soapConnectionFactory.createConnection();
}
/**
@ -259,8 +248,7 @@ public class TimSoapClient {
* @throws SOAPException
* if unable to close connection
*/
private static void closeConnection(SOAPConnection connection)
throws SOAPException {
private static void closeConnection(SOAPConnection connection) throws SOAPException {
connection.close();
}
@ -280,11 +268,13 @@ public class TimSoapClient {
* the response class
* @return the expected object or null
*/
public static <T, U> T sendRequestReceiveResponse(String url,
String userName, String password, U request, Class<T> response) {
public static <T, U> T sendRequestReceiveResponse(
String url, String userName, String password, U request, Class<T> response) {
try {
SOAPMessage requestMsg = createRequest(request, userName, password);
SOAPMessage responseMsg = sendRequest(url, requestMsg);
return unmarshal(response, responseMsg.getSOAPBody());
} catch (SOAPException soapExp) {
LOG.error("SOAPException: ", soapExp);
@ -307,12 +297,12 @@ public class TimSoapClient {
* the password
* @return true if user is authorized otherwise false
*/
public static boolean checkAuthorization(String url, String username,
String password) {
public static boolean checkAuthorization(String url, String username, String password) {
try {
SOAPMessage message = createMessage();
addAuthorization(message, username, password);
sendRequest(url, message);
return true;
} catch (SOAPException e) {
LOG.error("SOAP Exception: ", e);
@ -332,13 +322,11 @@ public class TimSoapClient {
*/
public static RosterResponseDTO unmarshalRosterFromFile(File file) {
try {
JAXBContext jaxbContext = JAXBContext
.newInstance(RosterResponseDTO.class);
JAXBContext jaxbContext = JAXBContext.newInstance(RosterResponseDTO.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
RosterResponseDTO exportResponseDTO = (RosterResponseDTO) unmarshaller
.unmarshal(file);
return exportResponseDTO;
return (RosterResponseDTO) unmarshaller.unmarshal(file);
} catch (JAXBException e) {
LOG.error("Error processing response: ", e);
}

View file

@ -20,7 +20,6 @@ package org.libreplan.web;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
@ -99,11 +98,8 @@ public class LoggingConfiguration implements ServletContextListener {
return null;
}
File[] tomcatLogDirectories = file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().contains("tomcat");
}
File[] tomcatLogDirectories = file.listFiles(pathname -> {
return pathname.getName().contains("tomcat");
});
if ( tomcatLogDirectories.length == 0 ) {

View file

@ -46,34 +46,34 @@ public class BootstrapListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
WebApplicationContext webApplicationContext = WebApplicationContextUtils
.getWebApplicationContext(servletContextEvent
.getServletContext());
WebApplicationContext webApplicationContext =
WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
doBootstrap(webApplicationContext);
// some snapshots could depend on the bootstrap being done, so they are
// launched after
// Some snapshots could depend on the bootstrap being done, so they are launched after
launchSnapshots(webApplicationContext);
}
private void doBootstrap(WebApplicationContext webApplicationContext) {
List<IDataBootstrap> bootstrapsFound = findBootstraps(webApplicationContext);
Collections.sort(bootstrapsFound, byBootstrapOrder());
for (IDataBootstrap each : bootstrapsFound) {
each.loadRequiredData();
}
}
private List<IDataBootstrap> findBootstraps(
WebApplicationContext webApplicationContext) {
String[] beanNames = BeanFactoryUtils
.beanNamesForTypeIncludingAncestors(webApplicationContext,
IDataBootstrap.class);
List<IDataBootstrap> result = new ArrayList<IDataBootstrap>();
private List<IDataBootstrap> findBootstraps(WebApplicationContext webApplicationContext) {
String[] beanNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(webApplicationContext, IDataBootstrap.class);
List<IDataBootstrap> result = new ArrayList<>();
for (String name : beanNames) {
IDataBootstrap bootstrap = (IDataBootstrap) webApplicationContext
.getBean(name);
IDataBootstrap bootstrap = (IDataBootstrap) webApplicationContext.getBean(name);
result.add(bootstrap);
}
return result;
}
@ -87,24 +87,23 @@ public class BootstrapListener implements ServletContextListener {
private int getOrderingValue(IDataBootstrap dataBootstrap) {
BootstrapOrder annotation = searchAnnotationFor(dataBootstrap);
return annotation == null ? 0 : annotation.value();
}
private BootstrapOrder searchAnnotationFor(
IDataBootstrap dataBootstrap) {
Class<? extends IDataBootstrap> klass = dataBootstrap
.getClass();
BootstrapOrder result = klass
.getAnnotation(BootstrapOrder.class);
if (result == null && dataBootstrap instanceof Advised) {
private BootstrapOrder searchAnnotationFor(IDataBootstrap dataBootstrap) {
Class<? extends IDataBootstrap> klass = dataBootstrap.getClass();
BootstrapOrder result = klass.getAnnotation(BootstrapOrder.class);
if ( result == null && dataBootstrap instanceof Advised ) {
return searchInProxiedClass((Advised) dataBootstrap);
}
return result;
}
private BootstrapOrder searchInProxiedClass(Advised advised) {
Class<?> proxiedClass = advised.getTargetSource()
.getTargetClass();
Class<?> proxiedClass = advised.getTargetSource().getTargetClass();
return proxiedClass.getAnnotation(BootstrapOrder.class);
}
};
@ -115,16 +114,13 @@ public class BootstrapListener implements ServletContextListener {
snapshots.registerSnapshots();
}
private PredefinedDatabaseSnapshots getPredefinedDatabaseSnapshots(
WebApplicationContext webApplicationContext) {
return (PredefinedDatabaseSnapshots) webApplicationContext
.getBean(lowercaseFirst(PredefinedDatabaseSnapshots.class
.getSimpleName()));
private PredefinedDatabaseSnapshots getPredefinedDatabaseSnapshots(WebApplicationContext webApplicationContext) {
return (PredefinedDatabaseSnapshots)
webApplicationContext.getBean(lowercaseFirst(PredefinedDatabaseSnapshots.class.getSimpleName()));
}
private String lowercaseFirst(String simpleName) {
return simpleName.substring(0, 1).toLowerCase()
+ simpleName.substring(1);
return simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
}
}

View file

@ -35,9 +35,8 @@ import org.libreplan.business.resources.entities.CriterionType;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Implements all the methods needed to search the criterion to filter the
* orders. Provides multiples criterions to filter like {@link Criterion} and
* {@link Label}.
* Implements all the methods needed to search the criterion to filter the orders.
* Provides multiples criterions to filter like {@link Criterion} and {@link Label}.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@ -55,20 +54,22 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
fillWithFirstTenFiltersLabels();
fillWithFirstTenFiltersCriterions();
addNoneFilter();
return getListMatching();
}
private List<FilterPair> fillWithFirstTenFiltersLabels() {
Map<LabelType, List<Label>> mapLabels = getLabelsMap();
Iterator<LabelType> iteratorLabelType = mapLabels.keySet().iterator();
while (iteratorLabelType.hasNext() && getListMatching().size() < 10) {
LabelType type = iteratorLabelType.next();
for (int i = 0; getListMatching().size() < 10
&& i < mapLabels.get(type).size(); i++) {
for (int i = 0; getListMatching().size() < 10 && i < mapLabels.get(type).size(); i++) {
Label label = mapLabels.get(type).get(i);
addLabel(type, label);
addLabel(label);
}
}
return getListMatching();
}
@ -78,16 +79,16 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private List<FilterPair> fillWithFirstTenFiltersCriterions() {
SortedMap<CriterionType, List<Criterion>> mapCriterions = getMapCriterions();
Iterator<CriterionType> iteratorCriterionType = mapCriterions.keySet()
.iterator();
Iterator<CriterionType> iteratorCriterionType = mapCriterions.keySet().iterator();
while (iteratorCriterionType.hasNext() && getListMatching().size() < 10) {
CriterionType type = iteratorCriterionType.next();
for (int i = 0; getListMatching().size() < 10
&& i < mapCriterions.get(type).size(); i++) {
for (int i = 0; getListMatching().size() < 10 && i < mapCriterions.get(type).size(); i++) {
Criterion criterion = mapCriterions.get(type).get(i);
addCriterion(type, criterion);
}
}
return getListMatching();
}
@ -97,22 +98,22 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
public List<FilterPair> getMatching(String filter) {
getListMatching().clear();
if ((filter != null) && (!filter.isEmpty())) {
if ( (filter != null) && (!filter.isEmpty()) ) {
filter = StringUtils.deleteWhitespace(filter.toLowerCase());
searchInCriterionTypes(filter);
searchInLabelTypes(filter);
}
addNoneFilter();
return getListMatching();
}
private void searchInCriterionTypes(String filter) {
boolean limited = (filter.length() < 3);
for (CriterionType type : getMapCriterions().keySet()) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName().toLowerCase());
if ( name.contains(filter) ) {
setFilterPairCriterionType(type, limited);
} else {
searchInCriterions(type, filter);
@ -122,15 +123,15 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterions(CriterionType type, String filter) {
List<Criterion> list = getMapCriterions().get(type);
if (list == null) {
if ( list == null ) {
return;
}
for (Criterion criterion : list) {
String name = StringUtils.deleteWhitespace(criterion.getName()
.toLowerCase());
if (name.contains(filter)) {
String name = StringUtils.deleteWhitespace(criterion.getName().toLowerCase());
if ( name.contains(filter) ) {
addCriterion(type, criterion);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
if ( (filter.length() < 3) && (getListMatching().size() > 9) ) {
return;
}
}
@ -139,12 +140,13 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void setFilterPairCriterionType(CriterionType type, boolean limited) {
List<Criterion> list = getMapCriterions().get(type);
if (list == null) {
if ( list == null ) {
return;
}
for (Criterion criterion : list) {
addCriterion(type, criterion);
if ((limited) && (getListMatching().size() > 9)) {
if ( (limited) && (getListMatching().size() > 9) ) {
return;
}
}
@ -153,9 +155,8 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInLabelTypes(String filter) {
boolean limited = (filter.length() < 3);
for (LabelType type : getLabelsMap().keySet()) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName().toLowerCase());
if ( name.contains(filter) ) {
setFilterPairLabelType(type, limited);
} else {
searchInLabels(type, filter);
@ -165,11 +166,10 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInLabels(LabelType type, String filter) {
for (Label label : getLabelsMap().get(type)) {
String name = StringUtils.deleteWhitespace(label.getName()
.toLowerCase());
if (name.contains(filter)) {
addLabel(type, label);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
String name = StringUtils.deleteWhitespace(label.getName().toLowerCase());
if ( name.contains(filter) ) {
addLabel(label);
if ( (filter.length() < 3) && (getListMatching().size() > 9) ) {
return;
}
}
@ -178,8 +178,8 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void setFilterPairLabelType(LabelType type, boolean limited) {
for (Label label : getLabelsMap().get(type)) {
addLabel(type, label);
if ((limited) && (getListMatching().size() > 9)) {
addLabel(label);
if ( (limited) && (getListMatching().size() > 9) ) {
return;
}
}
@ -188,14 +188,11 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void addCriterion(CriterionType type, Criterion criterion) {
String pattern = criterion.getName() + " ( " + type.getName() + " )";
getListMatching().add(
new FilterPair(OrderElementFilterEnum.Criterion, type
.getResource().toLowerCase(), pattern, criterion));
new FilterPair(OrderElementFilterEnum.Criterion, type.getResource().toLowerCase(), pattern, criterion));
}
private void addLabel(LabelType type, Label label) {
getListMatching().add(
new FilterPair(OrderElementFilterEnum.Label, label
.getFinderPattern(), label));
private void addLabel(Label label) {
getListMatching().add(new FilterPair(OrderElementFilterEnum.Label, label.getFinderPattern(), label));
}
}

View file

@ -25,8 +25,7 @@ import static org.libreplan.web.I18nHelper._;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.planner.entities.Task;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.web.common.Util;
import org.libreplan.web.planner.order.PlanningStateCreator.PlanningState;
@ -48,9 +47,6 @@ import org.zkoss.zul.Window;
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AdvanceConsolidationController extends GenericForwardComposer {
private static final Log LOG = LogFactory
.getLog(AdvanceConsolidationController.class);
private IAdvanceConsolidationModel advanceConsolidationModel;
private Grid advancesGrid;
@ -65,9 +61,7 @@ public class AdvanceConsolidationController extends GenericForwardComposer {
window = (Window) comp;
}
public void showWindow(IContextWithPlannerTask<TaskElement> context,
org.libreplan.business.planner.entities.Task task,
PlanningState planningState) {
public void showWindow(IContextWithPlannerTask<TaskElement> context, Task task, PlanningState planningState) {
this.context = context;
advanceConsolidationModel.initAdvancesFor(task, context, planningState);
@ -75,9 +69,7 @@ public class AdvanceConsolidationController extends GenericForwardComposer {
try {
Util.reloadBindings(window);
window.doModal();
} catch (SuspendNotAllowedException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
} catch (SuspendNotAllowedException | InterruptedException e) {
throw new RuntimeException(e);
}
}
@ -89,9 +81,9 @@ public class AdvanceConsolidationController extends GenericForwardComposer {
public void accept() {
advanceConsolidationModel.accept();
if (context.getRelativeTo() instanceof TaskComponent) {
if ( context.getRelativeTo() instanceof TaskComponent ) {
((TaskComponent) context.getRelativeTo()).updateProperties();
((TaskComponent) context.getRelativeTo()).invalidate();
context.getRelativeTo().invalidate();
}
close();
}
@ -101,9 +93,8 @@ public class AdvanceConsolidationController extends GenericForwardComposer {
}
public String getInfoAdvance() {
String infoAdvanceAssignment = advanceConsolidationModel
.getInfoAdvanceAssignment();
if (infoAdvanceAssignment.isEmpty()) {
String infoAdvanceAssignment = advanceConsolidationModel.getInfoAdvanceAssignment();
if ( infoAdvanceAssignment.isEmpty() ) {
return _("Progress measurements");
}
@ -133,9 +124,10 @@ public class AdvanceConsolidationController extends GenericForwardComposer {
}
public String getReadOnlySclass() {
if (advanceConsolidationModel.hasLimitingResourceAllocation()) {
if ( advanceConsolidationModel.hasLimitingResourceAllocation() ) {
return "readonly";
}
return "";
}

View file

@ -25,7 +25,6 @@ import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.common.exceptions.ValidationException;
import org.libreplan.business.externalcompanies.entities.CommunicationType;
import org.libreplan.business.orders.entities.Order;
@ -39,8 +38,6 @@ import org.libreplan.web.common.MessagesForUser;
import org.libreplan.web.common.Util;
import org.libreplan.web.planner.tabs.IGlobalViewEntryPoints;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
@ -60,9 +57,6 @@ import org.zkoss.zul.SimpleListModel;
@SuppressWarnings("serial")
public class SubcontractorCommunicationCRUDController extends GenericForwardComposer {
private static final org.apache.commons.logging.Log LOG = LogFactory
.getLog(SubcontractorCommunicationCRUDController.class);
private ISubcontractorCommunicationModel subcontractorCommunicationModel;
private SubcontractorCommunicationRenderer subcontractorCommunicationRenderer = new SubcontractorCommunicationRenderer();
@ -90,14 +84,14 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
}
public void goToEdit(SubcontractorCommunication subcontractorCommunication) {
if(subcontractorCommunication != null){
if ( subcontractorCommunication != null ) {
TaskElement task = subcontractorCommunication.getSubcontractedTaskData().getTask();
OrderElement orderElement = task.getOrderElement();
Order order = subcontractorCommunicationModel.getOrder(orderElement);
if(subcontractorCommunication.getCommunicationType().equals(CommunicationType.PROGRESS_UPDATE)){
if ( subcontractorCommunication.getCommunicationType().equals(CommunicationType.PROGRESS_UPDATE) ) {
globalView.goToAdvanceTask(order,task);
}else{
} else {
globalView.goToOrderDetails(order);
}
}
@ -122,17 +116,22 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
listing.invalidate();
}
protected void save(SubcontractorCommunication subcontractorCommunication)
throws ValidationException {
protected void save(SubcontractorCommunication subcontractorCommunication) throws ValidationException {
subcontractorCommunicationModel.confirmSave(subcontractorCommunication);
}
public List<SubcontractorCommunication> getSubcontractorCommunications() {
FilterCommunicationEnum currentFilter = subcontractorCommunicationModel.getCurrentFilter();
switch(currentFilter){
case ALL: return subcontractorCommunicationModel.getSubcontractorAllCommunications();
case NOT_REVIEWED: return subcontractorCommunicationModel.getSubcontractorCommunicationWithoutReviewed();
default: return subcontractorCommunicationModel.getSubcontractorAllCommunications();
switch (currentFilter) {
case ALL:
return subcontractorCommunicationModel.getSubcontractorAllCommunications();
case NOT_REVIEWED:
return subcontractorCommunicationModel.getSubcontractorCommunicationWithoutReviewed();
default:
return subcontractorCommunicationModel.getSubcontractorAllCommunications();
}
}
@ -140,8 +139,7 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
return subcontractorCommunicationRenderer;
}
private class SubcontractorCommunicationRenderer implements
RowRenderer {
private class SubcontractorCommunicationRenderer implements RowRenderer {
@Override
public void render(Row row, Object data) {
@ -149,16 +147,16 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
row.setValue(subcontractorCommunication);
final boolean reviewed = subcontractorCommunication.getReviewed();
if(!reviewed){
if ( !reviewed ) {
row.setSclass("communication-not-reviewed");
}
appendLabel(row, subcontractorCommunication.getCommunicationType().toString());
appendLabel(row, subcontractorCommunication.getSubcontractedTaskData().getTask().getName());
appendLabel(row, getOrderName(subcontractorCommunication.getSubcontractedTaskData()));
appendLabel(row, getOrderCode(subcontractorCommunication.getSubcontractedTaskData()));
appendLabel(row, getOrderName(subcontractorCommunication.getSubcontractedTaskData()));
appendLabel(row, getOrderCode(subcontractorCommunication.getSubcontractedTaskData()));
appendLabel(row, subcontractorCommunication.getSubcontractedTaskData().getExternalCompany().getName());
appendLabel(row, Util.formatDateTime(subcontractorCommunication
.getCommunicationDate()));
appendLabel(row, Util.formatDateTime(subcontractorCommunication.getCommunicationDate()));
appendLabelWithTooltip(row, subcontractorCommunication);
appendCheckbox(row, subcontractorCommunication);
appendOperations(row, subcontractorCommunication);
@ -172,10 +170,10 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
return subcontractorCommunicationModel.getOrderName(subcontractedTaskData);
}
private String getLastValue(
SubcontractorCommunication subcontractorCommunication) {
SubcontractorCommunicationValue value = subcontractorCommunication
.getLastSubcontractorCommunicationValues();
private String getLastValue(SubcontractorCommunication subcontractorCommunication) {
SubcontractorCommunicationValue value =
subcontractorCommunication.getLastSubcontractorCommunicationValues();
return (value != null) ? value.toString() : "";
}
@ -183,68 +181,54 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
row.appendChild(new Label(label));
}
private void appendLabelWithTooltip(final Row row,
final SubcontractorCommunication subcontractorCommunication) {
private void appendLabelWithTooltip(
final Row row, final SubcontractorCommunication subcontractorCommunication) {
String lastValue = getLastValue(subcontractorCommunication);
final Label compLabel = new Label(lastValue);
if (subcontractorCommunication.getCommunicationType().equals(
CommunicationType.PROGRESS_UPDATE)) {
if ( subcontractorCommunication.getCommunicationType().equals(CommunicationType.PROGRESS_UPDATE) ) {
compLabel.setTooltip(pp);
compLabel.addEventListener(Events.ON_MOUSE_OVER,
new EventListener() {
@Override
public void onEvent(Event arg0) throws Exception {
List<SubcontractorCommunicationValue> model = subcontractorCommunication
.getSubcontractorCommunicationValues();
listingValues.setModel(new SimpleListModel(model));
listingValues.invalidate();
}
});
compLabel.addEventListener(Events.ON_MOUSE_OVER, arg0 -> {
List<SubcontractorCommunicationValue> model =
subcontractorCommunication.getSubcontractorCommunicationValues();
listingValues.setModel(new SimpleListModel(model));
listingValues.invalidate();
});
}
row.appendChild(compLabel);
}
private void appendCheckbox(final Row row,
final SubcontractorCommunication subcontractorCommunication) {
private void appendCheckbox(final Row row, final SubcontractorCommunication subcontractorCommunication) {
final Checkbox checkBoxReviewed = new Checkbox();
checkBoxReviewed.setChecked(subcontractorCommunication.getReviewed());
checkBoxReviewed.addEventListener(Events.ON_CHECK,
new EventListener() {
@Override
public void onEvent(Event arg0) throws Exception {
subcontractorCommunication.setReviewed(checkBoxReviewed.isChecked());
save(subcontractorCommunication);
updateRowClass(row, checkBoxReviewed.isChecked());
}
});
checkBoxReviewed.addEventListener(Events.ON_CHECK, arg0 -> {
subcontractorCommunication.setReviewed(checkBoxReviewed.isChecked());
save(subcontractorCommunication);
updateRowClass(row, checkBoxReviewed.isChecked());
});
row.appendChild(checkBoxReviewed);
}
private void updateRowClass(final Row row, Boolean reviewed){
row.setSclass("");
if(!reviewed){
if ( !reviewed ){
row.setSclass("communication-not-reviewed");
}
}
private void appendOperations(Row row,
final SubcontractorCommunication subcontractorCommunication) {
private void appendOperations(Row row, final SubcontractorCommunication subcontractorCommunication) {
Button buttonEdit = new Button();
buttonEdit.setSclass("icono");
buttonEdit.setImage("/common/img/ico_editar1.png");
buttonEdit.setHoverImage("/common/img/ico_editar.png");
buttonEdit.setTooltiptext(_("Edit"));
buttonEdit.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event arg0) throws Exception {
goToEdit(subcontractorCommunication);
}
});
buttonEdit.addEventListener(Events.ON_CLICK, arg0 -> goToEdit(subcontractorCommunication));
row.appendChild(buttonEdit);
}
}
@ -252,9 +236,8 @@ public class SubcontractorCommunicationCRUDController extends GenericForwardComp
/**
* Apply filter to subcontractors communications
*
* @param event
*/
public void onApplyFilter(Event event) {
public void onApplyFilter() {
refreshSubcontractorCommunicationsList();
}
}

View file

@ -26,6 +26,7 @@ import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
import org.libreplan.business.common.Configuration;
import org.libreplan.business.common.Registry;
@ -48,63 +49,80 @@ import org.libreplan.business.users.entities.UserRole;
*/
public enum PredefinedUsers {
ADMIN(Arrays.asList(UserRole.ROLE_SUPERUSER,
UserRole.ROLE_READ_ALL_PROJECTS,
UserRole.ROLE_EDIT_ALL_PROJECTS,
UserRole.ROLE_CREATE_PROJECTS), false) {
ADMIN(Arrays.asList(
UserRole.ROLE_SUPERUSER,
UserRole.ROLE_READ_ALL_PROJECTS,
UserRole.ROLE_EDIT_ALL_PROJECTS,
UserRole.ROLE_CREATE_PROJECTS),
false) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultAdminPassword();
}
},
WSREADER(Arrays.asList(UserRole.ROLE_WS_READER), Configuration
.isExampleUsersDisabled()) {
WSREADER(Collections.singletonList(UserRole.ROLE_WS_READER), Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultWsreaderPassword();
}
},
WSWRITER(Arrays.asList(UserRole.ROLE_WS_READER, UserRole.ROLE_WS_WRITER),
Configuration.isExampleUsersDisabled()) {
WSWRITER(Arrays.asList(
UserRole.ROLE_WS_READER, UserRole.ROLE_WS_WRITER), Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultWswriterPassword();
}
},
WSSUBCONTRACTING(Arrays.asList(UserRole.ROLE_WS_SUBCONTRACTING),
Configuration.isExampleUsersDisabled()) {
WSSUBCONTRACTING(
Collections.singletonList(UserRole.ROLE_WS_SUBCONTRACTING), Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration()
.getChangedDefaultWssubcontractingPassword();
return getConfiguration().getChangedDefaultWssubcontractingPassword();
}
},
MANAGER(null, Arrays.asList(PredefinedProfiles.PROJECT_MANAGER),
Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration()
.getChangedDefaultManagerPassword();
}
},
HRESOURCES(null, Arrays
.asList(PredefinedProfiles.HUMAN_RESOURCES_AND_COSTS_MANAGER),
MANAGER(
null,
Collections.singletonList(PredefinedProfiles.PROJECT_MANAGER),
Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultManagerPassword();
}
},
OUTSOURCING(null, Arrays.asList(PredefinedProfiles.OUTSOURCING_MANAGER),
HRESOURCES(
null,
Collections.singletonList(PredefinedProfiles.HUMAN_RESOURCES_AND_COSTS_MANAGER),
Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultManagerPassword();
}
},
REPORTS(null, Arrays.asList(PredefinedProfiles.REPORTS_RESPONSIBLE),
OUTSOURCING(
null,
Collections.singletonList(PredefinedProfiles.OUTSOURCING_MANAGER),
Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultManagerPassword();
}
},
REPORTS(
null,
Collections.singletonList(PredefinedProfiles.REPORTS_RESPONSIBLE),
Configuration.isExampleUsersDisabled()) {
@Override
public boolean hasChangedDefaultPassword() {
return getConfiguration().getChangedDefaultManagerPassword();
@ -112,14 +130,12 @@ public enum PredefinedUsers {
};
public static boolean adminChangedAndSomeOtherNotChanged() {
return ADMIN.hasChangedDefaultPasswordOrDisabled()
&& someKeepsDefaultPassword(allExcept(ADMIN));
return ADMIN.hasChangedDefaultPasswordOrDisabled() && someKeepsDefaultPassword(allExcept(ADMIN));
}
public static boolean someKeepsDefaultPassword(
Collection<PredefinedUsers> mandatoryUsers) {
public static boolean someKeepsDefaultPassword(Collection<PredefinedUsers> mandatoryUsers) {
for (PredefinedUsers each : mandatoryUsers) {
if (!each.hasChangedDefaultPasswordOrDisabled()) {
if ( !each.hasChangedDefaultPasswordOrDisabled() ) {
return true;
}
}
@ -127,29 +143,29 @@ public enum PredefinedUsers {
}
private static org.libreplan.business.common.entities.Configuration getConfiguration() {
return Registry.getConfigurationDAO()
.getConfigurationWithReadOnlyTransaction();
return Registry.getConfigurationDAO().getConfigurationWithReadOnlyTransaction();
}
private Set<UserRole> initialRoles = new HashSet<UserRole>();
private Set<UserRole> initialRoles = new HashSet<>();
private Set<PredefinedProfiles> initialProfiles = new HashSet<PredefinedProfiles>();
private Set<PredefinedProfiles> initialProfiles = new HashSet<>();
private final boolean userDisabled;
private PredefinedUsers(Collection<UserRole> initialUserRoles,
boolean userDisabled) {
PredefinedUsers(Collection<UserRole> initialUserRoles, boolean userDisabled) {
this(initialUserRoles, null, userDisabled);
}
private PredefinedUsers(Collection<UserRole> initialUserRoles,
Collection<PredefinedProfiles> initialProfiles, boolean userDisabled) {
if (initialUserRoles != null) {
this.initialRoles = new HashSet<UserRole>(initialUserRoles);
PredefinedUsers(Collection<UserRole> initialUserRoles,
Collection<PredefinedProfiles> initialProfiles,
boolean userDisabled) {
if ( initialUserRoles != null ) {
this.initialRoles = new HashSet<>(initialUserRoles);
}
if (initialProfiles != null) {
this.initialProfiles = new HashSet<PredefinedProfiles>(
initialProfiles);
if ( initialProfiles != null ) {
this.initialProfiles = new HashSet<>(initialProfiles);
}
this.userDisabled = userDisabled;
}
@ -186,8 +202,7 @@ public enum PredefinedUsers {
public boolean isDisabled() {
try {
return Registry.getUserDAO().findByLoginName(getLoginName())
.isDisabled();
return Registry.getUserDAO().findByLoginName(getLoginName()).isDisabled();
} catch (InstanceNotFoundException e) {
return true;
}

View file

@ -22,7 +22,10 @@
*
* @author Manuel Rego Casasnovas <rego@igalia.com>
*/
@javax.xml.bind.annotation.XmlSchema(elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, namespace = WSCommonGlobalNames.REST_NAMESPACE)
@javax.xml.bind.annotation.XmlSchema(
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
namespace = WSCommonGlobalNames.REST_NAMESPACE)
package org.libreplan.ws.boundusers.api;
import org.libreplan.ws.common.api.WSCommonGlobalNames;

Some files were not shown because too many files have changed in this diff Show more