FaoInstitute.java

/**
 * Copyright 2014 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.genesys.server.model.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.MapKey;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.model.BasicModel;
import org.genesys.blocks.model.Copyable;
import org.genesys.blocks.model.EntityId;
import org.genesys.blocks.model.JsonViews;
import org.genesys.blocks.security.model.AclAwareModel;
import org.genesys.blocks.util.ClassAclOid;
import org.genesys.custom.elasticsearch.IgnoreField;
import org.genesys.custom.elasticsearch.SearchField;
import org.genesys.server.model.Partner;
import org.genesys.server.model.genesys.PDCIStatistics;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

@Cacheable
@Entity
@Table(name = "faoinstitute", uniqueConstraints = @UniqueConstraint(columnNames = { "code" }), indexes = { @Index(columnList = "code", name = "code_FAOINSTITUTE") })
@Document(indexName = "faoinstitute")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = FaoInstitute.class)
@Getter
@Setter
@NoArgsConstructor
public class FaoInstitute extends BasicModel implements GeoReferencedEntity, AclAwareModel, EntityId, LazyLoading<FaoInstitute>, Copyable<FaoInstitute> {

	private static final ClassAclOid<FaoInstitute> DEFAULT_PARENT_OID = ClassAclOid.forClass(FaoInstitute.class);

	private static final long serialVersionUID = -8773002513838748431L;

	private static final int LEN_ACRONYM = 50;

	private static final ObjectMapper mapper = new ObjectMapper();

	@Size(max = 10)
	@NotNull
	@Column(unique = true, nullable = false, length = 10)
	@SearchField
	private String code;

	@Size(max = 300)
	@Column(length = 300)
	@SearchField
	@Field(type = FieldType.Text)
	private String fullName;

	@Size(max = 100)
	@Column(length = 100)
	@JsonView({ JsonViews.Public.class })
	private String type;

	@Size(max = 300)
	@Column(length = 300)
	@JsonView({ JsonViews.Public.class })
	private String url;

	@Size(max = 300)
	@Column(length = 300)
	@JsonView({ JsonViews.Public.class })
	private String email;

	@Column(length = LEN_ACRONYM)
	@SearchField
	private String acronym;

	@Size(max = 10)
	@Column(length = 10)
	private String vCode;

	@Column(name = "codeSGSV")
	@JsonView({ JsonViews.Public.class })
	private String codeSGSV;

	private boolean current;

	@ManyToOne(cascade = {}, optional = true)
	@JoinColumn(name = "countryId")
	@JsonView({ JsonViews.Public.class })
	@Field(type = FieldType.Object)
	private Country country;

	@JsonView({ JsonViews.Protected.class })
	@OneToMany(cascade = {})
	@JoinColumn(referencedColumnName = "code", name = "instCode")
	@MapKey(name = "setting")
	@IgnoreField
	private Map<String, FaoInstituteSetting> settings = new HashMap<String, FaoInstituteSetting>();

	@JsonView({ JsonViews.Public.class })
	@ManyToMany(cascade = {}, fetch = FetchType.LAZY, mappedBy = "members")
	@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "slug")
	@JsonIdentityReference(alwaysAsId = true)
	@JsonProperty(access = Access.READ_ONLY)
	@Field(type = FieldType.Keyword)
	private List<PGRFANetwork> networks;


	@ManyToOne(cascade = {})
	@JoinColumn(name = "partnerId")
	@JsonView({ JsonViews.Public.class })
	@JsonProperty(access = Access.READ_ONLY)
	private Partner owner;

	private long accessionCount;
	private boolean pgrActivity;
	private boolean maintainsCollection;
	private Double latitude;
	private Double longitude;
	private Double elevation;
	private boolean uniqueAcceNumbs = false;
	private boolean allowMaterialRequests = false;
	private Double pdciMin;
	private Double pdciMax;
	private Double pdciAvg;

	@Column(name = "pdciHistogram")
	@JsonProperty(access = Access.READ_ONLY)
	@IgnoreField
	private String pdciHistogram;


	@Override
	public AclAwareModel aclParentObject(){
		return this.owner == null ? DEFAULT_PARENT_OID : this.owner;
	}

	@Override
	public String toString() {
		return MessageFormat.format("FaoInst id={0,number,#} code={1} fullName={2}", getId(), code, fullName);
	}

	public void setAcronym(final String acronym) {
		this.acronym = StringUtils.abbreviate(acronym, LEN_ACRONYM);
	}

	public boolean hasUniqueAcceNumbs() {
		return this.uniqueAcceNumbs;
	}

	@IgnoreField
	public PDCIStatistics getStatisticsPDCI() {
		if (this.pdciMin == null || this.pdciMax == null || this.pdciAvg == null) {
			return null;
		}

		PDCIStatistics stats = new PDCIStatistics();
		stats.setMin(this.pdciMin);
		stats.setMax(this.pdciMax);
		stats.setCount(this.accessionCount);
		stats.setAvg(this.pdciAvg);
		stats.setHistogram(parsePdciHistogram());

		return stats;
	}

	public long[] parsePdciHistogram() {
		long[] histogram = new long[21];

		if (StringUtils.isBlank(this.pdciHistogram)) {
			return histogram;
		}

		try {
			histogram = mapper.readValue(this.pdciHistogram, long[].class);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return histogram;
	}

	/**
	 * Transitive
	 * 
	 * @throws MalformedURLException
	 */
	public List<URL> getUrls() throws MalformedURLException {
		if (StringUtils.isBlank(this.url)) {
			return null;
		}

		ArrayList<URL> urls = new ArrayList<URL>();

		String[] s = this.url.split("[,;\\s]+");
		for (String u : s) {
			if (StringUtils.isBlank(u)) {
				continue;
			}

			u = u.trim();
			URL url = null;
			try {
				url = new URL(u);
			} catch (MalformedURLException e) {
				if (e.getMessage().startsWith("no protocol")) {
					try {
						url = new URL("http://" + u);
					} catch (MalformedURLException e2) {
						throw e;
					}
				} else if (e.getMessage().startsWith("unknown protocol")) {
					try {
						url = new URL("http://" + u.substring(u.indexOf("://") + 3));
					} catch (MalformedURLException e2) {
						throw e;
					}
				} else {
					throw e;
				}
			}

			if (url != null) {
				urls.add(url);
			}
		}

		return urls;
	}

	/**
	 * Same as {@link #getUrls()} above, but no exceptions are thrown
	 * 
	 * @return
	 */
	public List<URL> getSafeUrls() {
		try {
			return getUrls();
		} catch (MalformedURLException e) {
			// Ignore
			return null;
		}
	}

	@Override
	public void lazyLoad() {
		if (CollectionUtils.isNotEmpty(networks)) {
			networks.size();
		}
	}

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