ExecutionRun.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.model.kpi;

import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import lombok.Getter;
import lombok.Setter;
import org.genesys.blocks.model.BasicModel;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name = "kpi_execution_run")
@Getter
@Setter
public class ExecutionRun extends BasicModel {

	private static final long serialVersionUID = -3572471919023776436L;

	/** The sum of all observations.value */
	private Double totalValue;

	@NotNull
	@Column(nullable = false)
	@Temporal(TemporalType.TIMESTAMP)
	private Date timestamp = new Date();

	@NotNull
	@JsonIgnore
	@ManyToOne(cascade = {}, optional = false)
	private Execution execution;

	@OneToMany(mappedBy="executionRun", cascade = { CascadeType.PERSIST }, orphanRemoval = true)
	private List<Observation> observations;

	@PrePersist
	@PreUpdate
	private void prePersist() {
		if (observations != null) {
			this.totalValue = observations.stream().map(Observation::getValue).reduce(0D, (x, y) -> x + y);
		}
	}

	@Override
	public boolean canEqual(Object other) {
		return other instanceof ExecutionRun;
	}
}