...
 
Commits (11)
......@@ -17,6 +17,7 @@ package org.gringlobal.api.v1.impl;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.genesys.blocks.model.JsonViews;
import org.gringlobal.api.v1.ApiBaseController;
......@@ -138,4 +139,9 @@ public class AccessionController extends FilteredCRUDController<Accession, Acces
return crudService.acquire(acquisitionBatch);
}
}
\ No newline at end of file
@PostMapping(value = "/overview/{groupBy:.+}", produces = { MediaType.APPLICATION_JSON_VALUE })
@Operation(operationId = "accessionOverview", description = "Get accession statistics", summary = "Overview")
public Map<?, ?> accessionOverview(@PathVariable(name = "groupBy", required = true) String groupBy, @RequestBody AccessionFilter filter) {
return crudService.accessionOverview(groupBy, filter);
}
}
......@@ -66,6 +66,11 @@ public class AppController extends ApiBaseController {
return l10n;
}
@GetMapping(value = "/languages", produces = { MediaType.APPLICATION_JSON_VALUE })
public List<SysLang> listLanguage() {
return languageService.listAll();
}
@GetMapping(value = "/resources/{appName}/{lang}", produces = { MediaType.APPLICATION_JSON_VALUE })
public LookupMap<String, String, AppResourceInfo> appResourcesList(@PathVariable("appName") String appName, @PathVariable("lang") String lang) {
......
......@@ -207,7 +207,7 @@ public class Accession extends CooperatorOwnedModel implements ElasticLoader, El
@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
@JsonIgnore
private List<AccessionIpr> accessionIprList;
private List<AccessionIpr> accessionIprs;
@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
@JsonIgnore
......@@ -428,12 +428,12 @@ public class Accession extends CooperatorOwnedModel implements ElasticLoader, El
this.accessionActions = accessionActions;
}
public List<AccessionIpr> getAccessionIprList() {
return accessionIprList;
public List<AccessionIpr> getAccessionIprs() {
return accessionIprs;
}
public void setAccessionIprList(List<AccessionIpr> accessionIprList) {
this.accessionIprList = accessionIprList;
public void setAccessionIprs(List<AccessionIpr> accessionIprs) {
this.accessionIprs = accessionIprs;
}
public List<AccessionPedigree> getAccessionPedigrees() {
......
......@@ -19,6 +19,7 @@ import javax.persistence.*;
import org.genesys.blocks.model.Copyable;
import org.gringlobal.component.elastic.ElasticTrigger;
import org.gringlobal.custom.validation.javax.CodeValueField;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonProperty;
......@@ -46,6 +47,7 @@ public class AccessionInvName extends CooperatorOwnedModel implements ElasticTri
@Basic
@Column(name = "category_code", nullable = false, length = 20)
@CodeValueField("ACCESSION_NAME_TYPE")
private String categoryCode;
@Basic
......
......@@ -19,6 +19,8 @@ import java.util.Date;
import javax.persistence.*;
import org.gringlobal.custom.validation.javax.CodeValueField;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
......@@ -82,6 +84,7 @@ public class AccessionIpr extends CooperatorOwnedModel {
@Basic
@Column(name = "type_code", nullable = false, length = 20)
@CodeValueField("ACCESSION_RESTRICTION_TYPE")
private String typeCode;
public AccessionIpr() {
......
......@@ -22,6 +22,8 @@ import java.util.List;
import javax.persistence.*;
import org.genesys.blocks.model.Copyable;
import org.gringlobal.custom.validation.javax.CodeValueField;
import org.gringlobal.model.community.CommunityCodeValues;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
......@@ -38,18 +40,6 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class AccessionSource extends CooperatorOwnedModel implements Copyable<AccessionSource> {
private static final long serialVersionUID = 8820879032034410951L;
/**
* ACCESSION_SOURCE_TYPE code_group
*/
public static enum SourceType {
/** "COLLECTED" Collection source event */
COLLECTED,
/** "DEVELOPED" Developer source event */
DEVELOPED,
/** "DONATED" Donor source event */
DONATED,
}
/**
* ACCESSION_SOURCE_HABITAT_TYPE code_group
*/
......@@ -145,10 +135,12 @@ public class AccessionSource extends CooperatorOwnedModel implements Copyable<Ac
@Basic
@Column(name = "source_type_code", nullable = false, length = 20)
@CodeValueField(CommunityCodeValues.ACCESSION_SOURCE_TYPE)
private String sourceTypeCode;
@Basic
@Column(name = "acquisition_source_code", length = 20)
@CodeValueField("ACCESSION_SOURCE_HABITAT_TYPE")
private String acquisitionSource;
@Basic
......@@ -158,6 +150,7 @@ public class AccessionSource extends CooperatorOwnedModel implements Copyable<Ac
@Basic
@Column(name = "collected_form_code", length = 20)
@CodeValueField(CommunityCodeValues.GERMPLASM_FORM)
private String collectedFormCode;
@Basic
......@@ -194,6 +187,7 @@ public class AccessionSource extends CooperatorOwnedModel implements Copyable<Ac
@Basic
@Column(name = "georeference_protocol_code", length = 20)
@CodeValueField("GEOREFERENCE_PROTOCOL")
private String georeferenceProtocolCode;
@Basic
......@@ -229,6 +223,7 @@ public class AccessionSource extends CooperatorOwnedModel implements Copyable<Ac
@Basic
@Column(name = "source_date_code", length = 20)
@CodeValueField(CommunityCodeValues.DATE_FORMAT)
private String sourceDateCode;
@Basic
......@@ -236,6 +231,7 @@ public class AccessionSource extends CooperatorOwnedModel implements Copyable<Ac
@Basic
@Column(name = "unit_quantity_collected_code", length = 20)
@CodeValueField(CommunityCodeValues.UNIT_OF_QUANTITY)
private String unitQuantityCollectedCode;
@JsonIgnore
......
......@@ -34,6 +34,20 @@ public abstract class CommunityCodeValues {
public static final String UNIT_OF_QUANTITY = "UNIT_OF_QUANTITY";
public static final CodeValueDef UNIT_OF_QUANTITY_SEED;
public static final String ACCESSION_SOURCE_TYPE = "ACCESSION_SOURCE_TYPE";
public static final CodeValueDef ACCESSION_SOURCE_TYPE_COLLECTED;
public static final CodeValueDef ACCESSION_SOURCE_TYPE_DEVELOPED;
public static final CodeValueDef ACCESSION_SOURCE_TYPE_DONATED;
public static final String ACCESSION_NAME_TYPE = "ACCESSION_NAME_TYPE";
public static final CodeValueDef ACCESSION_NAME_TYPE_COLLECTOR;
public static final CodeValueDef ACCESSION_NAME_TYPE_CULTIVAR;
public static final CodeValueDef ACCESSION_NAME_TYPE_DONOR;
public static final CodeValueDef ACCESSION_NAME_TYPE_DEVELOPER;
public static final String ACCESSION_RESTRICTION_TYPE = "ACCESSION_RESTRICTION_TYPE";
public static final CodeValueDef ACCESSION_RESTRICTION_TYPE_SMTA;
public static final String INVENTORY_AVAILABILITY_STATUS = "INVENTORY_AVAILABILITY_STATUS";
public static final CodeValueDef INVENTORY_AVAILABILITY_LOWINVENTORY;
......@@ -67,6 +81,20 @@ public abstract class CommunityCodeValues {
// Date formats
DATE_FORMAT_DATETIME = new CodeValueDef(DATE_FORMAT, "yyyy-MM-dd HH:mm", "Date and time", "yyyy-MM-dd HH:mm");
DATE_FORMAT_DATE = new CodeValueDef(DATE_FORMAT, "yyyy-MM-dd", "Date", "yyyy-MM-dd");
// Accession source type
ACCESSION_SOURCE_TYPE_COLLECTED = new CodeValueDef(ACCESSION_SOURCE_TYPE, "COLLECTED", "Collection source event", null);
ACCESSION_SOURCE_TYPE_DEVELOPED = new CodeValueDef(ACCESSION_SOURCE_TYPE, "DEVELOPED", "Developer source event", null);
ACCESSION_SOURCE_TYPE_DONATED = new CodeValueDef(ACCESSION_SOURCE_TYPE, "DONATED", "Donor source event", null);
// Accession name types
ACCESSION_NAME_TYPE_COLLECTOR = new CodeValueDef(ACCESSION_NAME_TYPE, "COLLECTOR", "Collector identifier", null);
ACCESSION_NAME_TYPE_CULTIVAR = new CodeValueDef(ACCESSION_NAME_TYPE, "CULTIVAR", "Cultivar name", null);
ACCESSION_NAME_TYPE_DONOR = new CodeValueDef(ACCESSION_NAME_TYPE, "DONOR", "Donor identifier", null);
ACCESSION_NAME_TYPE_DEVELOPER = new CodeValueDef(ACCESSION_NAME_TYPE, "DEVELOPER", "Developer identifier", null);
// Accession IPR types
ACCESSION_RESTRICTION_TYPE_SMTA = new CodeValueDef(ACCESSION_RESTRICTION_TYPE, "MTA-SMTA", "FAO Standard Material Transfer Agreement", null);
// Inventory availability
INVENTORY_AVAILABILITY_LOWINVENTORY = new CodeValueDef(INVENTORY_AVAILABILITY_STATUS, "LOW", "Low inventory", null);
......
......@@ -16,6 +16,7 @@
package org.gringlobal.service;
import java.util.List;
import java.util.Map;
import org.gringlobal.model.*;
import org.gringlobal.service.filter.AccessionFilter;
......@@ -67,4 +68,13 @@ public interface AccessionService extends FilteredCRUDService<Accession, Accessi
public String availabilityStatusCode = "NOT-SET"; // default
}
/**
* Accession overview.
*
* @param group Group by property of Accession
* @param filter the accession filters
* @return the map with statistics
*/
Map<Object, Number> accessionOverview(String group, AccessionFilter filter);
}
......@@ -15,6 +15,8 @@
*/
package org.gringlobal.service;
import java.util.List;
import org.gringlobal.model.SysLang;
/**
......@@ -30,4 +32,11 @@ public interface LanguageService extends CRUDService<SysLang> {
*/
SysLang getLanguage(String lang);
/**
* Fetch all system languages
*
* @return list
*/
List<SysLang> listAll();
}
......@@ -98,6 +98,9 @@ public class AccessionFilter extends CooperatorOwnedModelFilter<AccessionFilter,
/** The inventory filter. */
public InventoryFilter inventories;
/** Accession sources */
public AccessionSourceFilter sources;
/**
* Builds the query.
*
......@@ -175,6 +178,10 @@ public class AccessionFilter extends CooperatorOwnedModelFilter<AccessionFilter,
predicates.add(accession.inventories.isNotEmpty());
predicates.addAll(inventories.collectPredicates(accession.inventories.any()));
}
if (sources != null) {
predicates.add(accession.accessionSources.isNotEmpty());
predicates.addAll(sources.collectPredicates(accession.accessionSources.any()));
}
return predicates;
}
......
/*
* 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.service.filter;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.gringlobal.model.AccessionInvGroup;
import org.gringlobal.model.AccessionSource;
import org.gringlobal.model.QAccessionSource;
import com.querydsl.core.types.Predicate;
/**
* Filters for {@link AccessionInvGroup}
*/
public class AccessionSourceFilter extends CooperatorOwnedModelFilter<AccessionSourceFilter, AccessionSource> implements Serializable {
private static final long serialVersionUID = 8959999560169507323L;
/** sourceTypeCodes */
public Set<String> sourceTypeCode;
/** acquisitionSource */
public Set<String> acquisitionSource;
/** Origin */
public Boolean origin;
/** Geography */
public GeographyFilter geography;
/**
* Builds the query.
*
* @return the predicate
*/
@Override
public List<Predicate> collectPredicates() {
return collectPredicates(QAccessionSource.accessionSource);
}
/**
* Builds the query.
*
* @param accessionSource the accession source
* @return the predicate
*/
public List<Predicate> collectPredicates(QAccessionSource accessionSource) {
final List<Predicate> predicates = super.collectPredicates(accessionSource, accessionSource._super);
if (CollectionUtils.isNotEmpty(sourceTypeCode)) {
predicates.add(accessionSource.sourceTypeCode.in(sourceTypeCode));
}
if (CollectionUtils.isNotEmpty(acquisitionSource)) {
predicates.add(accessionSource.acquisitionSource.in(acquisitionSource));
}
if (origin != null) {
predicates.add(accessionSource.isOrigin.eq(origin ? "Y" : "N"));
}
if (geography != null) {
predicates.addAll(geography.collectPredicates(accessionSource.geography));
}
return predicates;
}
}
......@@ -20,6 +20,8 @@ import java.io.Serializable;
import java.util.List;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.model.filters.DateFilter;
import org.genesys.blocks.model.filters.StringFilter;
import org.gringlobal.model.Geography;
......@@ -32,6 +34,9 @@ public class GeographyFilter extends CooperatorOwnedModelFilter<GeographyFilter,
private static final long serialVersionUID = 2722353492694556448L;
/** Any text. */
public String _text;
/** The adm1. */
public StringFilter adm1;
......@@ -147,6 +152,12 @@ public class GeographyFilter extends CooperatorOwnedModelFilter<GeographyFilter,
if (changedDate != null) {
predicates.add(changedDate.buildQuery(geography.changedDate));
}
if (StringUtils.isNotBlank(_text)) {
String likeString = _text + "%";
BooleanExpression expression = geography.adm1.like(likeString).or(geography.adm2.like(likeString))
.or(geography.adm3.like(likeString)).or(geography.adm4.like(likeString)).or(geography.countryCode.like(likeString));
predicates.add(expression);
}
return predicates;
}
......
......@@ -15,12 +15,18 @@
*/
package org.gringlobal.service.impl;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.genesys.blocks.model.filters.EmptyModelFilter;
import org.gringlobal.api.InvalidApiUsageException;
import org.gringlobal.api.NotFoundElement;
import org.gringlobal.custom.elasticsearch.SearchException;
......@@ -43,13 +49,22 @@ import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.CollectionExpression;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BeanPath;
import com.querydsl.core.types.dsl.CollectionPathBase;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.jpa.impl.JPAQuery;
@Service
......@@ -226,7 +241,7 @@ public class AccessionServiceImpl extends FilteredCRUDServiceImpl<Accession, Acc
// initialize lazy data
Hibernate.initialize(accession.getAccessionSources());
Hibernate.initialize(accession.getAccessionActions());
Hibernate.initialize(accession.getAccessionIprList());
Hibernate.initialize(accession.getAccessionIprs());
Hibernate.initialize(accession.getAccessionPedigrees());
Hibernate.initialize(accession.getAccessionQuarantines());
Hibernate.initialize(accession.getCitations());
......@@ -235,7 +250,7 @@ public class AccessionServiceImpl extends FilteredCRUDServiceImpl<Accession, Acc
accessionDetails.accession = accession;
accessionDetails.sources = accession.getAccessionSources();
accessionDetails.actions = accession.getAccessionActions();
accessionDetails.ipr = accession.getAccessionIprList();
accessionDetails.ipr = accession.getAccessionIprs();
accessionDetails.pedigree = accession.getAccessionPedigrees();
accessionDetails.quarantine = accession.getAccessionQuarantines();
accessionDetails.citations = accession.getCitations();
......@@ -296,4 +311,165 @@ public class AccessionServiceImpl extends FilteredCRUDServiceImpl<Accession, Acc
group = accessionInvGroupService.addMembers(group, inventories, null);
return group;
}
@Override
public Map<Object, Number> accessionOverview(String group, AccessionFilter filter) {
if (filter.isFulltextQuery()) {
// FIXME
return null;
}
JPAQuery<?> query = jpaQueryFactory.from(QAccession.accession);
PathBuilder<Object> groupBy;
// fields
String[] groups = group.strip().split("\\.");
Object root = QAccession.accession;
Object currentFilter = filter;
PathBuilder<?> sourceProp = new PathBuilder<>(Accession.class, QAccession.accession.getMetadata());
String currentPath = "";
String lookupField = group;
for (int i = 0; i < groups.length - 1; i++) { // except the last path element
String fieldName = groups[i];
currentPath += fieldName + ".";
LOG.debug("Looking for {} currentPath={}", fieldName, currentPath);
try {
Field field = root.getClass().getField(fieldName);
LOG.debug("Found {} {}", field.getType(), field.getName());
if (BeanPath.class.isAssignableFrom(field.getType())) {
LOG.debug("{} is an entity", fieldName);
// No join, but change root
root = field.get(root);
// Must not change the lookup path!
} else if (CollectionPathBase.class.isAssignableFrom(field.getType())) {
LOG.debug("{} is a collection type, must join", fieldName);
// Figure out what it is
ResolvableType t1 = ResolvableType.forField(field);
Class<?> entityType = t1.resolveGeneric(0); // entity type
Class<?> qdslType = t1.resolveGeneric(1); // it's querydsl counterpart
LOG.debug("Got {} and {} for {}", entityType.getName(), qdslType.getName(), field);
// Join
Path<?> path = (Path<?>) qdslType.getDeclaredConstructor(String.class).newInstance("joined" + i);
joinQuery(query, entityType, qdslType, (CollectionExpression<?, ?>) field.get(root), path);
// Change root
root = path;
// Apply any filters on the join path, not on query root
// Is there a filter field for this entity?
Field pathFilterField = findPathFilter(fieldName, entityType);
// We found a matching filter, now apply filters on join path
if (pathFilterField != null) {
// If filter has values, skip otherwise
Object filterObj = pathFilterField.get(currentFilter);
if (filterObj != null) {
// We have an entity filter with some values
EmptyModelFilter<?, ?> emf = EmptyModelFilter.class.cast(filterObj);
LOG.warn("Found the filter for {} with values! {}", pathFilterField, emf.getClass().getName());
// Apply filter on path
java.lang.reflect.Method collectPredicates = emf.getClass().getMethod("collectPredicates", qdslType);
// Invoke the `collectPredicates(Q...)` method on join path
if (collectPredicates != null) {
Collection<Predicate> predicates = (Collection<Predicate>) collectPredicates.invoke(emf, path);
LOG.trace("Got", predicates);
query.where(ExpressionUtils.allOf(predicates));
// Clear accession filter for this property
pathFilterField.set(currentFilter, null);
} else {
LOG.warn("No collectPredicates method for {} on {}", qdslType.getName(), emf.getClass().getName());
}
} else {
LOG.trace("Found the filter for {} but it's null. {}", pathFilterField, entityType.getName());
}
}
// update lookup
sourceProp = new PathBuilder<>(entityType, "joined" + i);
LOG.debug("Changing lookup from {} to {}", lookupField, group.substring(currentPath.length()));
lookupField = group.substring(currentPath.length());
} else {
LOG.debug("{} is a regular path", fieldName);
// Must not change the lookup path!
// Should never reach here.
throw new InvalidApiUsageException("Invalid field '" + fieldName + "' in path " + group);
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
LOG.error("Field '{}' not found in {} for path {}: {}", fieldName, root.getClass().getName(), group, e.getMessage(), e);
throw new InvalidApiUsageException("Field '" + fieldName + "' not found in " + root.getClass().getName() + " for path " + group, e);
}
}
LOG.debug("Using field {} for {}", lookupField, group);
groupBy = sourceProp.get(lookupField);
if (filter != null) {
query.where(filter.buildPredicate());
}
JPAQuery<Tuple> select = query.select(groupBy, QAccession.accession.id.count()).groupBy(groupBy);
Map<Object, Number> results = new HashMap<>();
select.fetch().forEach(t -> {
Object key = t.get(0, Object.class);
results.put(key == null ? "NULL" : key, t.get(1, Number.class));
});
return results;
}
/**
* Find the entity filter field of specified type in AccessionFilter
*/
private Field findPathFilter(String fieldName, Class<?> entityType) throws IllegalArgumentException, IllegalAccessException {
for (Field filterField : AccessionFilter.class.getFields()) {
// Must be a model filter
if (EmptyModelFilter.class.isAssignableFrom(filterField.getType())) {
ResolvableType filterType = ResolvableType.forClass(EmptyModelFilter.class, filterField.getType());
Class<?> gen0 = filterType.resolveGeneric(0);
Class<?> gen1 = filterType.resolveGeneric(1);
LOG.warn("Looking at {} as subfilter {} {}", filterField, gen0, gen1);
// If the filter is for the specified type
if (gen1 != null && gen1.equals(entityType)) {
if (! filterField.getName().equalsIgnoreCase(fieldName)) {
LOG.warn("Potential filter mismatch between {} and {}!", filterField.getName(), fieldName);
// TODO We have multiple SiteFilters in AccessionFilter. Need the right one!
}
return filterField;
}
} else {
// LOG.trace("Not a sub-filter {} {}", filterField, filterField.getType().getName());
}
}
return null;
}
@SuppressWarnings("unchecked")
private <A, E> void joinQuery(JPAQuery<?> query, Class<?> entityType, Class<E> qdslType, CollectionExpression<?, ?> collectionPath, Path<?> alias)
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
query.join((CollectionExpression<?, E>) collectionPath, (Path<E>) alias);
}
}
......@@ -60,4 +60,8 @@ public class LanguageServiceImpl extends CRUDServiceImpl<SysLang, SysLangReposit
return sysLang;
}
@Override
public List<SysLang> listAll() {
return repository.findAll();
}
}
......@@ -37,6 +37,7 @@ import org.gringlobal.model.TaxonomyCropMap;
import org.gringlobal.model.TaxonomyFamily;
import org.gringlobal.model.TaxonomyGenus;
import org.gringlobal.model.TaxonomySpecies;
import org.gringlobal.model.community.CommunityCodeValues;
import org.gringlobal.persistence.AccessionRepository;
import org.gringlobal.persistence.GeographyRepository;
import org.gringlobal.persistence.SiteRepository;
......@@ -398,10 +399,10 @@ public class GenesysDownloader implements InitializingBean {
if (donorWiews != null || donorName != null) {
sources = getOrCreateAccessionSources(a);
AccessionSource donorSource = sources.stream().filter((source) -> source.getSourceTypeCode() == AccessionSource.SourceType.DONATED.name()).findFirst().orElse(null);
AccessionSource donorSource = sources.stream().filter((source) -> source.getSourceTypeCode() == CommunityCodeValues.ACCESSION_SOURCE_TYPE_DONATED.value).findFirst().orElse(null);
if (donorSource == null) {
donorSource = new AccessionSource();
donorSource.setSourceTypeCode(AccessionSource.SourceType.DONATED.name());
donorSource.setSourceTypeCode(CommunityCodeValues.ACCESSION_SOURCE_TYPE_DONATED.value);
donorSource.setAccession(a);
sources.add(donorSource);
}
......@@ -419,10 +420,10 @@ public class GenesysDownloader implements InitializingBean {
ObjectNode nodeGeo = acce.hasNonNull("geo") ? (ObjectNode) acce.get("geo") : null;
if (origCty != null || nodeGeo != null || nodeCollecting != null) {
sources = getOrCreateAccessionSources(a);
AccessionSource collectingSource = sources.stream().filter((source) -> source.getSourceTypeCode() == AccessionSource.SourceType.COLLECTED.name()).findFirst().orElse(null);
AccessionSource collectingSource = sources.stream().filter((source) -> source.getSourceTypeCode() == CommunityCodeValues.ACCESSION_SOURCE_TYPE_COLLECTED.value).findFirst().orElse(null);
if (collectingSource == null) {
collectingSource = new AccessionSource();
collectingSource.setSourceTypeCode(AccessionSource.SourceType.COLLECTED.name());
collectingSource.setSourceTypeCode(CommunityCodeValues.ACCESSION_SOURCE_TYPE_COLLECTED.value);
collectingSource.setAccession(a);
sources.add(collectingSource);
}
......
......@@ -360,8 +360,8 @@ public class UsdaTaxonomyUpdater {
TaxonomyAuthor author = new TaxonomyAuthor();
author.setShortName(authorRow.getShortName());
if (author.getFullName() == null) {
LOG.warn("Missing fullName id={}", authorRow.getTaxonomyAuthorId());
if (author.getShortName() == null) {
LOG.warn("Missing shortName id={}", authorRow.getTaxonomyAuthorId());
continue;
}
......@@ -380,9 +380,9 @@ public class UsdaTaxonomyUpdater {
if (narrow.size() == 1) {
author = narrow.get(0);
} else if (narrow.size() == 0) {
LOG.debug("{} matches found for {}! Will create new entry.", narrow.size(), author.getFullName());
LOG.debug("{} matches found for {}! Will create new entry.", narrow.size(), author.getShortName());
} else {
throw new InvalidApiUsageException("This shouldn't happen, your taxonomy_author needs cleaning: " + author.getFullName());
throw new InvalidApiUsageException("This shouldn't happen, your taxonomy_author needs cleaning: " + author.getShortName());
}
}
......
......@@ -194,6 +194,25 @@ public class AppControllerTest extends AbstractApiV1Test {
/*@formatter:on*/
}
@Test
public void listAllLanguagesTest() throws Exception {
long count = sysLangRepository.count();
assertThat(count, greaterThan(0L));
/*@formatter:off*/
mockMvc
.perform(get(AppController.API_URL.concat("/languages"))
.contentType(MediaType.APPLICATION_JSON))
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$", hasSize((int) count)))
;
/*@formatter:on*/
}
@Test
public void codeListByLangTest() throws Exception {
codeValueLangRepository.deleteAll();
......
......@@ -168,7 +168,7 @@ public class InventoryControllerTest extends AbstractApiV1Test {
.contentType(MediaType.APPLICATION_JSON)
.content(verboseMapper.writeValueAsString(quantity))
)
.andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
;
/*@formatter:on*/
......@@ -226,7 +226,7 @@ public class InventoryControllerTest extends AbstractApiV1Test {
.contentType(MediaType.APPLICATION_JSON)
.content(verboseMapper.writeValueAsString(quantity))
)
.andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
;
/*@formatter:on*/
......
......@@ -15,22 +15,13 @@
*/
package org.gringlobal.test.api.v1;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.google.common.collect.Sets;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.persistence.OAuthClientRepository;
import org.genesys.blocks.oauth.service.OAuthClientDetailsService;
......@@ -43,9 +34,10 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Sets;
/**
* @author Maxym Borodenko
*/
......@@ -87,8 +79,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
.perform(post(OAuthManagementController.API_URL + "/filter")
.contentType(MediaType.APPLICATION_JSON)
.content(verboseMapper.writeValueAsString(filter)))
.andDo(MockMvcResultHandlers.print())
.andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.content", hasSize(1)))
......@@ -108,7 +99,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
.perform(post(OAuthManagementController.API_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(verboseMapper.writeValueAsString(client)))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$", notNullValue()))
......@@ -141,7 +132,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
.perform(put(OAuthManagementController.API_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(verboseMapper.writeValueAsString(client)))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$", notNullValue()))
......@@ -167,7 +158,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
mockMvc
.perform(delete(OAuthManagementController.API_URL + OAuthManagementController.ENDPOINT_CLIENT_ID, client.getClientId())
.contentType(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
;
......@@ -185,7 +176,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
mockMvc
.perform(post(OAuthManagementController.API_URL + "/{clientId}/secret", client.getClientId())
.contentType(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$").isString())
......@@ -203,7 +194,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
mockMvc
.perform(delete(OAuthManagementController.API_URL + "/{clientId}/secret", client.getClientId())
.contentType(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(jsonPath("$", notNullValue()))
.andExpect(jsonPath("$.clientSecret", nullValue()))
......@@ -222,7 +213,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
mockMvc
.perform(get(OAuthManagementController.API_URL + OAuthManagementController.ENDPOINT_CLIENT_ID, client.getClientId())
.contentType(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$", notNullValue()))
......@@ -243,7 +234,7 @@ public class OAuthManagementControllerTest extends AbstractApiV1Test {
mockMvc
.perform(get(OAuthManagementController.API_URL + OAuthManagementController.ENDPOINT_CLIENT_ID, "notExistingClientId")
.contentType(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
// .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())
.andExpect(status().isNotFound())
;
/*@formatter:on*/
......
......@@ -179,12 +179,12 @@ public abstract class AbstractServicesTest extends AbstractServiceTest {
}
protected AccessionSource addAccessionSourceToDB(Accession accession) {
return addAccessionSourceToDB(accession, AccessionSource.SourceType.COLLECTED);
return addAccessionSourceToDB(accession, CommunityCodeValues.ACCESSION_SOURCE_TYPE_COLLECTED.value);
}
protected AccessionSource addAccessionSourceToDB(Accession accession, AccessionSource.SourceType type) {
protected AccessionSource addAccessionSourceToDB(Accession accession, String sourceTypeCode) {
AccessionSource source = new AccessionSource();
source.setSourceTypeCode(type.name());
source.setSourceTypeCode(sourceTypeCode);
source.setAccession(accession);
return accessionSourceRepository.save(source);
......@@ -211,7 +211,7 @@ public abstract class AbstractServicesTest extends AbstractServiceTest {
protected AccessionIpr addAccessionIprToDB(Accession accession) {
AccessionIpr ipr = new AccessionIpr();
ipr.setAccession(accession);
ipr.setTypeCode("TypeCode");
ipr.setTypeCode(CommunityCodeValues.ACCESSION_RESTRICTION_TYPE_SMTA.value);
return accessionIprRepository.save(ipr);
}
......@@ -297,7 +297,7 @@ public abstract class AbstractServicesTest extends AbstractServiceTest {
AccessionInvName invName = new AccessionInvName();
invName.setPlantName(plantName);
invName.setIsWebVisible(TRUE);
invName.setCategoryCode("Category code");
invName.setCategoryCode(CommunityCodeValues.ACCESSION_NAME_TYPE_DEVELOPER.value);
invName.setInventory(inventory);
return accessionInvNameRepository.save(invName);
......
......@@ -26,6 +26,7 @@ import org.apache.commons.lang3.RandomUtils;
import org.gringlobal.api.InvalidApiUsageException;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.*;
import org.gringlobal.model.community.CommunityCodeValues;
import org.gringlobal.persistence.AccessionInvGroupMapRepository;
import org.gringlobal.persistence.AccessionInvGroupRepository;
import org.gringlobal.service.AccessionInvGroupService;
......@@ -137,7 +138,7 @@ public class AccessionServiceTest extends AbstractServicesTest {
// create AccessionSource
AccessionSource source = new AccessionSource();
source.setSourceTypeCode(AccessionSource.SourceType.COLLECTED.name());
source.setSourceTypeCode(CommunityCodeValues.ACCESSION_SOURCE_TYPE_COLLECTED.value);
source.setAccession(accession);
// add AccessionSource to accession
......@@ -162,7 +163,7 @@ public class AccessionServiceTest extends AbstractServicesTest {
// create AccessionSource
AccessionSource source = new AccessionSource();
source.setSourceTypeCode(AccessionSource.SourceType.COLLECTED.name());
source.setSourceTypeCode(CommunityCodeValues.ACCESSION_SOURCE_TYPE_COLLECTED.value);
source.setAccession(a);
// add AccessionSource to accession
......@@ -308,7 +309,7 @@ public class AccessionServiceTest extends AbstractServicesTest {
acquisitionBatch.inventoryNumberPart1 = "INTRO";
acquisitionBatch.siteId = 1;
acquisitionBatch.inventoryMaintenancePolicyId = maintPolicy.getId();
acquisitionBatch.availabilityStatusCode = "AVAIL";
acquisitionBatch.availabilityStatusCode = CommunityCodeValues.INVENTORY_AVAILABILITY_AVAILABLE.value;
acquisitionBatch.accessions = new ArrayList<>();
for (int i = 0; i < 10; i++) {
......@@ -319,11 +320,11 @@ public class AccessionServiceTest extends AbstractServicesTest {
accession.setTaxonomySpecies(new TaxonomySpecies(taxonomySpecies.getId()));
List<AccessionInvName> names = Lists.newArrayList(new AccessionInvName(), new AccessionInvName(), new AccessionInvName());
names.get(0).setCategoryCode("DEVELOPER");
names.get(0).setCategoryCode(CommunityCodeValues.ACCESSION_NAME_TYPE_DEVELOPER.value);
names.get(0).setPlantName("Developed " + (i+1));
names.get(1).setCategoryCode("COLLECTOR");
names.get(1).setCategoryCode(CommunityCodeValues.ACCESSION_NAME_TYPE_COLLECTOR.value);
names.get(1).setPlantName("COLL " + (RandomUtils.nextInt(100, 99999)));
names.get(2).setCategoryCode("DONOR");
names.get(2).setCategoryCode(CommunityCodeValues.ACCESSION_NAME_TYPE_DONOR.value);
names.get(2).setPlantName("TZm-" + (RandomUtils.nextInt(100, 99999)));
accession.setNames(names);
......@@ -332,7 +333,7 @@ public class AccessionServiceTest extends AbstractServicesTest {
acquisitionBatch.sources = new ArrayList<>();
AccessionSource source = new AccessionSource();
source.setSourceTypeCode("DONATED");
source.setSourceTypeCode(CommunityCodeValues.ACCESSION_SOURCE_TYPE_DONATED.value);
source.setSourceDate(new Date());
source.setSourceDateCode("YYYY-MM-DD");
List<Cooperator> cooperators = Lists.newArrayList(new Cooperator(1l), new Cooperator(2l));
......@@ -341,7 +342,7 @@ public class AccessionServiceTest extends AbstractServicesTest {
// Source 2
source = new AccessionSource();
source.setSourceTypeCode("DEVELOPED");
source.setSourceTypeCode(CommunityCodeValues.ACCESSION_SOURCE_TYPE_DEVELOPED.value);
source.setSourceDate(new Date());
source.setSourceDateCode("YYYY-MM-DD");
cooperators = Lists.newArrayList(new Cooperator(3l));
......
......@@ -33,6 +33,7 @@ log4j.category.org.gringlobal=info
#log4j.category.org.gringlobal.spring=trace
log4j.category.org.gringlobal.custom.elasticsearch=warn
log4j.category.org.gringlobal.service.impl.ElasticsearchServiceImpl=warn
log4j.category.org.gringlobal.service.impl.CodeValueServiceImpl=warn
log4j.category.org.springframework.web.client=trace
log4j.category.org.elasticsearch.client=error
......