NumericListDimension.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 lombok.Getter;
import lombok.Setter;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Transient;
/**
* @author Matija Obreza
*/
@Entity
@Getter
@Setter
public class NumericListDimension extends FixedListDimension<Number> {
private static final long serialVersionUID = -7094497676282983119L;
@Column(length = 100)
private String javaType = "java.lang.Integer";
@Transient
private Class<?> clazz;
@Column(name = "listvalue", nullable = false)
@ElementCollection()
@CollectionTable(name = "kpi_dimension_numeric", joinColumns = @JoinColumn(name = "dimensionId"))
private Set<Double> values;
@Override
public Class<Number> getTargetType() {
return Number.class;
}
public void setValues(Set<Number> list) {
if (list == null) {
this.values = null;
} else {
this.values = list.stream().map(Number::doubleValue).collect(Collectors.toSet());
}
}
@Override
public Set<Number> getValues() {
if (values == null) {
return null;
}
return this.values.stream().map(this::toType).collect(Collectors.toSet());
}
private Number toType(Double d) {
if (this.clazz == null) {
getClazz();
}
if (this.clazz == Integer.class) {
return d.intValue();
} else if (this.clazz == Long.class) {
return d.longValue();
} else if (this.clazz == Float.class) {
return d.floatValue();
} else if (this.clazz == Double.class) {
return d;
} else if (this.clazz == Short.class) {
return d.shortValue();
} else if (this.clazz == Byte.class) {
return d.byteValue();
}
throw new RuntimeException("Unsupported NumericListDimension type " + this.javaType + " clazz=" + this.clazz);
}
public Class<?> getClazz() {
if (clazz == null) {
try {
this.clazz = Class.forName(javaType);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
this.javaType = this.clazz.getName();
}
@Override
public boolean canEqual(Object other) {
return other instanceof NumericListDimension;
}
@Override
public Dimension<Number> apply(Dimension source) {
this.setValues(((NumericListDimension)source).getValues());
return super.apply(source);
}
}