WebOwnedModel.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.Basic;
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.security.SecurityContextUtil;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.util.JsonSidConverter;

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

@MappedSuperclass
@Getter
@Setter
public abstract class WebOwnedModel extends AuditedModel implements LazyLoading<WebOwnedModel> {

	private static final long serialVersionUID = 5390807226530987338L;

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

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

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

	@Override
	public void lazyLoad() {
		lazyLoad(this.ownedBy);
	}

}