CooperatorOwnedModel.java

/*
 * Copyright 2019 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;

import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;

import lombok.Getter;
import lombok.Setter;
import org.genesys.blocks.auditlog.annotations.Audited;
import org.genesys.blocks.security.SecurityContextUtil;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.util.JsonClassNameWriter;
import org.genesys.blocks.util.JsonSidConverter;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/* @formatter:off */
@JsonAppend(props = { 
	@JsonAppend.Prop(name = "_class", value = JsonClassNameWriter.class, type = String.class),
	// @JsonAppend.Prop(name = "_permissions", value = GGCEPermissionsWriter.class, type = Permissions.class)
})
/* @formatter:on */
@Audited
@MappedSuperclass
@Getter
@Setter
public abstract class CooperatorOwnedModel extends AuditedModel implements LazyLoading<CooperatorOwnedModel> {

	private static final long serialVersionUID = -5885407152743912546L;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "owned_by", nullable = false)
	@JsonProperty(access = JsonProperty.Access.READ_ONLY)
	@JsonSerialize(converter = JsonSidConverter.class)
	private AclSid ownedBy;

	@Column(name = "owned_date", nullable = false)
	private Instant ownedDate;

	/**
	 * Automatically populate ownedBy and ownedDate if not specified.
	 */
	@PrePersist
	protected void prePersist() {
		if (ownedBy == null) {
			ownedBy = SecurityContextUtil.getCurrentUser();
		}
		if (ownedDate == null) {
			ownedDate = this.getCreatedDate();
		}
	}

}