Commit 68e3da10 authored by Matija Obreza's avatar Matija Obreza

Merge branch '427-remove-publishvalidationinterface' into 'master'

Remove PublishValidationInterface

Closes #427

See merge request genesys-pgr/genesys-server!368
parents 5963a1e2 71850d3f
/*
* Copyright 2017 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.catalog.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.genesys.catalog.service.PublishValidationInterface;
import static java.lang.annotation.ElementType.FIELD;
/**
* Fields with this annotation are required fields, they have to be filled
* during publication process. You should implement
* {@link PublishValidationInterface} for parent class. That give you use
* {@link PublishValidationInterface#validation()} for validate before publish.
* And if you want use {@link PublishValidation#innerCheck()} you should
* implement {@link PublishValidationInterface} for child class and override
* {@link PublishValidationInterface#validation()} method.
*
* @author Andrey Lugovskoy.
*/
@Documented
@Target({ FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface PublishValidation {
/**
* If field is object and innerCheck=true than we have to check inner fields.
*
* @return boolean value
*/
boolean innerCheck() default false;
/**
* You should set {@link Boolean#TRUE} for this field to avoid recursive invoke
* {@link PublishValidationInterface#validation()} method if child class has
* link to parent class.
*
* @return boolean value
*/
boolean ignoreValidation() default false;
}
/*
* Copyright 2017 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.catalog.annotations;
import java.util.HashMap;
import java.util.Map;
import org.genesys2.server.exception.InvalidApiUsageException;
/**
* The Class PublishValidationException.
*
* @author Andrey Lugovskoy.
*/
public class PublishValidationException extends InvalidApiUsageException {
private static final long serialVersionUID = 3227086532743886389L;
private Map<String, String> errorMap = new HashMap<>();
/**
* Gets the error map.
*
* @return the error map
*/
public Map<String, String> getErrorMap() {
return errorMap;
}
/**
* Adds the error.
*
* @param key the key
* @param value the value
*/
public void addError(final String key, final String value) {
errorMap.put(key, value);
}
/**
* Instantiates a new publish validation exception.
*/
public PublishValidationException() {
super();
}
/**
* Instantiates a new publish validation exception.
*
* @param errorMap the error map
*/
public PublishValidationException(final Map<String, String> errorMap) {
super();
this.errorMap = errorMap;
}
/**
* Instantiates a new publish validation exception.
*
* @param message the message
*/
public PublishValidationException(final String message) {
super(message);
}
/**
* Instantiates a new publish validation exception.
*
* @param message the message
* @param cause the cause
*/
public PublishValidationException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Instantiates a new publish validation exception.
*
* @param cause the cause
*/
public PublishValidationException(final Throwable cause) {
super(cause);
}
}
......@@ -47,10 +47,8 @@ import org.genesys.blocks.model.Publishable;
import org.genesys.blocks.model.SelfCleaning;
import org.genesys.blocks.model.UuidModel;
import org.genesys.blocks.security.model.AclAwareModel;
import org.genesys.catalog.annotations.PublishValidation;
import org.genesys.catalog.model.Partner;
import org.genesys.catalog.model.traits.Descriptor;
import org.genesys.catalog.service.PublishValidationInterface;
import org.genesys.filerepository.model.RepositoryFile;
import org.genesys2.server.model.PublishState;
import org.genesys2.server.model.impl.Crop;
......@@ -75,20 +73,18 @@ import com.fasterxml.jackson.annotation.JsonView;
@Cacheable
@Audited
@Document(indexName = "dataset")
public class Dataset extends UuidModel implements Publishable, SelfCleaning, PublishValidationInterface, AclAwareModel {
public class Dataset extends UuidModel implements Publishable, SelfCleaning, AclAwareModel {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -4601980446454791177L;
/** The versions. */
@PublishValidation
@ManyToOne(cascade = CascadeType.ALL, optional = false)
@JoinColumn(name = "versionsId", updatable = false)
@JsonIgnore
private DatasetVersions versions;
/** The owner. */
@PublishValidation
@ManyToOne(cascade = {}, optional = false)
@JoinColumn(name = "partnerId", updatable = false)
@JsonView({ JsonViews.Public.class })
......@@ -109,7 +105,6 @@ public class Dataset extends UuidModel implements Publishable, SelfCleaning, Pub
private List<Descriptor> descriptors;
/** The repository files. */
@PublishValidation
@OneToMany(fetch = FetchType.LAZY, cascade = {})
@JoinTable(name = "dataset_repositoryfile", joinColumns = @JoinColumn(name = "datasetId", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "repositoryfileId", referencedColumnName = "id"))
@OrderColumn(name = "position")
......@@ -118,14 +113,12 @@ public class Dataset extends UuidModel implements Publishable, SelfCleaning, Pub
private List<RepositoryFile> repositoryFiles;
/** The creators. */
@PublishValidation(innerCheck = true)
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "dataset", orphanRemoval = true, fetch = FetchType.LAZY)
@Field(type = FieldType.Object)
@JsonView({ JsonViews.Public.class })
private List<DatasetCreator> creators;
/** The locations. */
@PublishValidation(innerCheck = true)
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "dataset", orphanRemoval = true, fetch = FetchType.LAZY)
@Field(type = FieldType.Object)
@JsonView({ JsonViews.Public.class })
......@@ -168,13 +161,11 @@ public class Dataset extends UuidModel implements Publishable, SelfCleaning, Pub
/**
* DatasetVersions title in English.
*/
@PublishValidation
private String title;
/**
* DatasetVersions description in English.
*/
@PublishValidation
@Lob
private String description;
......@@ -184,14 +175,12 @@ public class Dataset extends UuidModel implements Publishable, SelfCleaning, Pub
private String format;
/** Language used in the versions. */
@PublishValidation
private String language;
/** The subject of the versions. */
private String subject;
/** The rights. */
@PublishValidation
private String rights;
/** The source. */
......
......@@ -17,8 +17,6 @@ package org.genesys.catalog.model.dataset;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.genesys.blocks.model.UuidModel;
import org.genesys.catalog.annotations.PublishValidation;
import org.genesys.catalog.service.PublishValidationInterface;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
......@@ -32,7 +30,7 @@ import java.util.Map;
*/
@Entity
@Table(name="dataset_creator")
public class DatasetCreator extends UuidModel implements PublishValidationInterface {
public class DatasetCreator extends UuidModel {
/**
*
......@@ -58,35 +56,28 @@ public class DatasetCreator extends UuidModel implements PublishValidationInterf
}
/** The full name. */
@PublishValidation
@NotNull
@Size(max = 200)
@Column(length = 200, nullable = false)
private String fullName;
/** The email. */
@PublishValidation
private String email;
/** The phone number. */
@PublishValidation
private String phoneNumber;
/** The fax. */
@PublishValidation
private String fax;
/** The institutional affiliation. */
@PublishValidation
private String institutionalAffiliation;
/** The institute address. */
@PublishValidation
private String instituteAddress;
/** The role. */
@Enumerated(EnumType.STRING)
@PublishValidation
private DatasetCreatorRole role;
/** The dataset. */
......@@ -238,13 +229,4 @@ public class DatasetCreator extends UuidModel implements PublishValidationInterf
public void setInstituteAddress(final String instituteAddress) {
this.instituteAddress = instituteAddress;
}
/*
* (non-Javadoc)
* @see org.genesys.catalog.service.PublishValidationInterface#validation()
*/
@Override
public Map<String, String> validation() {
return PublishValidationInterface.super.validation();
}
}
......@@ -17,8 +17,6 @@ package org.genesys.catalog.model.dataset;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.genesys.blocks.model.UuidModel;
import org.genesys.catalog.annotations.PublishValidation;
import org.genesys.catalog.service.PublishValidationInterface;
import org.genesys2.util.MCPDUtil;
import javax.persistence.*;
......@@ -32,7 +30,7 @@ import java.util.Map;
*/
@Entity
@Table(name="dataset_location")
public class DatasetLocation extends UuidModel implements PublishValidationInterface {
public class DatasetLocation extends UuidModel {
/**
*
......@@ -46,26 +44,21 @@ public class DatasetLocation extends UuidModel implements PublishValidationInter
private Dataset dataset;
/** The user-provided country name. */
@PublishValidation
private String userCountry;
/** Country as detected from coordinates. */
@PublishValidation
private String mapCountry;
/** The state province. */
@PublishValidation
private String stateProvince;
/** The verbatim locality. */
private String verbatimLocality;
/** The decimal latitude. */
@PublishValidation
private Double decimalLatitude;
/** The decimal longitude. */
@PublishValidation
private Double decimalLongitude;
/** ISO3 country code of the location */
......@@ -294,13 +287,4 @@ public class DatasetLocation extends UuidModel implements PublishValidationInter
public void setDescription(String description) {
this.description = description;
}
/*
* (non-Javadoc)
* @see org.genesys.catalog.service.PublishValidationInterface#validation()
*/
@Override
public Map<String, String> validation() {
return PublishValidationInterface.super.validation();
}
}
......@@ -16,7 +16,6 @@
package org.genesys.catalog.model.dataset;
import org.genesys.blocks.model.UuidModel;
import org.genesys.catalog.annotations.PublishValidation;
import javax.persistence.Entity;
import javax.persistence.FetchType;
......@@ -40,12 +39,10 @@ public class DatasetVersions extends UuidModel {
private static final long serialVersionUID = 7307818236681549484L;
/** The current version. */
@PublishValidation(ignoreValidation = true)
@OneToOne(cascade = {}, orphanRemoval = true)
private Dataset currentVersion;
/** The all versions. */
@PublishValidation
@OneToMany(cascade = {}, fetch = FetchType.LAZY, mappedBy = "versions", orphanRemoval = true)
private List<Dataset> allVersions;
......
/*
* Copyright 2018 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.catalog.service;
import org.genesys.catalog.annotations.PublishValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Interface for PublishValidation.
*
* @author Andrey Lugovskoy.
*/
public interface PublishValidationInterface {
/** The log. */
Logger LOG = LoggerFactory.getLogger(org.genesys.catalog.service.PublishValidationInterface.class);
/**
* Validation before publish.
*
* @return Map with error
*/
default Map<String, String> validation() {
final Map<String, String> errorMap = new HashMap<>();
final Class aClass = this.getClass();
Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
if (field.isAnnotationPresent(PublishValidation.class)) {
final String methodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
try {
final Method method = aClass.getMethod(methodName);
if (method.invoke(this) == null) {
errorMap.put(this.getClass().getName() + " -> " + field.getName(), "Is no filled");
} else {
field.setAccessible(true);
final Object fieldValue = field.get(this);
if (Collection.class.isAssignableFrom(fieldValue.getClass())) {
final Method size = field.getType().getMethod("size");
if ((Integer) size.invoke(fieldValue) == 0) {
errorMap.put(this.getClass().getName() + " -> " + field.getName(), "Is no filled");
} else {
if (field.getAnnotation(PublishValidation.class).innerCheck()) {
LOG.info("Field is Collection: {}", field.getName());
final List<? extends org.genesys.catalog.service.PublishValidationInterface> test = (List<? extends org.genesys.catalog.service.PublishValidationInterface>) method.invoke(this);
test.forEach(element -> {
try {
final Method myMethod = element.getClass().getDeclaredMethod("validation");
errorMap.putAll((Map<? extends String, ? extends String>) myMethod.invoke(element));
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
errorMap.put("Class " + this.getClass().getName() + " ->", " not implement" + org.genesys.catalog.service.PublishValidationInterface.class.getName());
LOG.error("You should implement {} class" + e.getMessage(), org.genesys.catalog.service.PublishValidationInterface.class.getName());
}
});
}
}
} else {
if (!field.getAnnotation(PublishValidation.class).ignoreValidation() && field.getAnnotation(PublishValidation.class).innerCheck()) {
final Method myMethod = fieldValue.getClass().getDeclaredMethod("validation");
errorMap.putAll((Map<? extends String, ? extends String>) myMethod.invoke(fieldValue));
}
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
LOG.error("Error validation model of class {}. Field {} has no getter", this.getClass().getName(), field.getName());
} catch (final ClassCastException cce) {
errorMap.put("Field class" + " ->" + field.toString(), " not implement" + org.genesys.catalog.service.PublishValidationInterface.class.getName() + "or not override validation() method");
LOG.error("You should implement {} class" + cce.getMessage(), org.genesys.catalog.service.PublishValidationInterface.class.getName());
}
}
});
return errorMap;
}
}
......@@ -17,8 +17,6 @@ package org.genesys2.server.model.impl;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.genesys.blocks.model.UuidModel;
import org.genesys.catalog.annotations.PublishValidation;
import org.genesys.catalog.service.PublishValidationInterface;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
......@@ -32,7 +30,7 @@ import java.util.Map;
*/
@Entity
@Table(name="subset_creator")
public class SubsetCreator extends UuidModel implements PublishValidationInterface {
public class SubsetCreator extends UuidModel{
/**
*
......@@ -58,35 +56,28 @@ public class SubsetCreator extends UuidModel implements PublishValidationInterfa
}
/** The full name. */
@PublishValidation
@NotNull
@Size(max = 200)
@Column(length = 200, nullable = false)
private String fullName;
/** The email. */
@PublishValidation
private String email;
/** The phone number. */
@PublishValidation
private String phoneNumber;
/** The fax. */
@PublishValidation
private String fax;
/** The institutional affiliation. */
@PublishValidation
private String institutionalAffiliation;
/** The institute address. */
@PublishValidation
private String instituteAddress;
/** The role. */
@Enumerated(EnumType.STRING)
@PublishValidation
private SubsetCreatorRole role;
/** The subset. */
......@@ -238,13 +229,4 @@ public class SubsetCreator extends UuidModel implements PublishValidationInterfa
public void setInstituteAddress(final String instituteAddress) {
this.instituteAddress = instituteAddress;
}
/*
* (non-Javadoc)
* @see org.genesys.catalog.service.PublishValidationInterface#validation()
*/
@Override
public Map<String, String> validation() {
return PublishValidationInterface.super.validation();
}
}
......@@ -18,7 +18,6 @@ package org.genesys.test.catalog.services;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import org.genesys.catalog.annotations.PublishValidationException;
import org.genesys.catalog.model.dataset.Dataset;
import org.genesys2.server.exception.InvalidApiUsageException;
import org.genesys2.server.exception.NotFoundElement;
......@@ -52,7 +51,7 @@ public class DatasetPublishingTest extends AbstractDatasetServiceTest {
}
@Test
public void testSavedDataset() throws NotFoundElement, PublishValidationException {
public void testSavedDataset() throws NotFoundElement {
assertThat(savedDataset.isPublished(), is(false));
assertThat(savedDataset.isPersisted(), is(true));
assertThat(savedDataset.getId(), greaterThan(0l));
......@@ -102,7 +101,7 @@ public class DatasetPublishingTest extends AbstractDatasetServiceTest {
}
@Test
public void testLoadDataset() throws NotFoundElement, PublishValidationException {
public void testLoadDataset() throws NotFoundElement {
Dataset loaded = datasetRepository.findByUuid(savedDataset.getUuid());
assertThat(loaded, not(nullValue()));
......
......@@ -585,8 +585,7 @@ public class DatasetServiceTest extends AbstractDatasetServiceTest {
@Test
public void testErrorPublish() {
final Dataset result = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, PublishState.DRAFT);
final Map<String, String> errorMap = result.validation();
assertThat(errorMap.size(), not(is(0)));
assertNotNull(result);
}
@Test
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment