diff --git a/pom.xml b/pom.xml index 5c381c028a97064747b9ff4588677fe49258b7e5..1848a0c72cfc4d5fbc1c03c1b44f5e48271d7560 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,7 @@ 4.1.4 4.3.11.Final - 2.3.3 + 2.3.6 2.7.4 1.7.21 @@ -268,6 +268,13 @@ ${spring-data-jpa.version} + + org.springframework.security + spring-security-test + ${spring.security.version} + test + + com.querydsl querydsl-jpa @@ -646,12 +653,8 @@ 2.19.1 once - -Xms512m -Xmx1024m + -Xms512m -Xmx1024m -server false - - - *.docs.*Test.java - @@ -864,6 +867,10 @@ true + + src/test/resources + true + ${project.build.directory}/generated-resources false diff --git a/src/main/java/org/genesys/catalog/api/v0/DatasetController.java b/src/main/java/org/genesys/catalog/api/v0/DatasetController.java index 22daae62611fdf87e4dc5306597deeeaf485cbde..413439f3ce7ce4293b0409c081d3274a7fce8ef7 100644 --- a/src/main/java/org/genesys/catalog/api/v0/DatasetController.java +++ b/src/main/java/org/genesys/catalog/api/v0/DatasetController.java @@ -61,7 +61,7 @@ import io.swagger.annotations.Api; public class DatasetController { // Rest controller base URL - protected static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/dataset"; + public static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/dataset"; private static final Logger LOG = LoggerFactory.getLogger(DatasetController.class); diff --git a/src/main/java/org/genesys/catalog/api/v0/DatasetCreatorController.java b/src/main/java/org/genesys/catalog/api/v0/DatasetCreatorController.java index 83dd7b23285b531ce963cf2085a44993d860bb88..3890d20d62fe658809347f8c0d425aa34d4c6a22 100644 --- a/src/main/java/org/genesys/catalog/api/v0/DatasetCreatorController.java +++ b/src/main/java/org/genesys/catalog/api/v0/DatasetCreatorController.java @@ -49,7 +49,7 @@ import java.util.UUID; public class DatasetCreatorController { /** The Constant API_BASE. */ - protected static final String CONTROLLER_URL = DatasetController.CONTROLLER_URL + "/{UUID}/datasetcreator"; + public static final String CONTROLLER_URL = DatasetController.CONTROLLER_URL + "/{UUID}/datasetcreator"; /** The dataset service. */ @Autowired diff --git a/src/main/java/org/genesys/catalog/api/v0/DescriptorController.java b/src/main/java/org/genesys/catalog/api/v0/DescriptorController.java index 7eef6cdc9da21a5237f5f189585f72601217df42..c465092536a0155927d552e23cda2f6633cbb19c 100644 --- a/src/main/java/org/genesys/catalog/api/v0/DescriptorController.java +++ b/src/main/java/org/genesys/catalog/api/v0/DescriptorController.java @@ -116,7 +116,7 @@ public class DescriptorController { * @throws IOException */ @PostMapping(value = "/list") - public FilteredPage listDescriptorsByFilter(@RequestParam(name = "p", required = false, defaultValue = "0") final int page, + public FilteredPage listDescriptors(@RequestParam(name = "p", required = false, defaultValue = "0") final int page, @RequestParam(name = "l", required = false, defaultValue = "50") final int pageSize, @RequestParam(name = "d", required = false, defaultValue = "ASC") final Sort.Direction direction, @RequestParam(name = "s", required = false, defaultValue = "id") final String[] sort, @@ -141,7 +141,7 @@ public class DescriptorController { * @param filterCode the filter code * @return the filtered page * @throws IOException Signals that an I/O exception has occurred. - * @deprecated Use {@link #listDescriptorsByFilter(int, int, org.springframework.data.domain.Sort.Direction, String[], DescriptorFilter)} + * @deprecated Use {@link #listDescriptors(int, int, org.springframework.data.domain.Sort.Direction, String[], DescriptorFilter)} */ @PostMapping(value = "/list/{filterCode}") public FilteredPage listDescriptorsByShort(@RequestParam(name = "p", required = false, defaultValue = "0") final int page, diff --git a/src/main/java/org/genesys/catalog/mvc/DescriptorListExporter.java b/src/main/java/org/genesys/catalog/mvc/DescriptorListExporter.java index 4ee82efaab48d0bb89fd1d6ff8e8a767c3ca43cb..f12c2260df5ce1c6cc9b54c092920df84607d2b8 100644 --- a/src/main/java/org/genesys/catalog/mvc/DescriptorListExporter.java +++ b/src/main/java/org/genesys/catalog/mvc/DescriptorListExporter.java @@ -41,7 +41,7 @@ import java.util.Map; public class DescriptorListExporter { @Autowired - private FreemarkerTemplating freemarker; + private FreemarkerTemplating freemarkerTemplating; /** The Constant OPTIONS. */ /*@formatter:off*/ @@ -75,7 +75,7 @@ public class DescriptorListExporter { public String markdownDescriptorList(final DescriptorList descriptorList) throws FreemarkerException { final Map root = new HashMap<>(); root.put("descriptorList", descriptorList); - return freemarker.processTemplateResource("descriptorlist/booklet.ftl", root); + return freemarkerTemplating.processTemplateResource("descriptorlist/booklet.ftl", root); } /** @@ -88,7 +88,7 @@ public class DescriptorListExporter { public String htmlDescriptorList(final DescriptorList descriptorList) throws FreemarkerException { final Map root = new HashMap<>(); root.put("descriptorList", descriptorList); - final String markdown = freemarker.processTemplateResource("descriptorlist/booklet.ftl", root); + final String markdown = freemarkerTemplating.processTemplateResource("descriptorlist/booklet.ftl", root); // System.err.println(markdown); final Parser parser = Parser.builder(OPTIONS).build(); @@ -103,7 +103,7 @@ public class DescriptorListExporter { root.put("author", StringUtils.defaultIfEmpty(descriptorList.getPublisher(), descriptorList.getOwner().getName())); root.put("html", html); - return freemarker.processTemplateResource("html.ftl", root); + return freemarkerTemplating.processTemplateResource("html.ftl", root); } } diff --git a/src/main/java/org/genesys/catalog/service/impl/DatasetServiceImpl.java b/src/main/java/org/genesys/catalog/service/impl/DatasetServiceImpl.java index 077879c72cb0748ab8627b0e9bce7c65edce93a6..c523cdec3f94dab19c8494688c2b3a8c0f6a0f44 100644 --- a/src/main/java/org/genesys/catalog/service/impl/DatasetServiceImpl.java +++ b/src/main/java/org/genesys/catalog/service/impl/DatasetServiceImpl.java @@ -79,7 +79,7 @@ public class DatasetServiceImpl implements DatasetService { /** The file repo service. */ @Autowired - private RepositoryService fileRepoService; + private RepositoryService repositoryService; @Autowired private CustomAclService aclService; @@ -304,7 +304,7 @@ public class DatasetServiceImpl implements DatasetService { InvalidRepositoryFileDataException { dataset = datasetRepository.findByUuidAndVersion(dataset.getUuid(), dataset.getVersion()); - final RepositoryFile repositoryFile = fileRepoService.addFile(Paths.get(datasetRepositoryPath, dataset.getUuid().toString()).toAbsolutePath().toString(), file + final RepositoryFile repositoryFile = repositoryService.addFile(Paths.get(datasetRepositoryPath, dataset.getUuid().toString()).toAbsolutePath().toString(), file .getOriginalFilename(), file.getContentType(), file.getBytes(), null); dataset.getRepositoryFiles().add(repositoryFile); return lazyLoad(datasetRepository.save(dataset)); @@ -320,7 +320,7 @@ public class DatasetServiceImpl implements DatasetService { if (datasetFile == null) { throw new NotFoundElement("No such dataset file"); } - final RepositoryFile updated = fileRepoService.updateMetadata(metadata); + final RepositoryFile updated = repositoryService.updateMetadata(metadata); // replace it dataset.getRepositoryFiles().replaceAll(df -> df.getUuid().equals(datasetFile.getUuid()) ? updated : df); return lazyLoad(dataset); @@ -335,9 +335,9 @@ public class DatasetServiceImpl implements DatasetService { public Dataset removeDatasetFile(Dataset dataset, final UUID fileUuid) throws NotFoundElement, NoSuchRepositoryFileException, IOException { dataset = datasetRepository.findByUuidAndVersion(dataset.getUuid(), dataset.getVersion()); - final RepositoryFile repositoryFile = fileRepoService.getFile(fileUuid); + final RepositoryFile repositoryFile = repositoryService.getFile(fileUuid); dataset.getRepositoryFiles().remove(repositoryFile); - fileRepoService.removeFile(repositoryFile); + repositoryService.removeFile(repositoryFile); return lazyLoad(datasetRepository.save(dataset)); } diff --git a/src/main/java/org/genesys2/server/api/admin/v0/CacheController.java b/src/main/java/org/genesys2/server/api/admin/v0/CacheController.java index c45809ac7cc4b11a372b6e01766ad9e940495439..0ac4571eb7a6133ce2e7353f0aa7393affe50eeb 100644 --- a/src/main/java/org/genesys2/server/api/admin/v0/CacheController.java +++ b/src/main/java/org/genesys2/server/api/admin/v0/CacheController.java @@ -43,10 +43,12 @@ import io.swagger.annotations.Api; @Controller("adminCacheApi0") @PreAuthorize("isAuthenticated()") -@RequestMapping(value = { "/api/v0/admin/cache", "/json/v0/cache" }) +@RequestMapping(value = { CacheController.API_URL, "/json/v0/cache" }) @Api(tags = { "admin" }) public class CacheController extends ApiBaseController { + public final static String API_URL = ApiBaseController.APIv0_ADMIN_BASE + "/cache"; + @Autowired private MappingService mappingService; diff --git a/src/main/java/org/genesys2/server/api/v0/CropsController.java b/src/main/java/org/genesys2/server/api/v0/CropsController.java index d5da43ab57daa32014968a6f19e878221b770edf..497d1f4a24ae0e359c0943433ff13bf0b169ef8a 100644 --- a/src/main/java/org/genesys2/server/api/v0/CropsController.java +++ b/src/main/java/org/genesys2/server/api/v0/CropsController.java @@ -56,7 +56,7 @@ import net.sf.oval.Validator; @Api(tags = { "crop" }) public class CropsController extends ApiBaseController { - protected static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/crops"; + public static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/crops"; @Autowired GenesysService genesysService; diff --git a/src/main/java/org/genesys2/server/api/v0/PermissionController.java b/src/main/java/org/genesys2/server/api/v0/PermissionController.java index 85374deaab5c550d2e392e2331aeff9b0faf4c42..100b13c57bc9a8e13149da5c51188ab454de5a99 100644 --- a/src/main/java/org/genesys2/server/api/v0/PermissionController.java +++ b/src/main/java/org/genesys2/server/api/v0/PermissionController.java @@ -62,7 +62,7 @@ public class PermissionController extends ApiBaseController { @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ApiResult addPermission(@RequestBody PermissionJson permissionJson) { LOG.info("Adding permission {}", permissionJson); - final AclObjectIdentity oid = aclService.getObjectIdentity(permissionJson.getOid(), permissionJson.getClazz()); + final AclObjectIdentity oid = aclService.ensureObjectIdentity(permissionJson.getOid(), permissionJson.getClazz()); if (permissionJson.getAuthority() != null) { final AclSid sid = aclService.getAuthoritySid(permissionJson.getAuthority()); diff --git a/src/main/java/org/genesys2/server/model/genesys/AccessionId.java b/src/main/java/org/genesys2/server/model/genesys/AccessionId.java index a90a2e74fb399941b22270f65efbef3972f1340f..caff024ba667e7ce9728d31356981f59901dcc59 100644 --- a/src/main/java/org/genesys2/server/model/genesys/AccessionId.java +++ b/src/main/java/org/genesys2/server/model/genesys/AccessionId.java @@ -80,7 +80,7 @@ public class AccessionId extends AuditedVersionedModel implements IdUUID { @OneToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, optional = true, orphanRemoval = true) @JoinColumn(name = "pdciId", unique = true) @JsonIgnoreProperties({ "accession" }) - @JsonView({ JsonViews.Root.class }) + @JsonView({ JsonViews.Internal.class }) private PDCI pdci; @Column(name = "storage", nullable = false) diff --git a/src/main/java/org/genesys2/server/service/audit/SpringSecurityAuditorAware.java b/src/main/java/org/genesys2/server/service/audit/SpringSecurityAuditorAware.java deleted file mode 100644 index 7553a85a57a1d23d1d7a70d28f2ed76452580d66..0000000000000000000000000000000000000000 --- a/src/main/java/org/genesys2/server/service/audit/SpringSecurityAuditorAware.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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.genesys2.server.service.audit; - -import org.genesys.blocks.security.SecurityContextUtil; -import org.genesys2.server.model.impl.User; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.AuditorAware; -import org.springframework.stereotype.Component; - -@Component("auditorAware") -public class SpringSecurityAuditorAware implements AuditorAware { - public static final Logger LOG = LoggerFactory.getLogger(SpringSecurityAuditorAware.class); - - @Override - public Long getCurrentAuditor() { - final User user = SecurityContextUtil.getCurrentUser(); - return user == null ? null : user.getId(); - } -} diff --git a/src/main/java/org/genesys2/server/service/impl/AccessionListServiceImpl.java b/src/main/java/org/genesys2/server/service/impl/AccessionListServiceImpl.java index e48b0a6be54b237b7606ada2bb98b99fc3134749..3b6c709dd60e09f408036f5d87fa2656b8b82ac1 100644 --- a/src/main/java/org/genesys2/server/service/impl/AccessionListServiceImpl.java +++ b/src/main/java/org/genesys2/server/service/impl/AccessionListServiceImpl.java @@ -49,7 +49,7 @@ public class AccessionListServiceImpl implements AccessionListService { @Autowired AccessionListRepository accessionListRepository; - @Autowired + @Autowired(required = false) ElasticUpdater elasticUpdater; @Override @@ -95,9 +95,10 @@ public class AccessionListServiceImpl implements AccessionListService { @PreAuthorize("hasRole('ADMINISTRATOR') or hasPermission(#accessionList, 'WRITE')") @Transactional public void removeAll(AccessionList accessionList) { - // Re-index - elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); - + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + } accessionListRepository.removeAll(accessionList); } @@ -105,9 +106,10 @@ public class AccessionListServiceImpl implements AccessionListService { @PreAuthorize("hasRole('ADMINISTRATOR') or hasPermission(#accessionList, 'WRITE')") @Transactional public void addToList(AccessionList list, AccessionData accession) { - // Re-index - elasticUpdater.update(Accession.class, accession.getId()); - + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.update(Accession.class, accession.getId()); + } accessionListRepository.addOne(list, accession.getAccessionId()); } @@ -120,22 +122,28 @@ public class AccessionListServiceImpl implements AccessionListService { accessionListRepository.addAll(acceList, accessionIds); - // Re-index - elasticUpdater.updateAll(Accession.class, accessionIds.toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.updateAll(Accession.class, accessionIds.toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + } } @Override @PreAuthorize("hasRole('ADMINISTRATOR') or hasPermission(#accessionList, 'WRITE')") @Transactional public void setList(AccessionList accessionList, Collection accessionIds) { - // Re-index - elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); - + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + } + accessionListRepository.removeAll(accessionList); accessionListRepository.addAll(accessionList, accessionIds); - // Re-index - elasticUpdater.updateAll(Accession.class, accessionIds.toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.updateAll(Accession.class, accessionIds.toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + } } @Override @@ -144,17 +152,20 @@ public class AccessionListServiceImpl implements AccessionListService { public void addToList(AccessionList accessionList, AppliedFilters filters) { accessionListRepository.addAll(accessionList, filters); - // Re-index - elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + } } @Override @PreAuthorize("hasRole('ADMINISTRATOR') or hasPermission(#accessionList, 'DELETE')") @Transactional public void delete(AccessionList accessionList) { - // Re-index - elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); - + if (elasticUpdater!=null) { + // Re-index + elasticUpdater.updateAll(Accession.class, accessionListRepository.getAccessionIds(accessionList).toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY)); + } accessionListRepository.delete(accessionList); } diff --git a/src/main/java/org/genesys2/server/service/impl/ElasticSearchManagementServiceImpl.java b/src/main/java/org/genesys2/server/service/impl/ElasticSearchManagementServiceImpl.java index 6727e676926f2d6af87fc42e25d85d6aea55733c..571984f94f728b3b9c253e8ac9b874d6d353096f 100644 --- a/src/main/java/org/genesys2/server/service/impl/ElasticSearchManagementServiceImpl.java +++ b/src/main/java/org/genesys2/server/service/impl/ElasticSearchManagementServiceImpl.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; import javax.annotation.Resource; @@ -58,8 +59,6 @@ import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; -import com.hazelcast.core.ILock; - @Service public class ElasticSearchManagementServiceImpl implements ElasticSearchManagementService { @@ -81,7 +80,7 @@ public class ElasticSearchManagementServiceImpl implements ElasticSearchManageme private GenesysLowlevelRepository genesysLowlevelRepository; @Resource - private ILock elasticsearchAdminLock; + private Lock elasticsearchAdminLock; private final Map> clazzMap; diff --git a/src/main/java/org/genesys2/server/service/impl/FullTextSearchServiceImpl.java b/src/main/java/org/genesys2/server/service/impl/FullTextSearchServiceImpl.java index d42b0bdad0a118966e4fb0ec3dbe7afb70c9c79a..2b839c1f39189cb952f4d06b2b4c3f97db689069 100644 --- a/src/main/java/org/genesys2/server/service/impl/FullTextSearchServiceImpl.java +++ b/src/main/java/org/genesys2/server/service/impl/FullTextSearchServiceImpl.java @@ -15,10 +15,7 @@ **/ package org.genesys2.server.service.impl; -import static org.elasticsearch.index.query.QueryBuilders.boolQuery; -import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; -import static org.elasticsearch.index.query.QueryBuilders.matchQuery; -import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; +import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.fieldValueFactorFunction; import java.util.ArrayList; @@ -35,7 +32,6 @@ import org.genesys2.server.model.impl.ActivityPost; import org.genesys2.server.model.impl.Article; import org.genesys2.server.model.impl.Country; import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.mvc.JspHelper; import org.genesys2.server.persistence.ActivityPostRepository; import org.genesys2.server.persistence.ArticleRepository; import org.genesys2.server.persistence.CountryRepository; @@ -86,9 +82,6 @@ public class FullTextSearchServiceImpl implements FullTextSearchService, Initial @Autowired private FaoInstituteRepository instituteRepository; - @Autowired - private JspHelper jspHelper; - @Autowired private ContentService contentService; @@ -326,7 +319,7 @@ public class FullTextSearchServiceImpl implements FullTextSearchService, Initial document.setSummary(activityPost.getTitle()); document.setCreatedDate(activityPost.getCreatedDate()); document.setLastModifiedDate(activityPost.getLastModifiedDate()); - document.setUrlToContent("/content/news/" + activityPost.getId() + "/" + this.jspHelper.suggestUrlForText(activityPost.getTitle())); + document.setUrlToContent("/content/news/" + activityPost.getId() + "/"); } private void updateDocument(Country country, FullTextDocument document) { diff --git a/src/main/java/org/genesys2/server/persistence/GenesysLowlevelRepositoryCustomImpl.java b/src/main/java/org/genesys2/server/service/impl/GenesysLowlevelRepositoryCustomImpl.java similarity index 99% rename from src/main/java/org/genesys2/server/persistence/GenesysLowlevelRepositoryCustomImpl.java rename to src/main/java/org/genesys2/server/service/impl/GenesysLowlevelRepositoryCustomImpl.java index babb91b5da016528b53470bb1dc5bad19c51f4fa..ff694156850c4730d827ea91720157dd750022f3 100644 --- a/src/main/java/org/genesys2/server/persistence/GenesysLowlevelRepositoryCustomImpl.java +++ b/src/main/java/org/genesys2/server/service/impl/GenesysLowlevelRepositoryCustomImpl.java @@ -14,7 +14,7 @@ * limitations under the License. **/ -package org.genesys2.server.persistence; +package org.genesys2.server.service.impl; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -24,7 +24,8 @@ import java.sql.SQLException; import java.util.List; import org.genesys2.server.model.genesys.Method; -import org.genesys2.server.service.impl.DirectMysqlQuery; +import org.genesys2.server.persistence.GenesysLowlevelRepository; +import org.genesys2.server.persistence.MethodRepository; import org.genesys2.server.service.impl.DirectMysqlQuery.MethodResolver; import org.genesys2.server.service.impl.FilterHandler.AppliedFilters; import org.slf4j.Logger; diff --git a/src/main/java/org/genesys2/server/service/impl/TaxonomyManager.java b/src/main/java/org/genesys2/server/service/impl/TaxonomyManager.java index 79a28bf70aa8dc3d2f62be18e71e1273f00d766b..fff7bdd07492bb02ff03284c34400fcb07349387 100644 --- a/src/main/java/org/genesys2/server/service/impl/TaxonomyManager.java +++ b/src/main/java/org/genesys2/server/service/impl/TaxonomyManager.java @@ -17,6 +17,7 @@ package org.genesys2.server.service.impl; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; import javax.annotation.Resource; @@ -49,7 +50,7 @@ public class TaxonomyManager { * update logic */ @Resource - private ILock taxonomyUpdateLock; + private Lock taxonomyUpdateLock; public Taxonomy2 ensureTaxonomy2(String genus, String species, String spAuthor, String subtaxa, String subtAuthor) { if (StringUtils.isBlank(genus)) { diff --git a/src/main/java/org/genesys2/server/persistence/TraitValueRepositoryImpl.java b/src/main/java/org/genesys2/server/service/impl/TraitValueRepositoryImpl.java similarity index 97% rename from src/main/java/org/genesys2/server/persistence/TraitValueRepositoryImpl.java rename to src/main/java/org/genesys2/server/service/impl/TraitValueRepositoryImpl.java index e6f8618bdb4d0184d50fcdb492d3e2f157f4a943..489767cfae48b12bb249deb2a4879c3ce18e59e7 100644 --- a/src/main/java/org/genesys2/server/persistence/TraitValueRepositoryImpl.java +++ b/src/main/java/org/genesys2/server/service/impl/TraitValueRepositoryImpl.java @@ -14,7 +14,7 @@ * limitations under the License. **/ -package org.genesys2.server.persistence; +package org.genesys2.server.service.impl; import java.sql.Connection; import java.sql.PreparedStatement; @@ -37,6 +37,11 @@ import org.genesys2.server.model.genesys.ExperimentAccessionTrait; import org.genesys2.server.model.genesys.ExperimentTrait; import org.genesys2.server.model.genesys.Metadata; import org.genesys2.server.model.genesys.Method; +import org.genesys2.server.persistence.AccessionTraitRepository; +import org.genesys2.server.persistence.MetadataAccessionRepository; +import org.genesys2.server.persistence.MetadataMethodRepository; +import org.genesys2.server.persistence.MethodRepository; +import org.genesys2.server.persistence.TraitValueRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -51,7 +56,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository -@Transactional(readOnly = true) +//@Transactional(readOnly = true) public class TraitValueRepositoryImpl implements TraitValueRepository { public static final Logger LOG = LoggerFactory.getLogger(TraitValueRepository.class); private JdbcTemplate jdbcTemplate; diff --git a/src/main/java/org/genesys2/server/service/worker/ElasticUpdater.java b/src/main/java/org/genesys2/server/service/worker/ElasticUpdater.java index 853d1041fa17f9b713c5dd69782d485b92bd1212..946149e4d39c0a6e30949ded0f8fa857087ef956 100644 --- a/src/main/java/org/genesys2/server/service/worker/ElasticUpdater.java +++ b/src/main/java/org/genesys2/server/service/worker/ElasticUpdater.java @@ -22,6 +22,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.BlockingQueue; import javax.annotation.Resource; @@ -34,8 +35,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.stereotype.Component; -import com.hazelcast.core.IQueue; - /** * Component that receives updated or deleted accession IDs and uses a * background thread to refresh ES @@ -50,10 +49,10 @@ public class ElasticUpdater { private ElasticsearchTemplate elasticsearchTemplate; @Resource - private IQueue elasticRemoveQueue; + private BlockingQueue elasticRemoveQueue; @Resource - private IQueue elasticUpdateQueue; + private BlockingQueue elasticUpdateQueue; /** * Schedule objects for removal diff --git a/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterAspect.java b/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterAspect.java index 201330057dbb77ee603d9680715cfec0f9d56eff..9b1e7a7c7f9ace6e01c397c5dba886578f5297ed 100644 --- a/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterAspect.java +++ b/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterAspect.java @@ -337,7 +337,10 @@ public class ElasticUpdaterAspect { if (LOG.isTraceEnabled()) { LOG.trace("Returning from {} id={}", joinPoint.toLongString(), (long) joinPoint.getArgs()[0]); } - elasticUpdater.remove(Article.class, (Long) joinPoint.getArgs()[0]); + // test for deleteAll with no args + if (joinPoint.getArgs().length > 0) { + elasticUpdater.remove(Article.class, (Long) joinPoint.getArgs()[0]); + } } /** @@ -352,7 +355,10 @@ public class ElasticUpdaterAspect { if (LOG.isTraceEnabled()) { LOG.trace("Returning from {} id={}", joinPoint.toLongString(), (long) joinPoint.getArgs()[0]); } - elasticUpdater.remove(FullTextDocument.class, (Long) joinPoint.getArgs()[0]); + // test for deleteAll with no args + if (joinPoint.getArgs().length > 0) { + elasticUpdater.remove(FullTextDocument.class, (Long) joinPoint.getArgs()[0]); + } } /** @@ -367,7 +373,10 @@ public class ElasticUpdaterAspect { if (LOG.isTraceEnabled()) { LOG.trace("Returning from {} id={}", joinPoint.toLongString(), (long) joinPoint.getArgs()[0]); } - elasticUpdater.remove(Country.class, (Long) joinPoint.getArgs()[0]); + // test for deleteAll with no args + if (joinPoint.getArgs().length > 0) { + elasticUpdater.remove(Country.class, (Long) joinPoint.getArgs()[0]); + } } /** @@ -382,6 +391,9 @@ public class ElasticUpdaterAspect { if (LOG.isTraceEnabled()) { LOG.trace("Returning from {} id={}", joinPoint.toLongString(), (long) joinPoint.getArgs()[0]); } - elasticUpdater.remove(FaoInstitute.class, (Long) joinPoint.getArgs()[0]); + // test for deleteAll with no args + if (joinPoint.getArgs().length > 0) { + elasticUpdater.remove(FaoInstitute.class, (Long) joinPoint.getArgs()[0]); + } } } diff --git a/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterProcessor.java b/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterProcessor.java index 18dcb9f097fd948308bd0f5c67d540d81a03dea7..74d577148478af4fe4e157fe06ea67e1eb88e7e6 100644 --- a/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterProcessor.java +++ b/src/main/java/org/genesys2/server/service/worker/ElasticUpdaterProcessor.java @@ -3,6 +3,7 @@ package org.genesys2.server.service.worker; import java.util.HashMap; import java.util.HashSet; import java.util.Set; +import java.util.concurrent.BlockingQueue; import javax.annotation.Resource; @@ -17,14 +18,12 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; -import com.hazelcast.core.IQueue; - /** * ES Processor component uses Spring's @Scheduled annotation to scan queues with 2000ms delay measured from the * completion time of each preceding invocation. */ @Component -class ElasticUpdaterProcessor { +public class ElasticUpdaterProcessor { public static final Logger LOG = LoggerFactory.getLogger(ElasticUpdaterProcessor.class); private static final int BATCH_SIZE = 100; @@ -39,10 +38,10 @@ class ElasticUpdaterProcessor { private ThreadPoolTaskExecutor executor; @Resource - private IQueue elasticRemoveQueue; + private BlockingQueue elasticRemoveQueue; @Resource - private IQueue elasticUpdateQueue; + private BlockingQueue elasticUpdateQueue; private HashMap> buckets = new HashMap>(); diff --git a/src/main/java/org/genesys2/spring/config/ApplicationConfig.java b/src/main/java/org/genesys2/spring/config/ApplicationConfig.java index 33e24c1a8215b65ae9305d2f15734971dba20616..ef4f6fba3c8ba8ca9943099ede08b5ed4a4ece5b 100644 --- a/src/main/java/org/genesys2/spring/config/ApplicationConfig.java +++ b/src/main/java/org/genesys2/spring/config/ApplicationConfig.java @@ -33,16 +33,23 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.Import; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.core.annotation.Order; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration -@Import({ CommonConfig.class, SchedulerConfig.class, DatabaseConfig.class, MailConfig.class, OAuth2ServerConfig.class, SecurityConfig.class, CacheConfig.class, - ElasticsearchConfig.class, FileRepositoryConfig.class, WebConfiguration.class, AuditConfig.class, GLISConfig.class }) +@Import({ HazelcastConfig.class, CommonConfig.class, SchedulerConfig.class, DatabaseConfig.class, TemplatingConfig.class, MailConfig.class, OAuth2ServerConfig.class, SecurityConfig.class, CacheConfig.class, + ElasticsearchConfig.class, FileRepositoryConfig.class, WebSecurityConfig.class, WebConfiguration.class, AuditConfig.class, GLISConfig.class, SwaggerConfig.class }) + +@EnableAspectJAutoProxy +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class ApplicationConfig { public static final Logger LOG = LoggerFactory.getLogger(ApplicationConfig.class); diff --git a/src/main/java/org/genesys2/spring/config/AuditConfig.java b/src/main/java/org/genesys2/spring/config/AuditConfig.java index 31a747aa31038f53332f568ed329c7d0f1f8162a..16a3f3575caba490e43036a8facd92c6a0f09954 100644 --- a/src/main/java/org/genesys2/spring/config/AuditConfig.java +++ b/src/main/java/org/genesys2/spring/config/AuditConfig.java @@ -20,8 +20,10 @@ import org.genesys.blocks.auditlog.service.AuditTrailService; import org.genesys.blocks.auditlog.service.ClassPKService; import org.genesys.blocks.auditlog.service.impl.AuditTrailServiceImpl; import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; +import org.genesys.blocks.security.SpringSecurityAuditorAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.domain.AuditorAware; /** * Configuration of audit-related components and services. @@ -30,6 +32,11 @@ import org.springframework.context.annotation.Configuration; */ @Configuration public class AuditConfig { + + @Bean + public AuditorAware auditorAware() { + return new SpringSecurityAuditorAware(); + } @Bean public ClassPKService classPkService() { diff --git a/src/main/java/org/genesys2/spring/config/CacheConfig.java b/src/main/java/org/genesys2/spring/config/CacheConfig.java index f9a60e691311a2a0b39ac46fed2f4b57d8abb5a4..5a44af6da1b2ed85fe85a7d95502f4fadbbe1f1d 100644 --- a/src/main/java/org/genesys2/spring/config/CacheConfig.java +++ b/src/main/java/org/genesys2/spring/config/CacheConfig.java @@ -16,152 +16,16 @@ package org.genesys2.spring.config; -import java.util.Properties; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IExecutorService; -import com.hazelcast.core.IMap; -import com.hazelcast.core.IQueue; -import com.hazelcast.spring.cache.HazelcastCacheManager; -import com.hazelcast.web.WebFilter; -import com.hazelcast.web.spring.SpringAwareWebFilter; - -import org.genesys.blocks.security.lockout.AccountLockoutManager.AttemptStatistics; import org.genesys.catalog.service.impl.ShortFilterServiceImpl; -import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.core.session.SessionRegistry; -import org.springframework.security.core.session.SessionRegistryImpl; @Configuration @EnableCaching -@Import({ HazelcastConfig.class }) public class CacheConfig { - - /** The instance name. */ - @Value("${hazelcast.instanceName}") - protected String instanceName = "genesys"; - - @Value("${base.cookie-domain}") - private String cookieDomain; - - @Value("${base.cookie-secure}") - private String cookieSecure; - - @Value("${base.cookie-http-only}") - private String cookieHttpOnly; - - /** - * Cache manager. - * - * @param hazelcastInstance the hazelcast instance - * @return the hazelcast cache manager - */ - @Bean - public HazelcastCacheManager cacheManager(final HazelcastInstance hazelcastInstance) { - final HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - /** - * Tileserver map. - * - * @param hazelcast the hazelcast - * @return the i map - */ - @Bean - public IMap tileserverMap(final HazelcastInstance hazelcast) { - final IMap x = hazelcast.getMap("tileserver"); - return x; - } - - /** - * Elastic remove queue. - * - * @param hazelcast the hazelcast - * @return the i queue - */ - @Bean - public IQueue elasticRemoveQueue(final HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-remove"); - } - /** - * Elastic update queue. - * - * @param hazelcast the hazelcast - * @return the i queue - */ - @Bean - public IQueue elasticUpdateQueue(final HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-update"); - } - - /** - * Distributed executor. - * - * @param hazelcast the hazelcast - * @return the i executor service - */ - @Bean - public IExecutorService distributedExecutor(final HazelcastInstance hazelcast) { - final IExecutorService executorService = hazelcast.getExecutorService("hazel-exec"); - return executorService; - } - - /** - * Account lockout map. - * - * @param hazelcast the hazelcast - * @return the i map - */ - @Bean - public IMap accountLockoutMap(final HazelcastInstance hazelcast) { - final IMap x = hazelcast.getMap("accountLocks"); - return x; - } - - /** - * Hazelcast web filter. - * - * @return the web filter - */ - @Bean - public WebFilter hazelcastWebFilter() { - return new SpringAwareWebFilter(filterProps()); - } - - /** - * Session registry. - * - * @return the session registry - */ - @Bean - public SessionRegistry SessionRegistry() { - return new SessionRegistryImpl(); - } - - private Properties filterProps() { - final Properties properties = new Properties(); - properties.setProperty("use-client", "false"); - properties.setProperty("map-name", "jetty-sessions"); - // Not allowed in HZ-3.8.1 - // properties.setProperty("session-ttl-seconds", "21600"); - properties.setProperty("sticky-session", "false"); - properties.setProperty("cookie-name", "hz-session-id"); - properties.setProperty("cookie-domain", cookieDomain); - properties.setProperty("cookie-secure", cookieSecure); - properties.setProperty("cookie-http-only", cookieHttpOnly); - // properties.setProperty("debug", "true"); - properties.setProperty("instance-name", instanceName); - properties.setProperty("shutdown-on-destroy", "true"); - return properties; - } - @Bean("shortFilterKeyGenerator") public KeyGenerator shortFilterKeyGenerator() { return new ShortFilterServiceImpl.KeyGen(); diff --git a/src/main/java/org/genesys2/spring/config/CommonConfig.java b/src/main/java/org/genesys2/spring/config/CommonConfig.java index 33513ec90644d63dd3fa6008f7e22d2e561dd03d..04ccc6ca93258fd42a2e189907cdf642e704ea4c 100644 --- a/src/main/java/org/genesys2/spring/config/CommonConfig.java +++ b/src/main/java/org/genesys2/spring/config/CommonConfig.java @@ -18,11 +18,7 @@ package org.genesys2.spring.config; import javax.persistence.Entity; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.SerializationFeature; - import org.genesys2.spring.validation.oval.spring.SpringOvalValidator; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -30,20 +26,18 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.Scope; import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; -import org.springframework.security.acls.AclPermissionEvaluator; -import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler; import org.springframework.stereotype.Controller; import org.springframework.validation.Validator; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.SerializationFeature; + @EnableAspectJAutoProxy @ComponentScan(basePackages = { "org.genesys2.spring", "org.genesys2.server", "org.genesys.catalog.server" }, excludeFilters = { @ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION), @ComponentScan.Filter(value = Configuration.class, type = FilterType.ANNOTATION) }, includeFilters = @ComponentScan.Filter(value = Entity.class, type = FilterType.ANNOTATION)) @Configuration public class CommonConfig { - @Autowired - private AclPermissionEvaluator aclPermissionEvaluator; - @Scope("singleton") @Bean public Validator validator() { @@ -59,11 +53,4 @@ public class CommonConfig { return mapperFactoryBean; } - @Bean - public DefaultWebSecurityExpressionHandler webExpressionHandler() { - final DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); - handler.setPermissionEvaluator(aclPermissionEvaluator); - return handler; - } - } diff --git a/src/main/java/org/genesys2/spring/config/DatabaseConfig.java b/src/main/java/org/genesys2/spring/config/DatabaseConfig.java index 9b40b1f4460d16f7305f4be528b1c06a06122d21..306f3c3b004f8ef9c5ea4a73f33de20605a5ffe2 100644 --- a/src/main/java/org/genesys2/spring/config/DatabaseConfig.java +++ b/src/main/java/org/genesys2/spring/config/DatabaseConfig.java @@ -24,7 +24,6 @@ import javax.persistence.EntityManagerFactory; import org.apache.tomcat.jdbc.pool.DataSource; import org.genesys.blocks.auditlog.component.AuditTrailInterceptor; -import org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper; import org.hibernate.CallbackException; import org.hibernate.EmptyInterceptor; import org.hibernate.Interceptor; @@ -32,7 +31,9 @@ import org.hibernate.Transaction; import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.type.Type; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.core.JdbcTemplate; @@ -131,7 +132,7 @@ public class DatabaseConfig { @Bean(name = "entityManagerFactory") @DependsOn("databaseMigration") - public LocalContainerEntityManagerFactoryBean entityManagerFactory(final HazelcastCacheRegionFactoryWrapper wrp) throws Exception { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception { final LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setDataSource(dataSource()); entityManager.setPersistenceUnitName("spring-jpa"); diff --git a/src/main/java/org/genesys2/spring/config/ElasticsearchConfigDev.java b/src/main/java/org/genesys2/spring/config/ElasticsearchConfigDev.java index dc2399ce9c97280137364a4911f2af38b5091de0..c4b487f44eaf49e95f06f735f42e81d0e252d2f0 100644 --- a/src/main/java/org/genesys2/spring/config/ElasticsearchConfigDev.java +++ b/src/main/java/org/genesys2/spring/config/ElasticsearchConfigDev.java @@ -41,7 +41,7 @@ public class ElasticsearchConfigDev { @Value("${elasticsearch.data.path}") private String dataPath; - @Bean + @Bean(destroyMethod = "close") public NodeClient nodeClient() { final ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled", String.valueOf(this.enableHttp)).put("path.home", this.dataPath); diff --git a/src/main/java/org/genesys2/spring/config/FileRepositoryConfig.java b/src/main/java/org/genesys2/spring/config/FileRepositoryConfig.java index 0b1d21098e489ace24c3012065d3dc17df950006..85ea87bd188394d9a1aefc6a55f6044e53f7bf46 100644 --- a/src/main/java/org/genesys2/spring/config/FileRepositoryConfig.java +++ b/src/main/java/org/genesys2/spring/config/FileRepositoryConfig.java @@ -181,20 +181,36 @@ public class FileRepositoryConfig implements InitializingBean { @Bean public RepositoryFtpServer ftpServer() { - final RepositoryFtpServer ftpServer = new RepositoryFtpServer(); - ftpServer.setFtpPort(ftpServerPort); - ftpServer.setUserManager(ftpUserManager()); + if (ftpServerPort > 0) { + final RepositoryFtpServer ftpServer = new RepositoryFtpServer(); + ftpServer.setFtpPort(ftpServerPort); + ftpServer.setUserManager(ftpUserManager()); + + if (StringUtils.isBlank(ftpKeystorePath)) { + LOG.warn("Using built-in keystore for FTP server /repository/ftpserver.jks"); + ftpKeystorePath = getClass().getResource(DEFAULT_REPOSITORY_KEYSTORE_RESOURCE).getPath(); + } + + if (StringUtils.isBlank(ftpKeystorePwd)) { + LOG.warn("Using built-in keystore password"); + ftpKeystorePwd = DEFAULT_REPOSITORY_KEYSTORE_PASSWORD; + } - ftpServer.setKeystorePath(ftpKeystorePath); - ftpServer.setKeystorePsw(ftpKeystorePwd); - ftpServer.setExternalAddress(ftpServerExternalAddress); - ftpServer.setPassivePorts(ftpServerPassivePorts); + ftpServer.setKeystorePath(ftpKeystorePath); + ftpServer.setKeystorePsw(ftpKeystorePwd); + ftpServer.setExternalAddress(ftpServerExternalAddress); + ftpServer.setPassivePorts(ftpServerPassivePorts); - return ftpServer; + return ftpServer; + } else { + System.err.println("Skipping FTP configuration"); + return null; + } } @Bean - public UserManager ftpUserManager() { + protected UserManager ftpUserManager() { + System.err.println("Creating FTP user manager"); return new AbstractUserManager() { @Autowired private AccountLockoutManager lockoutManager; @@ -282,16 +298,6 @@ public class FileRepositoryConfig implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - if (StringUtils.isBlank(ftpKeystorePath)) { - LOG.warn("Using built-in keystore for FTP server /repository/ftpserver.jks"); - ftpKeystorePath = getClass().getResource(DEFAULT_REPOSITORY_KEYSTORE_RESOURCE).getPath(); - } - - if (StringUtils.isBlank(ftpKeystorePwd)) { - LOG.warn("Using built-in keystore password"); - ftpKeystorePwd = DEFAULT_REPOSITORY_KEYSTORE_PASSWORD; - } - ftpServerExternalAddress = StringUtils.trimToNull(ftpServerExternalAddress); ftpServerPassivePorts = StringUtils.trimToNull(ftpServerPassivePorts); } diff --git a/src/main/java/org/genesys2/spring/config/HazelcastConfig.java b/src/main/java/org/genesys2/spring/config/HazelcastConfig.java index 76d4dc17ed76b49a0d298502e1fca1e14bbe9367..0d4e03a6b7ce974ec370fcc7958219414cb13706 100644 --- a/src/main/java/org/genesys2/spring/config/HazelcastConfig.java +++ b/src/main/java/org/genesys2/spring/config/HazelcastConfig.java @@ -21,6 +21,17 @@ import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.genesys.blocks.security.lockout.AccountLockoutManager.AttemptStatistics; +import org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import com.hazelcast.config.Config; import com.hazelcast.config.EvictionPolicy; @@ -35,19 +46,16 @@ import com.hazelcast.config.QueueConfig; import com.hazelcast.config.TcpIpConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IExecutorService; import com.hazelcast.core.ILock; +import com.hazelcast.core.IMap; +import com.hazelcast.core.IQueue; import com.hazelcast.core.ManagedContext; import com.hazelcast.hibernate.HazelcastCacheRegionFactory; +import com.hazelcast.spring.cache.HazelcastCacheManager; import com.hazelcast.spring.context.SpringManagedContext; - -import org.apache.commons.lang3.StringUtils; -import org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; +import com.hazelcast.web.WebFilter; +import com.hazelcast.web.spring.SpringAwareWebFilter; @Configuration @EnableCaching @@ -95,6 +103,16 @@ public abstract class HazelcastConfig { @Value("${cache.eviction-policy}") protected EvictionPolicy cacheEvictionPolicy; + @Value("${base.cookie-domain}") + private String cookieDomain; + + @Value("${base.cookie-secure}") + private String cookieSecure; + + @Value("${base.cookie-http-only}") + private String cookieHttpOnly; + + /** * Managed context. * @@ -115,7 +133,7 @@ public abstract class HazelcastConfig { * @param managedContext the managed context * @return the hazelcast instance */ - @Bean + @Bean(destroyMethod = "shutdown") public HazelcastInstance hazelcast(final ManagedContext managedContext) { final Config cfg = new Config(); cfg.setManagedContext(managedContext); @@ -222,6 +240,7 @@ public abstract class HazelcastConfig { return (this.hazelcastMembers != null) && (this.hazelcastMembers.length != 0) && (this.hazelcastMembers[0].length() > 0); } + /** * Taxonomy update lock. * @@ -254,6 +273,14 @@ public abstract class HazelcastConfig { x.setHazelcastCacheRegionFactory(hazelcastCacheRegionFactory); return x; } + + /** + * This type is declared in hibernate.properties + */ + @Bean + public HazelcastCacheRegionFactoryWrapper wrp() { + return new HazelcastCacheRegionFactoryWrapper(); + } /** * Injected into wrapper above @@ -316,4 +343,103 @@ public abstract class HazelcastConfig { queueConfig.setMaxSize(100); cfg.addQueueConfig(queueConfig); } + + + /** + * Cache manager. + * + * @param hazelcastInstance the hazelcast instance + * @return the hazelcast cache manager + */ + @Bean + public HazelcastCacheManager cacheManager(final HazelcastInstance hazelcastInstance) { + final HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); + return cm; + } + + /** + * Tileserver map. + * + * @param hazelcast the hazelcast + * @return the i map + */ + @Bean + public IMap tileserverMap(final HazelcastInstance hazelcast) { + final IMap x = hazelcast.getMap("tileserver"); + return x; + } + + /** + * Elastic remove queue. + * + * @param hazelcast the hazelcast + * @return the i queue + */ + @Bean + public IQueue elasticRemoveQueue(final HazelcastInstance hazelcast) { + return hazelcast.getQueue("es-remove"); + } + + /** + * Elastic update queue. + * + * @param hazelcast the hazelcast + * @return the i queue + */ + @Bean + public IQueue elasticUpdateQueue(final HazelcastInstance hazelcast) { + return hazelcast.getQueue("es-update"); + } + + /** + * Distributed executor. + * + * @param hazelcast the hazelcast + * @return the i executor service + */ + @Bean + public IExecutorService distributedExecutor(final HazelcastInstance hazelcast) { + final IExecutorService executorService = hazelcast.getExecutorService("hazel-exec"); + return executorService; + } + + /** + * Account lockout map. + * + * @param hazelcast the hazelcast + * @return the i map + */ + @Bean + public IMap accountLockoutMap(final HazelcastInstance hazelcast) { + final IMap x = hazelcast.getMap("accountLocks"); + return x; + } + + /** + * Hazelcast web filter. + * + * @return the web filter + */ + @Bean + public WebFilter hazelcastWebFilter() { + return new SpringAwareWebFilter(filterProps()); + } + + private Properties filterProps() { + final Properties properties = new Properties(); + properties.setProperty("use-client", "false"); + properties.setProperty("map-name", "jetty-sessions"); + // Not allowed in HZ-3.8.1 + // properties.setProperty("session-ttl-seconds", "21600"); + properties.setProperty("sticky-session", "false"); + properties.setProperty("cookie-name", "hz-session-id"); + properties.setProperty("cookie-domain", cookieDomain); + properties.setProperty("cookie-secure", cookieSecure); + properties.setProperty("cookie-http-only", cookieHttpOnly); + // properties.setProperty("debug", "true"); + properties.setProperty("instance-name", instanceName); + properties.setProperty("shutdown-on-destroy", "true"); + return properties; + } + } diff --git a/src/main/java/org/genesys2/spring/config/MailConfig.java b/src/main/java/org/genesys2/spring/config/MailConfig.java index 5be23e95bf4a77389a14c533b8c88e3399788a06..c48f21bf0e3b31b825786522776b13998854e208 100644 --- a/src/main/java/org/genesys2/spring/config/MailConfig.java +++ b/src/main/java/org/genesys2/spring/config/MailConfig.java @@ -16,16 +16,12 @@ package org.genesys2.spring.config; -import java.io.IOException; import java.util.Properties; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.VelocityException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.ui.velocity.VelocityEngineFactoryBean; @Configuration public class MailConfig { @@ -65,18 +61,6 @@ public class MailConfig { return sender; } - @Bean - public VelocityEngine velocityEngine() throws VelocityException, IOException { - final VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean(); - velocityEngineFactoryBean.setVelocityProperties(velocityProperties()); - velocityEngineFactoryBean.afterPropertiesSet(); - final VelocityEngine engine = velocityEngineFactoryBean.getObject(); - if (engine == null) { - throw new RuntimeException("Velocity engine could not be created"); - } - return engine; - } - private Properties javaMailProperties() { final Properties properties = new Properties(); properties.setProperty("mail.smtp.ssl.enable", sslEnable); @@ -85,15 +69,5 @@ public class MailConfig { properties.setProperty("mail.transport.protocol", protocol); return properties; } - - private Properties velocityProperties() { - final Properties properties = new Properties(); - properties.setProperty("resource.loader", "class"); - properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - properties.setProperty("velocimacro.permissions.allow.inline.local.scope", "false"); - properties.setProperty("runtime.log.logsystem.log4j.logger", "velocity"); - properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogChute"); - return properties; - } - + } diff --git a/src/main/java/org/genesys2/spring/config/OAuth2ServerConfig.java b/src/main/java/org/genesys2/spring/config/OAuth2ServerConfig.java index d93f11331559719aa115ccfde3e6ed9b2524b137..102765378935ff22209d81cbacb465a3df3b06bb 100644 --- a/src/main/java/org/genesys2/spring/config/OAuth2ServerConfig.java +++ b/src/main/java/org/genesys2/spring/config/OAuth2ServerConfig.java @@ -45,7 +45,6 @@ import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; @Configuration -@Import(SwaggerConfig.class) public class OAuth2ServerConfig { private static final String APPLICATION_RESOURCE_ID = "genesys"; diff --git a/src/main/java/org/genesys2/spring/config/SecurityConfig.java b/src/main/java/org/genesys2/spring/config/SecurityConfig.java index 85688efc21b0dc9f0fddd3668f18e18d94f23ab0..59ea1770fa1ff4848c74d5b459a0a70aede44fd6 100644 --- a/src/main/java/org/genesys2/spring/config/SecurityConfig.java +++ b/src/main/java/org/genesys2/spring/config/SecurityConfig.java @@ -25,7 +25,6 @@ import org.genesys.blocks.security.service.PasswordPolicy; import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; import org.genesys.blocks.security.service.impl.SimplePasswordPolicy; import org.genesys2.server.cache.HazelcastAclCache; -import org.genesys2.server.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; @@ -37,24 +36,16 @@ import org.springframework.security.acls.domain.AuditLogger; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; import org.springframework.security.acls.jdbc.BasicLookupStrategy; import org.springframework.security.acls.jdbc.JdbcMutableAclService; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.session.SessionRegistry; +import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) +//@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) @Import({ AccountLockoutConfig.class }) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private UserService userDetailsService; +public class SecurityConfig { @Autowired private DataSource dataSource; @@ -62,6 +53,16 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CacheManager cacheManager; + /** + * Session registry. + * + * @return the session registry + */ + @Bean + public SessionRegistry SessionRegistry() { + return new SessionRegistryImpl(); + } + @Bean(name = "permissionEvaluator") public AclPermissionEvaluator aclPermissionEvaluator() { return new AclPermissionEvaluator(aclService()); @@ -120,47 +121,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { final SimplePasswordPolicy passwordPolicy = new SimplePasswordPolicy(); return passwordPolicy; } - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - /*@formatter:off*/ - http - // No JSESSIONID in URL - .sessionManagement().enableSessionUrlRewriting(false).sessionFixation().migrateSession() - - // Authorizations - .and().authorizeRequests() - // admin - .antMatchers("/admin/**", "/1/admin/**").hasRole("ADMINISTRATOR") - // require login - .antMatchers("/profile/me", "/profile/me/**", "/oauth/authorize", "/swagger-**").fullyAuthenticated() - - // access denied - .and().exceptionHandling().accessDeniedPage("/access-denied") - - // CSRF - .and().csrf() - - // cors - .and().cors() - - // Logout and login - .and().logout().logoutUrl("/logout").logoutSuccessUrl("/") - - // Login form - .and().formLogin().permitAll().loginPage("/login").failureUrl("/login?error=1").loginProcessingUrl("/login-attempt").defaultSuccessUrl("/"); - /*@formatter:on*/ - } - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - } diff --git a/src/main/java/org/genesys2/spring/config/TemplatingConfig.java b/src/main/java/org/genesys2/spring/config/TemplatingConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..9796b732c3139b9e87a47938e2d358564d86db89 --- /dev/null +++ b/src/main/java/org/genesys2/spring/config/TemplatingConfig.java @@ -0,0 +1,44 @@ +/* + * 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.genesys2.spring.config; + +import java.util.Properties; + +import org.apache.velocity.app.VelocityEngine; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TemplatingConfig { + + @Bean + public VelocityEngine velocityEngine() { + final VelocityEngine engine = new VelocityEngine(velocityProperties()); + return engine; + } + + private Properties velocityProperties() { + final Properties properties = new Properties(); + properties.setProperty("resource.loader", "class"); + properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + properties.setProperty("velocimacro.permissions.allow.inline.local.scope", "false"); + properties.setProperty("runtime.log.logsystem.log4j.logger", "velocity"); + properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogChute"); + return properties; + } + +} diff --git a/src/main/java/org/genesys2/spring/config/WebConfiguration.java b/src/main/java/org/genesys2/spring/config/WebConfiguration.java index 56ca71c22f48bf9571672413e0a3893c99654c28..1015d24dd92aab43a5a1e64ce4644958d0a61c79 100644 --- a/src/main/java/org/genesys2/spring/config/WebConfiguration.java +++ b/src/main/java/org/genesys2/spring/config/WebConfiguration.java @@ -34,7 +34,6 @@ import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.Scope; import org.springframework.http.CacheControl; import org.springframework.http.converter.ByteArrayHttpMessageConverter; @@ -72,7 +71,6 @@ import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; */ @Configuration @EnableWebMvc -@EnableAspectJAutoProxy @ComponentScan(basePackages = { "org.genesys2.server.servlet.filter", "org.genesys2.server.mvc", "org.genesys2.server.api", "org.genesys.catalog.service", "org.genesys.catalog.server.util", "org.genesys.catalog.mvc", "org.genesys.catalog.api" }) public class WebConfiguration extends WebMvcConfigurerAdapter { @@ -80,7 +78,7 @@ public class WebConfiguration extends WebMvcConfigurerAdapter { @Value("${theme.defaultThemeName}") private String defaultThemeName; - @Autowired + @Autowired(required = false) private AddStuffInterceptor addStuffInterceptor; @Autowired(required = false) @@ -168,7 +166,9 @@ public class WebConfiguration extends WebMvcConfigurerAdapter { if (requestTrackingInterceptor != null) { registry.addInterceptor(requestTrackingInterceptor); } - registry.addInterceptor(addStuffInterceptor); + if (addStuffInterceptor != null) { + registry.addInterceptor(addStuffInterceptor); + } } @Override diff --git a/src/main/java/org/genesys2/spring/config/WebSecurityConfig.java b/src/main/java/org/genesys2/spring/config/WebSecurityConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..a6563f61214caaaa5103fc643780487d26617a57 --- /dev/null +++ b/src/main/java/org/genesys2/spring/config/WebSecurityConfig.java @@ -0,0 +1,92 @@ +/* + * 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.genesys2.spring.config; + +import org.genesys2.server.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.acls.AclPermissionEvaluator; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserService userDetailsService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private AclPermissionEvaluator aclPermissionEvaluator; + + @Bean + public DefaultWebSecurityExpressionHandler webExpressionHandler() { + final DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); + handler.setPermissionEvaluator(aclPermissionEvaluator); + return handler; + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + /*@formatter:off*/ + http + // No JSESSIONID in URL + .sessionManagement().enableSessionUrlRewriting(false).sessionFixation().migrateSession() + + // Authorizations + .and().authorizeRequests() + // admin + .antMatchers("/admin/**", "/1/admin/**").hasRole("ADMINISTRATOR") + // require login + .antMatchers("/profile/me", "/profile/me/**", "/oauth/authorize", "/swagger-**").fullyAuthenticated() + + // access denied + .and().exceptionHandling().accessDeniedPage("/access-denied") + + // CSRF + .and().csrf() + + // cors + .and().cors() + + // Logout and login + .and().logout().logoutUrl("/logout").logoutSuccessUrl("/") + + // Login form + .and().formLogin().permitAll().loginPage("/login").failureUrl("/login?error=1").loginProcessingUrl("/login-attempt").defaultSuccessUrl("/"); + /*@formatter:on*/ + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + +} diff --git a/src/test/java/org/genesys/hamcrest/Matchers.java b/src/test/java/org/genesys/hamcrest/Matchers.java new file mode 100644 index 0000000000000000000000000000000000000000..f1bee984fdd0c8552dc5089b6ba500c302773924 --- /dev/null +++ b/src/test/java/org/genesys/hamcrest/Matchers.java @@ -0,0 +1,53 @@ +/* + * 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.hamcrest; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +/** + * Custom Hamcrest matchers + * + * @author Matija Obreza + */ +public abstract class Matchers { + + /** + * Check if object's toString() is successfully parsed by Integer.parseInt() + * + * @return + */ + public final static Matcher parsesToInt() { + return new BaseMatcher() { + @Override + public boolean matches(final Object item) { + try { + Integer.parseInt(item.toString()); + return true; + } catch (final NumberFormatException e) { + } + return false; + } + + @Override + public void describeTo(final Description description) { + description.appendText("Something that can be parsed by Integer.parseInt()"); + } + }; + } + +} diff --git a/src/test/java/org/genesys/test/base/AbstractApiTest.java b/src/test/java/org/genesys/test/base/AbstractApiTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f6c177cd1324dba5726d99cfe907292ba4a812ba --- /dev/null +++ b/src/test/java/org/genesys/test/base/AbstractApiTest.java @@ -0,0 +1,140 @@ +/* + * 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.test.base; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; + +import java.util.HashSet; +import java.util.UUID; + +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.dataset.Dataset; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.persistence.PartnerRepository; +import org.genesys.catalog.persistence.dataset.DatasetRepository; +import org.genesys.catalog.persistence.traits.DescriptorRepository; +import org.genesys.catalog.service.DatasetService; +import org.genesys.catalog.service.ShortFilterService; +import org.genesys.test.config.ApplicationConfig; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("dev") +@WebAppConfiguration +@ContextHierarchy(@ContextConfiguration(name = "api", classes = { ApplicationConfig.WebAppConfig.class })) +public abstract class AbstractApiTest extends AbstractTest { + + @Autowired + protected ObjectMapper objectMapper; + protected static final ObjectMapper verboseMapper = new ObjectMapper(); + + @Autowired + private WebApplicationContext webApplicationContext; + @Autowired + protected DatasetRepository datasetRepository; + @Autowired + private PartnerRepository partnerRepository; + @Autowired + protected DescriptorRepository descriptorRepository; + @Autowired + protected DatasetService datasetService; + @Autowired + protected ShortFilterService shortFilterService; + + protected MockMvc mockMvc; + @Rule + public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets"); + + public AbstractApiTest() { + super(); + } + + @Before + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(restDocumentation).uris().withScheme("https").withHost( + "api.catalog.genesys-pgr.org").withPort(443)).build(); + } + + @After + @Override + public void cleanup() throws Exception { + datasetRepository.deleteAll(); + partnerRepository.deleteAll(); + super.cleanup(); + } + + protected Dataset setUpDataset(final boolean published) { + return setupDataset("Test Dataset Title", "Test Dataset Description", setUpPartner("Partner", true, "PartnerShortName", UUID.randomUUID()), published); + } + + protected Dataset setupDataset(final String title, final String description, final Partner owner, final boolean published) { + final Dataset input = new Dataset(); + input.setTitle(title); + input.setDescription(description); + input.setOwner(owner); + // input.setAccessionIdentifiers(accessions); + input.setPublished(published); + return input; + } + + protected Partner setUpPartner(final String name, final boolean isActive, final String shortName, final UUID uuid) { + final Partner partner = new Partner(); + partner.setName(name); + partner.setActive(isActive); + partner.setShortName(shortName); + partner.setUuid(uuid); + partner.setWiewsCodes(new HashSet<>()); + partner.setUrls(new HashSet<>()); + return partnerRepository.save(partner); + } + + protected Descriptor setUpDescriptor() { + + final Descriptor descriptor = new Descriptor(); + descriptor.setUuid(UUID.randomUUID()); + descriptor.setCategory(Descriptor.Category.PASSPORT); + descriptor.setDataType(Descriptor.DataType.BOOLEAN); + descriptor.setTitle("Title"); + descriptor.setVocabulary(null); + descriptor.setMinValue(null); + descriptor.setMaxValue(null); + descriptor.setVersionTag("1.0"); + descriptor.setOwner(setUpPartner("NewPartner", true, "ShortName", UUID.randomUUID())); + descriptor.setCrop("banana"); + descriptor.setPublished(true); + + return descriptor; + } + +} \ No newline at end of file diff --git a/src/test/java/org/genesys/test/base/AbstractServiceTest.java b/src/test/java/org/genesys/test/base/AbstractServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..13e31dd7a040398577a63637511b29cf26a13ebc --- /dev/null +++ b/src/test/java/org/genesys/test/base/AbstractServiceTest.java @@ -0,0 +1,47 @@ +/* + * 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.test.base; + +import org.genesys.test.config.ApplicationConfig; +import org.junit.After; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("dev") +@ContextHierarchy(@ContextConfiguration(name = "services", classes = { ApplicationConfig.BaseConfig.class })) +public abstract class AbstractServiceTest extends AbstractTest { + + @Before + @Transactional + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + } + + @After + @Transactional + @Override + public void cleanup() throws Exception { + super.cleanup(); + } + +} \ No newline at end of file diff --git a/src/test/java/org/genesys/test/base/AbstractTest.java b/src/test/java/org/genesys/test/base/AbstractTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f6bff0d0c3ffbfe5a23ef258754e8cfa8aac1842 --- /dev/null +++ b/src/test/java/org/genesys/test/base/AbstractTest.java @@ -0,0 +1,40 @@ +package org.genesys.test.base; + +import org.genesys.blocks.auditlog.persistence.AuditLogRepository; +import org.genesys.blocks.persistence.ClassPKRepository; +import org.junit.After; +import org.junit.Before; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +/** + * Do not touch + * + * @author Matija Obreza + */ +public abstract class AbstractTest { + + protected final Logger LOG = LoggerFactory.getLogger(getClass()); + + @Autowired + private AuditLogRepository auditLogRepo; + @Autowired + private ClassPKRepository classPKRepository; + + + @Transactional + @Before + public void beforeTest() throws Exception { + cleanup(); + } + + @Transactional + @After + public void cleanup() throws Exception { + auditLogRepo.deleteAll(); + classPKRepository.deleteAll(); + } + +} diff --git a/src/test/java/org/genesys/test/base/NoContextTest.java b/src/test/java/org/genesys/test/base/NoContextTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2c1a89c0db836f22e02d238b0df9a39a0a872ed9 --- /dev/null +++ b/src/test/java/org/genesys/test/base/NoContextTest.java @@ -0,0 +1,15 @@ +package org.genesys.test.base; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Do not touch + * + * @author Matija Obreza + */ +public abstract class NoContextTest { + + protected final Logger LOG = LoggerFactory.getLogger(getClass()); + +} diff --git a/src/test/java/org/genesys/test/base/WithMockOAuth2Authentication.java b/src/test/java/org/genesys/test/base/WithMockOAuth2Authentication.java new file mode 100644 index 0000000000000000000000000000000000000000..e1465dc780a5d8001588206b8193c6575c004e87 --- /dev/null +++ b/src/test/java/org/genesys/test/base/WithMockOAuth2Authentication.java @@ -0,0 +1,41 @@ +/* + * 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.test.base; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import org.springframework.security.test.context.support.WithSecurityContext; + +/** + * Based on + * https://stackoverflow.com/questions/29510759/how-to-test-spring-security-oauth2-resource-server-security/40921028#40921028 + */ +@Retention(RetentionPolicy.RUNTIME) +@WithSecurityContext(factory = WithMockOAuth2AuthenticationSecurityContextFactory.class) +public @interface WithMockOAuth2Authentication { + + /** + * User authorities + */ + String[] roles() default { "USER" }; + + /** + * OAuth client scopes + */ + String[] scopes() default { "write" }; + +} diff --git a/src/test/java/org/genesys/test/base/WithMockOAuth2AuthenticationSecurityContextFactory.java b/src/test/java/org/genesys/test/base/WithMockOAuth2AuthenticationSecurityContextFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..2173110607c5b7fafb60a926e7fbc74eafaa9e79 --- /dev/null +++ b/src/test/java/org/genesys/test/base/WithMockOAuth2AuthenticationSecurityContextFactory.java @@ -0,0 +1,73 @@ +/* + * 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.test.base; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.genesys.blocks.security.model.BasicUser; +import org.genesys2.server.model.UserRole; +import org.genesys2.server.model.impl.User; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.OAuth2Request; + +import com.google.common.collect.Sets; +import org.springframework.security.test.context.support.WithSecurityContextFactory; + +/** + * https://stackoverflow.com/questions/29510759/how-to-test-spring-security-oauth2-resource-server-security/40921028#40921028 + */ +public class WithMockOAuth2AuthenticationSecurityContextFactory implements WithSecurityContextFactory { + + private static final Long USER_ID = -10l; + private static final UUID USER_UUID = UUID.randomUUID(); + + @Override + public SecurityContext createSecurityContext(final WithMockOAuth2Authentication mockOAuth2Auth) { + final SecurityContext context = SecurityContextHolder.createEmptyContext(); + + final Set scopes = Sets.newHashSet(mockOAuth2Auth.scopes()); + + final String clientId = "mockmvc-oauth2-client"; + final Collection clientAuthorities = new HashSet<>(); + clientAuthorities.add(new SimpleGrantedAuthority("ROLE_CLIENT")); + final OAuth2Request request = new OAuth2Request(null, clientId, clientAuthorities, true, scopes, null, null, null, null); + + final BasicUser principal = new User(); + principal.setId(USER_ID); + principal.setUuid(USER_UUID.toString()); + principal.setEmail("user@example.com"); + principal.setPrincipal(true); + final Collection userAuthorities = Arrays.stream(mockOAuth2Auth.roles()).map(role -> UserRole.valueOf(role)).collect(Collectors.toSet()); + + final Authentication userAuthentication = new UsernamePasswordAuthenticationToken(principal, null, userAuthorities); + final Authentication auth = new OAuth2Authentication(request, userAuthentication); + + context.setAuthentication(auth); + + return context; + } +} diff --git a/src/test/java/org/genesys/test/catalog/api/v0/DatasetControllerTest.java b/src/test/java/org/genesys/test/catalog/api/v0/DatasetControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..bb6064f3f8923487bdd9fb6fdd6f353311dc4bea --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/api/v0/DatasetControllerTest.java @@ -0,0 +1,353 @@ +/* + * 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.test.catalog.api.v0; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import org.genesys.blocks.model.filters.StringFilter; +import org.genesys.catalog.api.v0.DatasetController; +import org.genesys.catalog.model.dataset.AccessionIdentifier; +import org.genesys.catalog.model.dataset.Dataset; +import org.genesys.catalog.model.filters.DatasetFilter; +import org.genesys.catalog.model.filters.PartnerFilter; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.test.base.AbstractApiTest; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.security.test.context.support.WithMockUser; + +import com.google.common.collect.Sets; + +/** + * @author Andrey Lugovskoy. + */ +public class DatasetControllerTest extends AbstractApiTest { + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void getDataset() throws Exception { + Dataset dataset = setUpDataset(false); + dataset = datasetService.createDataset(dataset); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.get(DatasetController.CONTROLLER_URL.concat("/{UUID}"), dataset.getUuid())) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andDo(document("contract-roles-get")); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void publishDataset() throws Exception { + Dataset dataset = setUpDataset(false); + dataset = datasetService.createDataset(dataset); + + /*@formatter:off*/ + mockMvc + .perform(post(DatasetController.CONTROLLER_URL.concat("/publish")) + .param("uuid", dataset.getUuid().toString()) + .param("version", dataset.getVersion().toString())) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andExpect(jsonPath("$.published", is(true))) + // .andExpect(jsonPath("$.version", is(dataset.getVersion() + 1))) + .andDo(document("dataset-publish")); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void unpublishDataset() throws Exception { + Dataset dataset = setUpDataset(false); + dataset = datasetService.createDataset(dataset); + + /*@formatter:off*/ + mockMvc + .perform(post(DatasetController.CONTROLLER_URL.concat("/publish")) + .param("uuid", dataset.getUuid().toString()) + .param("version", dataset.getVersion().toString())) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.published", is(true))) + // .andExpect(jsonPath("$.version", is(dataset.getVersion() + 1))) + ; + + mockMvc + .perform(post(DatasetController.CONTROLLER_URL.concat("/publish")) + .param("uuid", dataset.getUuid().toString()) + .param("version", "" + (dataset.getVersion() + 1)) + .param("published", "false")) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.published", is(false))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "USER") + @Ignore + public void getDatasetNotFound() throws Exception { + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.get(DatasetController.CONTROLLER_URL.concat("/{UUID}"), UUID.randomUUID()) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isNotFound()); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void listDataset() throws Exception { + final DatasetFilter datasetFilter = new DatasetFilter(); + final PartnerFilter partnerFilter = new PartnerFilter(); + partnerFilter.shortName = new HashSet<>(); + partnerFilter.shortName.add("PartnerShortNameTwo"); + datasetFilter.owner = partnerFilter; + + datasetService.createDataset(setUpDataset(false)); + final Dataset dataset2 = datasetService.createDataset(setupDataset("Test Dataset Title Two", "Test Dataset Description Two", setUpPartner("PartnerTwo", true, + "PartnerShortNameTwo", UUID.randomUUID()), true)); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL.concat("/list")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(datasetFilter))) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.filterCode", not(nullValue()))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0].id", is(dataset2.getId().intValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void listDatasetsByFilterCodeTest() throws Exception { + + final Dataset dataset = datasetService.createDataset(setupDataset("Test Dataset Title Two", "Test Dataset Description Two", setUpPartner("PartnerTwo", true, + "PartnerShortNameTwo", UUID.randomUUID()), true)); + datasetService.createDataset(setUpDataset(true)); + assertThat(datasetRepository.count(), is(2L)); + // datasetRepository.findAll().forEach(ds -> { + // LOG.info(ds + " publ=" + ds.isPublished() + " title=" + + // ds.getTitle() + " p=" + ds.getOwner().getShortName()); + // }); + + final DatasetFilter datasetFilter = new DatasetFilter(); + final StringFilter datasetTitle = new StringFilter(); + datasetTitle.contains = "two"; + datasetFilter.title = datasetTitle; + final PartnerFilter partnerFilter = new PartnerFilter(); + partnerFilter.shortName = new HashSet<>(); + partnerFilter.shortName.add("PartnerShortNameTwo"); + datasetFilter.owner = partnerFilter; + + final String filterCode = shortFilterService.getCode(datasetFilter); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/list?f={filterCode}", filterCode) + .contentType(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.filterCode", is(filterCode))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", is(dataset.getUuid().toString()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void createDataset() throws Exception { + final Dataset dataset = setUpDataset(false); + + final String s = verboseMapper.writeValueAsString(dataset); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/create") + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void updateDataset() throws Exception { + + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + dataset.setTitle("Title 2"); + final String s = verboseMapper.writeValueAsString(dataset); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/update") + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andExpect(jsonPath("$.title", is("Title 2"))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void updateDatasetCrops() throws Exception { + + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + dataset.setTitle("Title 2"); + dataset.setCrops(Sets.newHashSet("yam", "cassava")); + final String s = verboseMapper.writeValueAsString(dataset); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/update") + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andExpect(jsonPath("$.title", is("Title 2"))) + .andExpect(jsonPath("$.crops", hasSize(2))) + .andExpect(jsonPath("$.crops", containsInAnyOrder("cassava", "yam"))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void upsertAccessions() throws Exception { + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + + final Set accessionIdentifiers = new HashSet() { + /** + * + */ + private static final long serialVersionUID = 6718121172547984782L; + + { + final AccessionIdentifier accessionIdentifier = new AccessionIdentifier(); + accessionIdentifier.setAcceNumb("TestAccNum"); + accessionIdentifier.setGenus("TestGen"); + accessionIdentifier.setInstCode("InstCode"); + add(accessionIdentifier); + } + }; + + final String s = verboseMapper.writeValueAsString(accessionIdentifiers); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/upsertaccessions/{UUID},{version}", dataset.getUuid(), dataset.getVersion()) + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andExpect(jsonPath("$.accessionIdentifiers[0].acceNumb", is("TestAccNum"))) + .andExpect(jsonPath("$.accessionIdentifiers[0].instCode", is("InstCode"))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void addDescriptorTest() throws Exception { + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + + final Descriptor descriptor = descriptorRepository.save(setUpDescriptor()); + + final String s = verboseMapper.writeValueAsString(new UUID[] { descriptor.getUuid() }); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/add-descriptors/{UUID},{version}", dataset.getUuid(), dataset.getVersion()) + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andExpect(jsonPath("$.descriptors[0].uuid", is(descriptor.getUuid().toString()))) + .andExpect(jsonPath("$.descriptors[0].crop", is(descriptor.getCrop()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void removeDescriptorTest() throws Exception { + final Descriptor descriptor = descriptorRepository.save(setUpDescriptor()); + Dataset dataset = datasetService.createDataset(setUpDataset(false)); + dataset = datasetService.addDescriptors(dataset, descriptor); + + final String s = verboseMapper.writeValueAsString(new UUID[] { descriptor.getUuid() }); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/remove-descriptors/{UUID},{version}", dataset.getUuid(), dataset.getVersion()) + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(dataset.getUuid().toString()))) + .andExpect(jsonPath("$.descriptors", is(empty()))); + /*@formatter:on*/ + } + +} diff --git a/src/test/java/org/genesys/test/catalog/api/v0/DatasetCreatorControllerTest.java b/src/test/java/org/genesys/test/catalog/api/v0/DatasetCreatorControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..18cb41319b094c1161ca0aa992d66b8552e5b848 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/api/v0/DatasetCreatorControllerTest.java @@ -0,0 +1,133 @@ +/* + * 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.test.catalog.api.v0; + +import static org.hamcrest.Matchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import org.genesys.catalog.api.v0.DatasetCreatorController; +import org.genesys.catalog.model.dataset.Dataset; +import org.genesys.catalog.model.dataset.DatasetCreator; +import org.genesys.catalog.service.DatasetCreatorService; +import org.genesys.test.base.AbstractApiTest; +import org.genesys.test.base.WithMockOAuth2Authentication; +import org.junit.After; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.security.test.context.support.WithMockUser; + +/** + * @author Andrey Lugovskoy. + */ +@WithMockUser(username = "user", password = "user", roles = "USER") +public class DatasetCreatorControllerTest extends AbstractApiTest { + + @Autowired + private DatasetCreatorService datasetCreatorService; + + @After + @Override + public void cleanup() throws Exception { + super.cleanup(); + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void listDatasetCreators() throws Exception { + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset); + final DatasetCreator creator = datasetCreatorService.createDatasetCreator(dataset, datasetCreator); + + /*@formatter:off*/ + this.mockMvc.perform(RestDocumentationRequestBuilders.get(DatasetCreatorController.CONTROLLER_URL.concat("/list"), dataset.getUuid())) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].id", is(creator.getId().intValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void loadByUuid() throws Exception { + final Dataset dataset = datasetService.createDataset(setUpDataset(true)); + final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset); + final DatasetCreator creator = datasetCreatorService.createDatasetCreator(dataset, datasetCreator); + + /*@formatter:off*/ + this.mockMvc.perform(RestDocumentationRequestBuilders.get(DatasetCreatorController.CONTROLLER_URL.concat("/{creatorUuid}"), dataset.getUuid(), + creator.getUuid())) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.id", is(creator.getId().intValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void createDatasetCreator() throws Exception { + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset); + + final String s = verboseMapper.writeValueAsString(datasetCreator); + + /*@formatter:off*/ + mockMvc.perform(RestDocumentationRequestBuilders.post(DatasetCreatorController.CONTROLLER_URL + "/create", dataset.getUuid()) + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.fullName", equalTo(datasetCreator.getFullName()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void deleteDatasetCreator() throws Exception { + final Dataset dataset = datasetService.createDataset(setUpDataset(false)); + final DatasetCreator datasetCreator = buildDatasetCreator("TestFullName", "TestEmailName", "0673579007", dataset); + final DatasetCreator creator = datasetCreatorService.createDatasetCreator(dataset, datasetCreator); + final String s = verboseMapper.writeValueAsString(creator); + + /*@formatter:off*/ + mockMvc.perform(RestDocumentationRequestBuilders.post(DatasetCreatorController.CONTROLLER_URL + "/delete", + dataset.getUuid(), creator.getUuid()) + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()); + /*@formatter:on*/ + } + + protected DatasetCreator buildDatasetCreator(final String fullName, final String email, final String phoneNumber, final Dataset dataset) { + final DatasetCreator datasetCreator = new DatasetCreator(); + datasetCreator.setDataset(dataset); + datasetCreator.setFullName(fullName); + datasetCreator.setRole(DatasetCreator.DatasetCreatorRole.MANAGER); + datasetCreator.setEmail(email); + datasetCreator.setPhoneNumber(phoneNumber); + return datasetCreator; + } +} diff --git a/src/test/java/org/genesys/test/catalog/api/v0/DescriptorControllerTest.java b/src/test/java/org/genesys/test/catalog/api/v0/DescriptorControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..61be409f82d3cbf8ba295b5837acde3c38dc8478 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/api/v0/DescriptorControllerTest.java @@ -0,0 +1,283 @@ +/* + * 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.test.catalog.api.v0; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.util.UUID; + +import org.genesys.blocks.model.filters.StringFilter; +import org.genesys.catalog.api.v0.DescriptorController; +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.filters.DescriptorFilter; +import org.genesys.catalog.model.filters.PartnerFilter; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.model.traits.Descriptor.Category; +import org.genesys.catalog.model.traits.Descriptor.DataType; +import org.genesys.catalog.model.vocab.VocabularyTerm; +import org.genesys.catalog.persistence.PartnerRepository; +import org.genesys.catalog.persistence.traits.DescriptorRepository; +import org.genesys.test.base.AbstractApiTest; +import org.genesys.test.base.WithMockOAuth2Authentication; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +import com.google.common.collect.Lists; + +/** + * @author Matija Obreza. + * @author Andrey Lugovskoy. + */ +public class DescriptorControllerTest extends AbstractApiTest { + + private static final String CROPNAME = "banana"; + + private static final String PARTNER_NAME = "Partner Name"; + + protected static final String TERM_CODE_1 = "T1"; + protected static final String TERM_CODE_2 = "T2"; + protected static final String TERM_CODE_3 = "T3"; + protected static final String TERM_CODE_4 = "T4"; + protected static final String TERM_TITLE_1 = "Term title 1"; + protected static final String TERM_TITLE_2 = "Term title 2"; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Autowired + private DescriptorRepository descriptorRepository; + + @Autowired + private PartnerRepository partnerRepository; + + MockMvc mockMvc; + + private Partner partner; + + @Before + @Transactional + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + + { + final Partner partner = new Partner(); + partner.setName(PARTNER_NAME); + partner.setActive(true); + partner.setShortName("P1"); + partner.setUuid(UUID.randomUUID()); + this.partner = partnerRepository.save(partner); + } + + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(restDocumentation).uris().withScheme("https").withHost( + "api.catalog.genesys-pgr.org").withPort(443)).build(); + } + + @After + @Override + public void cleanup() throws Exception { + descriptorRepository.deleteAll(); + partnerRepository.deleteAll(); + super.cleanup(); + } + + @Test + public void listDescriptorCategories() throws Exception { + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.get(DescriptorController.CONTROLLER_URL + "/categories") + .accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.[0]", is(Category.PASSPORT.toString()))) + .andExpect(jsonPath("$.[1]", is(Category.MANAGEMENT.toString()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void listDescriptorsTest() throws Exception { + createDescriptorTest(); + + final DescriptorFilter descriptorFilter = new DescriptorFilter(); + final PartnerFilter partnerFilter = new PartnerFilter(); + partnerFilter.name = StringFilter.eq(PARTNER_NAME); + descriptorFilter.owner = partnerFilter; + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorController.CONTROLLER_URL.concat("/list")) + .contentType(MediaType.APPLICATION_JSON) + .content(verboseMapper.writeValueAsString(descriptorFilter))) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.filterCode", not(nullValue()))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", not(nullValue()))) + .andExpect(jsonPath("$.content[0].owner", not(nullValue()))) + .andExpect(jsonPath("$.content[0].owner.uuid", is(partner.getUuid().toString()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void listDescriptorsByFilterCodeTest() throws Exception { + final Descriptor descriptor = descriptorRepository.save(setUpDescriptor(true)); + assertThat(descriptorRepository.count(), is(1L)); + + final DescriptorFilter filter = new DescriptorFilter(); + filter.title = new StringFilter(); + filter.title.eq = descriptor.getTitle(); + // filter.owner = new PartnerFilter(); + // final StringFilter partnerName = new StringFilter(); + // partnerName.eq = partner.getName(); + // filter.owner.name = partnerName; + + final String filterCode = shortFilterService.getCode(filter); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorController.CONTROLLER_URL + "/list?f={filterCode}", filterCode) + .contentType(MediaType.APPLICATION_JSON)) + //.andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.filterCode", is(filterCode))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", is(descriptor.getUuid().toString()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "USER" }, scopes = { "write" }) + public void getDescriptorTest() throws Exception { + final Descriptor descriptor = descriptorRepository.save(setUpDescriptor(true)); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.get(DescriptorController.CONTROLLER_URL.concat("/{UUID}"), descriptor.getUuid())) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void updateDescriptorTest() throws Exception { + final Descriptor descriptor = descriptorRepository.save(setUpDescriptor(false)); + final Descriptor newDescriptor = new Descriptor(); + newDescriptor.apply(descriptor); + newDescriptor.setTitle("Test title 2"); + newDescriptor.setDataType(DataType.TEXT); + final String s = verboseMapper.writeValueAsString(newDescriptor); + + /*@formatter:off*/ + mockMvc + .perform( + RestDocumentationRequestBuilders + .post(DescriptorController.CONTROLLER_URL + "/update") + .content(s) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.title", is(newDescriptor.getTitle()))) + .andExpect(jsonPath("$.dataType", is(DataType.TEXT.toString()))) + .andExpect(jsonPath("$.uuid", is(descriptor.getUuid().toString()))) + .andExpect(jsonPath("$.owner", not(nullValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void createDescriptorTest() throws Exception { + + final String s = verboseMapper.writeValueAsString(setUpDescriptor(true)); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorController.CONTROLLER_URL + "/create") + .content(s) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.crop", is(CROPNAME))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void createCodedDescriptorTest() throws Exception { + final Descriptor input = setUpDescriptor(true); + input.setDataType(DataType.CODED); + input.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2))); + + final String s = verboseMapper.writeValueAsString(input); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorController.CONTROLLER_URL + "/create") + .content(s) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.crop", is(CROPNAME))) + .andExpect(jsonPath("$.terms", not(nullValue()))) + .andExpect(jsonPath("$.terms", hasSize(2))); + /*@formatter:on*/ + } + + private Descriptor setUpDescriptor(final boolean published) { + final Descriptor descriptor = new Descriptor(); + descriptor.setOwner(partner); + descriptor.setUuid(UUID.randomUUID()); + descriptor.setCategory(Category.PASSPORT); + descriptor.setDataType(DataType.BOOLEAN); + descriptor.setTitle("Title"); + descriptor.setVocabulary(null); + descriptor.setMinValue(null); + descriptor.setMaxValue(null); + descriptor.setVersionTag("1.0"); + descriptor.setCrop(CROPNAME); + descriptor.setPublished(published); + + return descriptor; + } +} diff --git a/src/test/java/org/genesys/test/catalog/api/v0/DescriptorListControllerTest.java b/src/test/java/org/genesys/test/catalog/api/v0/DescriptorListControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3fa4d32f67f2b3ffdbcde660fd56c47a6ec2037b --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/api/v0/DescriptorListControllerTest.java @@ -0,0 +1,321 @@ +/* + * 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.test.catalog.api.v0; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.util.UUID; + +import org.genesys.blocks.model.filters.StringFilter; +import org.genesys.catalog.api.v0.DescriptorListController; +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.filters.DescriptorListFilter; +import org.genesys.catalog.model.traits.DescriptorList; +import org.genesys.catalog.persistence.PartnerRepository; +import org.genesys.catalog.persistence.traits.DescriptorListRepository; +import org.genesys.catalog.persistence.traits.DescriptorRepository; +import org.genesys.test.base.AbstractApiTest; +import org.genesys.test.base.WithMockOAuth2Authentication; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * @author Matija Obreza. + * @author Andrey Lugovskoy. + */ +public class DescriptorListControllerTest extends AbstractApiTest { + + private static final String CROPNAME = "banana"; + + private static final String PARTNER_NAME = "Partner Name"; + + private static final String URL = "https://my-test-url.net"; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Autowired + private DescriptorListRepository descriptorListRepository; + + @Autowired + private DescriptorRepository descriptorRepository; + + @Autowired + private PartnerRepository partnerRepository; + + MockMvc mockMvc; + + private Partner partner; + + @Before + @Transactional + public void setUp() { + + { + final Partner partner = new Partner(); + partner.setName(PARTNER_NAME); + partner.setActive(true); + partner.setShortName("P1"); + partner.setUuid(UUID.randomUUID()); + this.partner = partnerRepository.save(partner); + } + + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(restDocumentation).uris().withScheme("https").withHost( + "api.catalog.genesys-pgr.org").withPort(443)).build(); + } + + @After + @Override + public void cleanup() throws Exception { + descriptorListRepository.deleteAll(); + descriptorRepository.deleteAll(); + partnerRepository.deleteAll(); + super.cleanup(); + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "USER") + public void createDescriptorListTest() throws Exception { + final String s = verboseMapper.writeValueAsString(setUpDescriptorList(true, UUID.randomUUID(), "Des 1", "Title 1", "Vt 1")); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorListController.CONTROLLER_URL + "/create") + .content(s) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.url", is(URL))) + .andExpect(jsonPath("$.crop", is(CROPNAME))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void updateDescriptorListTest() throws Exception { + DescriptorList descriptorList = setUpDescriptorList(false, UUID.randomUUID(), "Des 2", "Title 2", "Vt 2"); + descriptorList = descriptorListRepository.save(descriptorList); + + descriptorList.setTitle("Title 1"); + descriptorList.setDescription("Updated description"); + descriptorList.setUrl("https://new-test-url.net"); + final String s = verboseMapper.writeValueAsString(descriptorList); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorListController.CONTROLLER_URL + "/update") + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(descriptorList.getUuid().toString()))) + .andExpect(jsonPath("$.title", is(descriptorList.getTitle()))) + .andExpect(jsonPath("$.url", is(descriptorList.getUrl()))) + .andExpect(jsonPath("$.description", is(descriptorList.getDescription()))) + .andExpect(jsonPath("$.versionTag", is(descriptorList.getVersionTag()))); + /*@formatter:on */ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + @Ignore + public void failUpdatePublishedDescriptorListTest() throws Exception { + DescriptorList descriptorList = setUpDescriptorList(true, UUID.randomUUID(), "Des 2", "Title 2", "Vt 2"); + descriptorList = descriptorListRepository.save(descriptorList); + + descriptorList.setTitle("Updated title"); + final String s = verboseMapper.writeValueAsString(descriptorList); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorListController.CONTROLLER_URL + "/update") + .content(s) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.error", not(nullValue()))); + /*@formatter:on */ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void listPublishedDescriptorListsTest() throws Exception { + DescriptorList descriptorList = setUpDescriptorList(true, UUID.randomUUID(), "Des 2", "Title 2", "Vt 2"); + descriptorList = descriptorListRepository.save(descriptorList); + + descriptorListRepository.save(setUpDescriptorList(false, null, "Description 2", "Title 1", "Vt 1")); + assertThat(descriptorListRepository.count(), is(2l)); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorListController.CONTROLLER_URL + "/list") + .content("{}") + .contentType(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.filterCode", not(nullValue()))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", is(descriptorList.getUuid().toString()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void autocompleteTest() throws Exception { + DescriptorList descriptorList = setUpDescriptorList(true, UUID.randomUUID(), "Des 2", "First Title", "Vt 2"); + descriptorList = descriptorListRepository.save(descriptorList); + + descriptorListRepository.save(setUpDescriptorList(false, null, "Description 2", "Second Title", "Vt 1")); + assertThat(descriptorListRepository.count(), is(2l)); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.get(DescriptorListController.CONTROLLER_URL.concat("/autocomplete")) + .param("d", descriptorList.getTitle().substring(0, 4)) + .contentType(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.[0]", not(nullValue()))) + .andExpect(jsonPath("$.[0].description", not(nullValue()))) + .andExpect(jsonPath("$.[0].title", not(nullValue()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void listDescriptorListsByFilterCodeTest() throws Exception { + DescriptorList descriptorList = setUpDescriptorList(true, UUID.randomUUID(), "Test description", "Test title", "Vt 2"); + descriptorList = descriptorListRepository.save(descriptorList); + + assertThat(descriptorListRepository.count(), is(1L)); + + final DescriptorListFilter filter = new DescriptorListFilter(); + filter.description = new StringFilter(); + filter.description.eq = "Test description"; + filter.title = new StringFilter(); + filter.title.contains = "title"; + + final String filterCode = shortFilterService.getCode(filter); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(DescriptorListController.CONTROLLER_URL + "/list/{filterCode}", filterCode) + .contentType(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.filterCode", is(filterCode))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", is(descriptorList.getUuid().toString()))); + /*@formatter:on*/ + } + + @Test + @WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" }) + public void getDescriptorListTest() throws Exception { + final DescriptorList descriptorList = setUpDescriptorList(true, UUID.randomUUID(), "Des 2", "Title 2", "Vt 2"); + descriptorListRepository.save(descriptorList); + final String s = verboseMapper.writeValueAsString(descriptorList); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.get(DescriptorListController.CONTROLLER_URL + "/{UUID}", descriptorList.getUuid()) + .content(s) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(descriptorList.getUuid().toString()))) + .andDo(document("contract-roles-get")); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + @Ignore + public void failRemovePublishedDescriptorList() throws Exception { + final DescriptorList descriptorList = setUpDescriptorList(true, UUID.randomUUID(), "Des 2", "Title 2", "Vt 2"); + descriptorListRepository.save(descriptorList); + + /*@formatter:off*/ + mockMvc.perform(RestDocumentationRequestBuilders + .delete(DescriptorListController.CONTROLLER_URL + "/{UUID},{version}", descriptorList.getUuid(), descriptorList.getVersion()) + .contentType(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isBadRequest()); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void removeDescriptorList() throws Exception { + final DescriptorList descriptorList = setUpDescriptorList(false, UUID.randomUUID(), "Des 2", "Title 2", "Vt 2"); + descriptorListRepository.save(descriptorList); + + /*@formatter:off*/ + mockMvc.perform(RestDocumentationRequestBuilders + .delete(DescriptorListController.CONTROLLER_URL + "/{UUID},{version}", descriptorList.getUuid(), descriptorList.getVersion()) + .contentType(MediaType.APPLICATION_JSON)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()); + /*@formatter:on*/ + } + + private DescriptorList setUpDescriptorList(final boolean published, final UUID uuid, final String description, final String title, final String versionTag) + throws JsonProcessingException { + final DescriptorList o = new DescriptorList(); + o.setOwner(partner); + o.setDescription(description); + o.setCrop(CROPNAME); + o.setPublished(published); + o.setTitle(title); + o.setUrl(URL); + o.setVersionTag(versionTag); + o.setUuid(uuid); + + return o; + } + +} diff --git a/src/test/java/org/genesys/test/catalog/api/v0/PartnerControllerTest.java b/src/test/java/org/genesys/test/catalog/api/v0/PartnerControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..164bd20a2ad4f32c6bbe930abe01da35858f1ecc --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/api/v0/PartnerControllerTest.java @@ -0,0 +1,196 @@ +/* + * 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.test.catalog.api.v0; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.genesys.blocks.model.filters.StringFilter; +import org.genesys.catalog.api.v0.PartnerController; +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.filters.PartnerFilter; +import org.genesys.catalog.persistence.PartnerRepository; +import org.genesys.test.base.AbstractApiTest; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.google.common.collect.Sets; + +/** + * @author Andrey Lugovskoy + * @author Matija Obreza + */ +public class PartnerControllerTest extends AbstractApiTest { + + @Autowired + private WebApplicationContext webApplicationContext; + + @Autowired + private PartnerRepository partnerRepository; + + private MockMvc mockMvc; + + @Before + public void beforeTest() throws Exception { + super.beforeTest(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(restDocumentation).uris().withScheme("https").withHost( + "api.catalog.genesys-pgr.org").withPort(443)).build(); + } + + @After + @Override + public void cleanup() throws Exception { + partnerRepository.deleteAll(); + super.cleanup(); + } + + @Test + public void listPartnersTest() throws Exception { + final PartnerFilter partnerFilter = new PartnerFilter(); + partnerFilter.name = StringFilter.eq("Partner Two"); + Partner partner = partnerRepository.save(setPartner("Partner one", true, "Partner one", UUID.randomUUID())); + partner = partnerRepository.save(setPartner("Partner Two", true, "Partner Two", UUID.randomUUID())); + + /*@formatter:off*/ + this.mockMvc + .perform(RestDocumentationRequestBuilders.post(PartnerController.CONTROLLER_URL.concat("/list")) + .contentType(MediaType.APPLICATION_JSON) + .content(verboseMapper.writeValueAsString(partnerFilter))) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.filterCode", not(nullValue()))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0]", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", is(partner.getUuid().toString()))) + .andExpect(jsonPath("$.content[0].name", is(partner.getName()))); + /*@formatter:on*/ + } + + @Test + public void listPartnersByFilterCodeTest() throws Exception { + final PartnerFilter partnerFilter = new PartnerFilter(); + partnerFilter.name = StringFilter.eq("Partner one"); + + final Partner partner = partnerRepository.save(setPartner("Partner one", true, "Partner one", UUID.randomUUID())); + partnerRepository.save(setPartner("Partner Two", true, "Partner Two", UUID.randomUUID())); + assertThat(partnerRepository.count(), is(2L)); + + final String filterCode = shortFilterService.getCode(partnerFilter); + + /*@formatter:off*/ + mockMvc + .perform(RestDocumentationRequestBuilders.post(PartnerController.CONTROLLER_URL + "/list/{filterCode}", filterCode) + .contentType(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.filterCode", is(filterCode))) + .andExpect(jsonPath("$.filter", not(nullValue()))) + .andExpect(jsonPath("$.content[0].uuid", is(partner.getUuid().toString()))); + /*@formatter:on*/ + } + + @Test + public void getPartnerTest() throws Exception { + final Partner partner = setPartner("Partner one", true, "Partner one", UUID.randomUUID()); + final String s = verboseMapper.writeValueAsString(partnerRepository.save(partner)); + + /*@formatter:off*/ + this.mockMvc + .perform(RestDocumentationRequestBuilders.get(PartnerController.CONTROLLER_URL.concat("/{UUID}"), partner.getUuid()) + .content(s).contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(partner.getUuid().toString()))) + .andExpect(jsonPath("$.wiewsCodes", containsInAnyOrder(partner.getWiewsCodes().toArray()))) + .andExpect(jsonPath("$.urls", containsInAnyOrder(partner.getUrls().stream().map(url -> url.toString()).collect(Collectors.toSet()).toArray()))) + .andDo(document("partner-get")); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void createPartnerTest() throws Exception { + + final Partner partner = setPartner("Partner one", true, "Partner one", UUID.randomUUID()); + final String s = verboseMapper.writeValueAsString(partner); + + /*@formatter:off*/ + this.mockMvc + .perform(RestDocumentationRequestBuilders.post(PartnerController.CONTROLLER_URL + "/create") + .content(s).contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) +// .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.name", is(partner.getName()))) + .andExpect(jsonPath("$.wiewsCodes", containsInAnyOrder(partner.getWiewsCodes().toArray()))) + .andExpect(jsonPath("$.urls", containsInAnyOrder(partner.getUrls().stream().map(url -> url.toString()).collect(Collectors.toSet()).toArray()))); + /*@formatter:on*/ + } + + @Test + @WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR") + public void updatePartner() throws Exception { + final Partner partner = partnerRepository.save(setPartner("Partner one", true, "Partner one", UUID.randomUUID())); + partner.setName("Test secondName"); + final String s = verboseMapper.writeValueAsString(partner); + + /*@formatter:off*/ + this.mockMvc + .perform(RestDocumentationRequestBuilders.post(PartnerController.CONTROLLER_URL + "/update/{UUID},{version}", partner.getUuid(), partner.getVersion()) + .content(s).contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON_UTF8)) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$", not(nullValue()))) + .andExpect(jsonPath("$.uuid", is(partner.getUuid().toString()))) + .andExpect(jsonPath("$.name", is(partner.getName()))); + /*@formatter:on*/ + } + + private Partner setPartner(final String name, final boolean isActive, final String shortName, final UUID uuid) throws MalformedURLException { + final Partner partner = new Partner(); + partner.setName(name); + partner.setActive(isActive); + partner.setShortName(shortName); + partner.setUuid(uuid); + partner.setWiewsCodes(Sets.newHashSet("PAR001", "PAR002")); + partner.setUrls(Sets.newHashSet(new URL("https://localhost"), new URL("http://localhost:8080"))); + return partner; + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/AbstractDatasetServiceTest.java b/src/test/java/org/genesys/test/catalog/services/AbstractDatasetServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..11597dea14dafd18bd054cc2279a65f8647ff280 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/AbstractDatasetServiceTest.java @@ -0,0 +1,133 @@ +/* + * 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.test.catalog.services; + +import java.util.HashSet; +import java.util.Set; + +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.dataset.AccessionIdentifier; +import org.genesys.catalog.model.dataset.Dataset; +import org.genesys.catalog.model.dataset.DatasetCreator; +import org.genesys.catalog.model.dataset.DatasetLocation; +import org.genesys.catalog.persistence.dataset.DatasetRepository; +import org.genesys.catalog.persistence.dataset.DatasetVersionsRepository; +import org.genesys.catalog.service.DatasetCreatorService; +import org.genesys.catalog.service.DatasetService; +import org.genesys.filerepository.persistence.RepositoryFilePersistence; +import org.junit.After; +import org.junit.Before; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class AbstractDatasetServiceTest extends CatalogServiceTest { + + protected static final String TEST_INSTCODE = "XYZ001"; + protected static final String DATASET_TITLE_1 = "Dataset title 1"; + protected static final String DATASET_TITLE_2 = "Dataset title 2"; + protected static final String DATASET_DESCRIPTION_1 = "Test description 1"; + protected static final String DATASET_DESCRIPTION_2 = "Test description 2"; + + @Autowired + protected DatasetService datasetService; + @Autowired + protected DatasetVersionsRepository datasetVersionsRepository; + @Autowired + protected DatasetRepository datasetRepository; + @Autowired + protected RepositoryFilePersistence repositoryFilePersistence; + @Autowired + protected DatasetCreatorService datasetCreatorService; + + public AbstractDatasetServiceTest() { + super(); + } + + @Before + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + } + + @After + @Override + public void cleanup() throws Exception { + datasetRepository.deleteAll(); + datasetVersionsRepository.deleteAll(); + descriptorRepository.deleteAll(); + repositoryFilePersistence.deleteAll(); + super.cleanup(); + } + + protected Dataset buildAndSaveDataset(final String datasetTitle, final String datasetDescription, final Partner partner, final boolean published) { + + final Set accessionIdentifiers = new HashSet() { + /** + * + */ + private static final long serialVersionUID = -2185214878678414276L; + + { + final AccessionIdentifier accessionIdentifier = new AccessionIdentifier(); + accessionIdentifier.setAcceNumb("TestAccNum"); + accessionIdentifier.setGenus("TestGen"); + accessionIdentifier.setInstCode("InstCode"); + add(accessionIdentifier); + } + }; + + return datasetService.createDataset(buildDataset(datasetTitle, datasetDescription, partner, accessionIdentifiers, published)); + } + + protected Dataset buildDataset(final String datasetTitle, final String datasetDescription, final Partner partner, final Set accessionIdentifiers, + final boolean published) { + final Dataset input = new Dataset(); + input.setTitle(datasetTitle); + input.setAccessionIdentifiers(accessionIdentifiers); + input.setDescription(datasetDescription); + input.setOwner(partner); + input.setPublished(published); + return input; + } + + protected DatasetCreator buildDatasetCreator(final String fullName, final String email, final String phoneNumber, final Dataset dataset) { + final DatasetCreator datasetCreator = new DatasetCreator(); + datasetCreator.setDataset(dataset); + datasetCreator.setFullName(fullName); + datasetCreator.setEmail(email); + datasetCreator.setRole(DatasetCreator.DatasetCreatorRole.MANAGER); + datasetCreator.setPhoneNumber(phoneNumber); + return datasetCreator; + } + + DatasetLocation buildLocation(final Dataset dataset, final String userCountry, final String mapCountry, final Double decimalLatitude) { + final DatasetLocation datasetLocation = new DatasetLocation(); + datasetLocation.setDataset(dataset); + datasetLocation.setUserCountry(userCountry); + datasetLocation.setMapCountry(mapCountry); + datasetLocation.setDecimalLatitude(decimalLatitude); + return datasetLocation; + } + + protected AccessionIdentifier makeAccessionIdentifier(final String instCode, final String acceNumb, final String genus, final String doi) { + final AccessionIdentifier accessionIdentifier = new AccessionIdentifier(); + accessionIdentifier.setInstCode(instCode); + accessionIdentifier.setAcceNumb(acceNumb); + accessionIdentifier.setGenus(genus); + accessionIdentifier.setDoi(doi); + return accessionIdentifier; + } + +} \ No newline at end of file diff --git a/src/test/java/org/genesys/test/catalog/services/AutomaticVocabulariesTest.java b/src/test/java/org/genesys/test/catalog/services/AutomaticVocabulariesTest.java new file mode 100644 index 0000000000000000000000000000000000000000..564ec67af107b1ad7a19d1b60707e4cc2eec734f --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/AutomaticVocabulariesTest.java @@ -0,0 +1,110 @@ +/* + * 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.test.catalog.services; + +import static org.genesys.hamcrest.Matchers.parsesToInt; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.List; + +import org.genesys.catalog.model.vocab.ControlledVocabulary; +import org.genesys.catalog.service.worker.DavrosCountrySource; +import org.genesys.catalog.service.worker.DavrosCountrySource.CountryInfo; +import org.genesys.catalog.service.worker.GeonamesISOLanguageSource; +import org.genesys.catalog.service.worker.GeonamesISOLanguageSource.LanguageInfo; +import org.genesys.test.base.AbstractServiceTest; +import org.genesys.catalog.service.worker.ISO3166VocabularyUpdater; +import org.genesys.catalog.service.worker.ISO639VocabularyUpdater; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * Test if automatic controlled vocabulary updating + * + * @author Matija Obreza + * @author Maxym Borodenko + */ +@Ignore +public class AutomaticVocabulariesTest extends AbstractServiceTest { + + @Autowired + private DavrosCountrySource davros; + + @Autowired + private ISO3166VocabularyUpdater iso3updater; + + @Autowired + private GeonamesISOLanguageSource geonames; + + @Autowired + private ISO639VocabularyUpdater iso639Updater; + + @Test + public void testDavros() throws IOException { + final List countries = davros.fetchCountryData(); + countries.stream().peek(c -> { + // LOG.debug(c); + }).count(); + assertThat(countries, hasSize(greaterThan(0))); + } + + @Test + public void testIso3166alpha3() throws IOException { + final ControlledVocabulary vocab = iso3updater.getISO3166Alpha3Vocabulary(); + assertThat(vocab.getTitle(), is("ISO-3166-3alpha")); + assertThat(vocab.getTerms(), hasSize(greaterThan(0))); + assertThat(vocab.getTerms().get(0).getCode().length(), is(3)); + } + + @Test + public void testIso3166alpha2() throws IOException { + final ControlledVocabulary vocab = iso3updater.getISO3166Alpha2Vocabulary(); + assertThat(vocab.getTitle(), is("ISO-3166-2alpha")); + assertThat(vocab.getTerms(), hasSize(greaterThan(0))); + assertThat(vocab.getTerms().get(0).getCode().length(), is(2)); + } + + @Test + public void testIso3166num() throws IOException { + final ControlledVocabulary vocab = iso3updater.getISO3166NumericVocabulary(); + // vocab.getTerms().stream().peek(c -> { + // LOG.debug(c); + // }).count(); + assertThat(vocab.getTitle(), is("ISO-3166-numeric")); + assertThat(vocab.getTerms(), hasSize(greaterThan(0))); + assertThat(vocab.getTerms().get(0).getCode(), both(notNullValue()).and(parsesToInt())); + } + + @Test + public void testGeonames() throws IOException { + final List languages = geonames.fetchLanguageData(); + languages.stream().peek(c -> { + // LOG.debug(c); + }).count(); + assertThat(languages, hasSize(greaterThan(0))); + } + + @Test + public void testIso639() throws IOException { + final ControlledVocabulary vocab = iso639Updater.getISO639Vocabulary(); + assertThat(vocab.getTitle(), is("ISO639-3")); + assertThat(vocab.getTerms(), hasSize(greaterThan(0))); + assertThat(vocab.getTerms().get(0).getCode().length(), is(3)); + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/CatalogServiceTest.java b/src/test/java/org/genesys/test/catalog/services/CatalogServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..81b8b3ad3c7a40482965e0bdc6ae8e8be9f914fa --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/CatalogServiceTest.java @@ -0,0 +1,138 @@ +/* + * 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.test.catalog.services; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Set; + +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.model.traits.Descriptor.Category; +import org.genesys.catalog.model.traits.DescriptorList; +import org.genesys.catalog.persistence.PartnerRepository; +import org.genesys.catalog.persistence.ShortFilterRepository; +import org.genesys.catalog.persistence.traits.DescriptorListRepository; +import org.genesys.catalog.persistence.traits.DescriptorRepository; +import org.genesys.catalog.service.DescriptorListService; +import org.genesys.catalog.service.DescriptorService; +import org.genesys.catalog.service.PartnerService; +import org.genesys.catalog.service.ShortFilterService; +import org.genesys.catalog.service.VocabularyService; +import org.genesys.test.base.AbstractServiceTest; +import org.junit.After; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.collect.Sets; + +/** + * @author Maxym Borodenko + */ +public abstract class CatalogServiceTest extends AbstractServiceTest { + + protected static final String PARTNER_1 = "International Partner Institute"; + protected static final String PARTNER_ACRONYM_1 = "IPI"; + + protected static final String PARTNER_2 = "Another Partner Institute"; + protected static final String PARTNER_ACRONYM_2 = "API"; + + protected static final String TERM_CODE_1 = "T1"; + protected static final String TERM_CODE_2 = "T2"; + protected static final String TERM_CODE_3 = "T3"; + protected static final String TERM_CODE_4 = "T4"; + protected static final String TERM_TITLE_1 = "Term title 1"; + protected static final String TERM_TITLE_2 = "Term title 2"; + + protected static URL URL_1; + + { + try { + URL_1 = new URL("http://url1"); + } catch (final MalformedURLException e) { + } + } + + @Autowired + protected PartnerService partnerService; + + @Autowired + protected PartnerRepository partnerRepository; + + @Autowired + protected DescriptorListService descriptorListService; + + @Autowired + protected DescriptorListRepository descriptorListRepository; + + @Autowired + protected DescriptorService descriptorService; + + @Autowired + protected DescriptorRepository descriptorRepository; + + @Autowired + protected VocabularyService vocabularyService; + + @Autowired + protected ShortFilterService shortFilterService; + + @Autowired + protected ShortFilterRepository shortFilterRepository; + + protected Partner partner; + protected Partner partner2; + + @After + @Override + public void cleanup() throws Exception { + partnerRepository.deleteAll(); + partner = setupPartner(PARTNER_1, PARTNER_ACRONYM_1, Sets.newHashSet(URL_1)); + partner2 = setupPartner(PARTNER_2, PARTNER_ACRONYM_2, Sets.newHashSet(URL_1)); + super.cleanup(); + } + + protected Partner setupPartner(final String name, final String shortName, final Set urls, final String... wiewsCodes) { + final Partner inputP = new Partner(); + inputP.setName(name); + inputP.setShortName(shortName); + inputP.setUrls(urls); + inputP.setWiewsCodes(Sets.newHashSet(wiewsCodes)); + return partnerService.createPartner(inputP); + } + + protected DescriptorList setupDescriptorList(final String title, final String version, final String description) { + final DescriptorList descriptorList = new DescriptorList(); + descriptorList.setOwner(partner); + descriptorList.setTitle(title); + descriptorList.setVersionTag(version); + descriptorList.setDescription(description); + return descriptorList; + } + + protected Descriptor createDescriptor(final Partner owner, final String title, final String versionTag, final Descriptor.DataType type) { + final Descriptor input = new Descriptor(); + input.setCategory(Category.PASSPORT); + input.setTitle(title); + input.setVersionTag(versionTag); + input.setDataType(type); + input.setOwner(owner); + return input; + } + + protected Descriptor setupDescriptor(final Partner owner, final String title, final String versionTag, final Descriptor.DataType type) { + return descriptorService.createDescriptor(createDescriptor(owner, title, versionTag, type)); + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/CodedDescriptorTest.java b/src/test/java/org/genesys/test/catalog/services/CodedDescriptorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3b09b67e6758497faee99d3fbb1dde430ade539b --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/CodedDescriptorTest.java @@ -0,0 +1,120 @@ +/* + * 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.test.catalog.services; + +import static org.genesys.catalog.model.vocab.QVocabularyTerm.vocabularyTerm; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; + +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.model.traits.Descriptor.Category; +import org.genesys.catalog.model.traits.Descriptor.DataType; +import org.genesys.catalog.model.vocab.ControlledVocabulary; +import org.genesys.catalog.model.vocab.VocabularyTerm; +import org.genesys.catalog.persistence.traits.DescriptorRepository; +import org.genesys.catalog.persistence.vocab.ControlledVocabularyRepository; +import org.genesys.catalog.persistence.vocab.VocabularyTermRepository; +import org.genesys.catalog.service.DescriptorService; +import org.genesys.catalog.service.VocabularyService; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.collect.Lists; + +public class CodedDescriptorTest extends CatalogServiceTest { + + private static final String DESCRIPTOR_TITLE_1 = "D1"; + private static final String VERSION_1_0 = "1.0"; + // private static final String VERSION_1_1 = "1.1"; + private static final String VOCABULARY_1 = "V1"; + + @Autowired + private DescriptorService descriptorService; + + @Autowired + private DescriptorRepository descriptorRepository; + @Autowired + private VocabularyService vocabularyService; + @Autowired + private ControlledVocabularyRepository vocabRepository; + @Autowired + private VocabularyTermRepository termRepository; + + @Override + public void cleanup() throws Exception { + descriptorRepository.deleteAll(); + vocabRepository.deleteAll(); + super.cleanup(); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testFailCreateCodedDescriptorWithoutVocabulary() { + final Descriptor input = new Descriptor(); + input.setOwner(partner); + input.setCategory(Category.PASSPORT); + input.setTitle(DESCRIPTOR_TITLE_1); + input.setVersionTag(VERSION_1_0); + input.setDataType(DataType.CODED); + descriptorService.createDescriptor(input); + } + + @Test + public void testCreateCodedDescriptor() { + ControlledVocabulary vocab = new ControlledVocabulary(); + vocab.setOwner(partner); + vocab.setTitle(VOCABULARY_1); + vocab = vocabularyService.createVocabulary(vocab); + + Descriptor descriptor = new Descriptor(); + descriptor.setOwner(partner); + descriptor.setCategory(Category.PASSPORT); + descriptor.setTitle(DESCRIPTOR_TITLE_1); + descriptor.setVersionTag(VERSION_1_0); + descriptor.setDataType(DataType.CODED); + descriptor.setVocabulary(vocab); + + descriptor = descriptorService.createDescriptor(descriptor); + assertThat(descriptor.getTerms(), nullValue()); + assertThat(descriptor.getVocabulary(), not(nullValue())); + assertThat(descriptor.getVocabulary().getUuid(), is(vocab.getUuid())); + } + + @Test + public void testCreateCodedDescriptorWithTerms() { + Descriptor descriptor = new Descriptor(); + descriptor.setOwner(partner); + descriptor.setCategory(Category.PASSPORT); + descriptor.setTitle(DESCRIPTOR_TITLE_1); + descriptor.setVersionTag(VERSION_1_0); + descriptor.setDataType(DataType.CODED); + descriptor.setTerms(Lists.newArrayList(VocabularyTerm.fromData("1", "One"), VocabularyTerm.fromData("2", "Two"))); + descriptor = descriptorService.createDescriptor(descriptor); + assertThat(descriptor.getTerms(), hasSize(2)); + } + + + @Test + public void queryTermByDescriptor() throws JsonProcessingException { + testCreateCodedDescriptorWithTerms(); + VocabularyTerm term = termRepository.findOne(vocabularyTerm.descriptor.title.eq(DESCRIPTOR_TITLE_1).and(vocabularyTerm.code.eq("2"))); + assertThat(term, not(nullValue())); + assertThat(term.getCode(), equalTo("2")); + assertThat(term.getTitle(), equalTo("Two")); + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/ControlledVocabularyTest.java b/src/test/java/org/genesys/test/catalog/services/ControlledVocabularyTest.java new file mode 100644 index 0000000000000000000000000000000000000000..05d64847c9010d7971fc39708cc90754b24feca7 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/ControlledVocabularyTest.java @@ -0,0 +1,423 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.genesys.catalog.model.vocab.ControlledVocabulary; +import org.genesys.catalog.model.vocab.VocabularyTerm; +import org.genesys.catalog.persistence.vocab.ControlledVocabularyRepository; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; + +import com.google.common.collect.Lists; + +public class ControlledVocabularyTest extends CatalogServiceTest { + + private static final String VOCABULARY_TITLE_1 = "Vocab 1"; + private static final String VOCABULARY_TITLE_2 = "Vocab 2"; + private static final String VOCABULARY_DESC_1 = "Controlled vocab description 1"; + + private static final String TERM_CODE_1 = "T1"; + private static final String TERM_CODE_2 = "T2"; + private static final String TERM_CODE_3 = "T3"; + private static final String TERM_CODE_4 = "T4"; + private static final String TERM_TITLE_1 = "Term title 1"; + private static final String TERM_TITLE_2 = "Term title 2"; + + @Autowired + private ControlledVocabularyRepository vocabRepository; + + @Override + public void cleanup() throws Exception { + vocabRepository.deleteAll(); + super.cleanup(); + } + + /** + * Create vocabulary with a new random UUID + */ + @Test + public void testCreateVocabulary() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + final List terms = Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2)); + vocab1.setTerms(terms); + + final ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getUuid(), not(nullValue())); + + assertThat(result.getTitle(), is(VOCABULARY_TITLE_1)); + assertThat(result.getTerms(), hasSize(2)); + assertEquals(partner.getUuid(), result.getOwner().getUuid()); + } + + /** + * Make sure that a vocabulary can be created by specifying it's UUID + */ + @Test + public void testCreateVocabularyWithUUID() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + final UUID uuid = UUID.randomUUID(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + final ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getUuid(), is(uuid)); + + // test load by UUID + final ControlledVocabulary loaded = vocabularyService.getVocabulary(uuid); + assertThat(loaded, not(nullValue())); + assertThat(loaded.getId(), is(result.getId())); + assertThat(vocabularyService.getVocabulary(UUID.randomUUID()), nullValue()); + } + + /** + * UUID of the vocabulary is unique + */ + @Test(expected = DataIntegrityViolationException.class) + public void testFailOnDuplicateUUID() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + final UUID uuid = UUID.randomUUID(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + final ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + assertThat(result.getUuid(), is(uuid)); + + // this must fail + vocabularyService.createVocabulary(vocab1); + } + + /** + * Create vocabulary with specified terms + */ + @Test + public void testCreateVocabularyWithTerms() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + final List terms = Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2)); + vocab1.setTerms(terms); + + final ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + assertThat(result, not(nullValue())); + assertThat(result.getTerms(), hasSize(2)); + assertEquals(terms.get(0).getTitle(), TERM_TITLE_1); + assertThat(terms.get(0).getDescription(), nullValue()); + } + + /** + * Fail to create vocabulary when term code is duplicated: term code is unique + * within vocabulary + */ + @Test(expected = DataIntegrityViolationException.class) + public void testFailOnDuplicateTermCode() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_2))); + + vocabularyService.createVocabulary(vocab1); + } + + /** + * Fail to update vocabulary when isPublish() = true + */ + @Test(expected = DataAccessResourceFailureException.class) + public void testFailOnUpdateVocabularyWithPublished() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setOwner(partner); + vocab1.setTitle(VOCABULARY_TITLE_1); + + ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + result.setPublished(Boolean.TRUE); + result = vocabularyService.updateVocabulary(result); + + result.setTitle(VOCABULARY_TITLE_2); + vocabularyService.updateVocabulary(result); + } + + @Test + public void testUpdateVocabulary() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + final UUID uuid = result.getUuid(); + vocab1.setUuid(uuid); + vocab1.setVersion(result.getVersion()); + vocab1.setTitle(VOCABULARY_TITLE_2); + vocab1.setPublisher("PUBLISHER"); + result = vocabularyService.updateVocabulary(vocab1); + result.setTerms(null); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.getTitle(), is(VOCABULARY_TITLE_2)); + assertThat(result.getDescription(), is(nullValue())); + assertThat(result.getPublisher(), is(vocab1.getPublisher())); + + result.setTitle(VOCABULARY_TITLE_1); + result.setDescription(VOCABULARY_DESC_1); + result = vocabularyService.updateVocabulary(result); + result.setTerms(null); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.getTitle(), is(VOCABULARY_TITLE_1)); + assertThat(result.getDescription(), is(VOCABULARY_DESC_1)); + assertEquals(partner.getUuid(), result.getOwner().getUuid()); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public void testFailUpdateWithoutIdentifiers() throws MalformedURLException { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + // update + vocab1.setId(null); + vocabularyService.updateVocabulary(vocab1); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public void testFailUpdateForNullVocabulary() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + vocabularyService.updateVocabulary(vocab1); + + } + + @Test(expected = ConcurrencyFailureException.class) + public void testFailUpdateForDifferentVersions() { + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + final ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + result.setVersion(result.getVersion() + 1); + vocabularyService.updateVocabulary(result); + } + + /** + * I should be able to add a new term to existing vocabulary + */ + @Test + public void testAddAndRemoveTerms() { + final UUID uuid = UUID.randomUUID(); + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.getTerms(), hasSize(0)); + + // add 2 terms + ArrayList terms = Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2)); + + result.setTerms(terms); + result = vocabularyService.updateVocabulary(result); + assertThat(result.getTerms(), hasSize(2)); + + // add 2 other terms + terms = new ArrayList<>(result.getTerms()); + terms.add(VocabularyTerm.fromData(TERM_CODE_3, TERM_TITLE_1)); + terms.add(VocabularyTerm.fromData(TERM_CODE_4, TERM_TITLE_2)); + + result.setTerms(terms); + result = vocabularyService.updateVocabulary(result); + assertThat(result.getTerms(), hasSize(4)); + + // remove listed terms + result.setTerms(new ArrayList<>()); + result = vocabularyService.updateVocabulary(result); + + result = vocabularyService.getVocabulary(uuid); + assertThat(result.getTerms(), hasSize(0)); + } + + /** + * I should be able to add new and update existing terms in a vocabulary in one + * call + */ + @Test + public void testAddOrUpdateTerms() { + final UUID uuid = UUID.randomUUID(); + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + + ControlledVocabulary result = vocabularyService.createVocabulary(vocab1); + + // add 2 terms + List terms = Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2)); + + result.setTerms(terms); + result = vocabularyService.updateVocabulary(result); + assertThat(result.getTerms(), hasSize(2)); + + // get persisted terms + terms = new ArrayList<>(result.getTerms()); + + // update 1 existing terms + terms.get(0).setDescription("Updated 1"); + terms.remove(1); + + // add 2 other terms + terms.add(VocabularyTerm.fromData(TERM_CODE_3, TERM_TITLE_1)); + terms.add(VocabularyTerm.fromData(TERM_CODE_4, TERM_TITLE_2)); + assertThat(terms, hasSize(3)); + + result.setTerms(terms); + result = vocabularyService.updateVocabulary(result); + assertThat(result.getTerms(), hasSize(3)); + } + + /** + * I should be able to fetch specific vocabulary terms + */ + @Test + public void testGetVocabularyTerms() { + final UUID uuid = UUID.randomUUID(); + ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + vocab1.setTerms(Lists.newArrayList( + /*@formatter:off*/ + VocabularyTerm.fromData("a", "a"), + VocabularyTerm.fromData("b", "b"), + VocabularyTerm.fromData("c", "c"), + VocabularyTerm.fromData("aa", "aa"), + VocabularyTerm.fromData("aaa", "aaa"), + VocabularyTerm.fromData("ab", "ab") + /*@formatter:on */ + )); + + vocab1 = vocabularyService.createVocabulary(vocab1); + + assertThat(vocabularyService.getVocabularyTerm(uuid, "a"), not(nullValue())); + assertThat(vocabularyService.getVocabularyTerm(uuid, "aaa"), not(nullValue())); + } + + /** + * I should be able to autocomplete vocabulary terms + */ + @Test + public void testAutocompleteVocabularyTerms() { + final UUID uuid = UUID.randomUUID(); + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + vocab1.setTerms(Lists.newArrayList( + /*@formatter:off*/ + VocabularyTerm.fromData("a", "a"), + VocabularyTerm.fromData("b", "b"), + VocabularyTerm.fromData("c", "c"), + VocabularyTerm.fromData("aa", "aa"), + VocabularyTerm.fromData("aaa", "aaa"), + VocabularyTerm.fromData("ab", "ab") + /*@formatter:on */ + )); + + vocabularyService.createVocabulary(vocab1); + + assertThat(vocabularyService.autocompleteTerms(uuid, "a"), hasSize(4)); + assertThat(vocabularyService.autocompleteTerms(uuid, "aa"), hasSize(2)); + assertThat(vocabularyService.autocompleteTerms(uuid, "aaa"), hasSize(1)); + } + + @Test + public void testOver50Terms() { + final UUID uuid = UUID.randomUUID(); + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + final ArrayList terms = Lists.newArrayList(); + vocab1.setTerms(terms); + for (int i = 0; i < 100; i++) { + terms.add(VocabularyTerm.fromData("a" + i, "a" + i)); + } + vocabularyService.createVocabulary(vocab1); + + ControlledVocabulary result = vocabularyService.getVocabulary(uuid); + assertThat(result, not(nullValue())); + assertThat(result.getTermCount(), greaterThan(50)); + assertThat(result.getTermCount(), is(100)); + assertThat(result.getTerms().size(), is(50)); + + // another 100 + for (int i = 100; i < 200; i++) { + terms.add(VocabularyTerm.fromData("a" + i, "a" + i)); + } + result.setTerms(terms); + vocabularyService.updateVocabulary(result); + + result = vocabularyService.getVocabulary(uuid); + assertThat(result, not(nullValue())); + assertThat(result.getTermCount(), is(200)); + assertThat(result.getTerms().size(), is(50)); + } + + @Test + public void testListOver50Terms() { + final UUID uuid = UUID.randomUUID(); + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setUuid(uuid); + vocab1.setTitle(VOCABULARY_TITLE_1); + vocab1.setOwner(partner); + final ArrayList terms = Lists.newArrayList(); + vocab1.setTerms(terms); + for (int i = 0; i < 200; i++) { + terms.add(VocabularyTerm.fromData("a" + i, "a" + i)); + } + vocabularyService.createVocabulary(vocab1); + + final ControlledVocabulary result = vocabularyService.getVocabulary(uuid); + Page paged = vocabularyService.listTerms(result, new PageRequest(0, 100)); + assertThat(paged.getContent(), not(nullValue())); + assertThat(paged.getTotalElements(), is(200l)); + assertThat(paged.getNumber(), is(0)); + assertThat(paged.getSize(), is(100)); + + paged = vocabularyService.listTerms(result, new PageRequest(1, 100)); + assertThat(paged.getContent(), not(nullValue())); + assertThat(paged.getTotalElements(), is(200l)); + assertThat(paged.getNumber(), is(1)); + assertThat(paged.getSize(), is(100)); + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/DatasetPublishingTest.java b/src/test/java/org/genesys/test/catalog/services/DatasetPublishingTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b91a2a67dc2246decdb857ccf8fb11cc34223940 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/DatasetPublishingTest.java @@ -0,0 +1,91 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; + +import org.genesys.catalog.annotations.PublishValidationException; +import org.genesys.catalog.exceptions.InvalidApiUsageException; +import org.genesys.catalog.exceptions.NotFoundElement; +import org.genesys.catalog.model.dataset.Dataset; +import org.junit.Before; +import org.junit.Test; +import org.springframework.transaction.annotation.Transactional; + +public class DatasetPublishingTest extends AbstractDatasetServiceTest { + + private Dataset published; + + @Override + @Transactional + public void cleanup() throws Exception { + published = null; + descriptorRepository.deleteAll(); + datasetRepository.deleteAll(); + super.cleanup(); + } + + @Before + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + assertThat(input.getVersion(), is(1)); + assertThat(input.getOwner(), not(nullValue())); + published = datasetService.publishDataset(input); + assertThat(published.getVersion(), is(2)); + } + + @Test + public void testPublishedDataset() throws NotFoundElement, PublishValidationException { + assertThat(published.isPublished(), is(true)); + assertThat(published.isPersisted(), is(true)); + assertThat(published.getId(), greaterThan(0l)); + assertThat(published.getVersion(), is(2)); + + Dataset loaded = datasetService.loadDataset(published.getUuid()); + assertThat(loaded, not(nullValue())); + loaded = datasetService.loadDataset(published.getUuid(), published.getVersion()); + assertThat(loaded, not(nullValue())); + } + + @Test + public void testLoadDataset() throws NotFoundElement, PublishValidationException { + Dataset loaded = datasetRepository.findByUuid(published.getUuid()); + assertThat(loaded, not(nullValue())); + + loaded = datasetRepository.findByUuidAndVersion(published.getUuid(), published.getVersion()); + assertThat(loaded, not(nullValue())); + } + + @Test(expected = InvalidApiUsageException.class) + public void testPublishDatasetFailWhenPublished() throws NotFoundElement, PublishValidationException { + assertThat(published.isPublished(), is(true)); + final Dataset loaded = datasetRepository.findByUuid(published.getUuid()); + assertThat(loaded, not(nullValue())); + datasetService.publishDataset(published); + } + + @Test + public void testUnpublishDataset() { + assertThat(published.isPublished(), is(true)); + final Dataset loaded = datasetRepository.findByUuid(published.getUuid()); + assertThat(loaded, not(nullValue())); + final Dataset dataset = datasetService.unpublishDataset(published); + assertThat(dataset.isPublished(), is(false)); + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/DatasetServiceTest.java b/src/test/java/org/genesys/test/catalog/services/DatasetServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b6f804626624b8cb9de76c814b7cc96970b99b1b --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/DatasetServiceTest.java @@ -0,0 +1,568 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.genesys.blocks.model.filters.StringFilter; +import org.genesys.catalog.exceptions.InvalidApiUsageException; +import org.genesys.catalog.exceptions.NotFoundElement; +import org.genesys.catalog.model.dataset.AccessionIdentifier; +import org.genesys.catalog.model.dataset.Dataset; +import org.genesys.catalog.model.filters.AccessionIdentifierFilter; +import org.genesys.catalog.model.filters.DatasetFilter; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.model.traits.Descriptor.DataType; +import org.genesys.filerepository.InvalidRepositoryFileDataException; +import org.genesys.filerepository.InvalidRepositoryPathException; +import org.genesys.filerepository.NoSuchRepositoryFileException; +import org.genesys.filerepository.model.RepositoryFile; +import org.junit.Test; +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.mock.web.MockMultipartFile; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +public class DatasetServiceTest extends AbstractDatasetServiceTest { + + @Test + public void testCreateDataset() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + assertThat(input, not(nullValue())); + assertThat(input.getId(), not(nullValue())); + assertThat(input.getAccessionIdentifiers().size(), is(1)); + assertThat(input.getVersions(), not(nullValue())); + assertThat(input.getVersions().getCurrentVersion(), is(input)); + } + + @Test + public void testCreateDatasetSelfCleaning() { + Dataset input = buildAndSaveDataset(DATASET_TITLE_1 + " ", " " + DATASET_DESCRIPTION_1, partner, false); + assertThat(input, not(nullValue())); + assertThat(input.getTitle(), is(DATASET_TITLE_1)); + assertThat(input.getDescription(), is(DATASET_DESCRIPTION_1)); + + input.setTitle(" \t " + DATASET_TITLE_2 + " \t"); + input.setDescription(" \t " + DATASET_DESCRIPTION_2 + " \t "); + input = datasetService.updateDataset(input); + assertThat(input.getTitle(), is(DATASET_TITLE_2)); + assertThat(input.getDescription(), is(DATASET_DESCRIPTION_2)); + } + + @Test + public void testCreateDatasetWithCrops() { + Dataset input = buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, null, true); + input.setCrops(Sets.newHashSet("maize", "wheat")); + input = datasetService.createDataset(input); + assertThat(input, not(nullValue())); + assertThat(input.getCrops(), hasSize(2)); + assertThat(input.getCrops(), containsInAnyOrder("wheat", "maize")); + + input = datasetService.loadDataset(input.getUuid()); + assertThat(input.getCrops(), hasSize(2)); + assertThat(input.getCrops(), containsInAnyOrder("wheat", "maize")); + } + + @Test + public void testCreateDatasetIsUnpublished() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + assertThat(input.isPublished(), not(is(true))); + } + + @Test(expected = NotFoundElement.class) + public void testRemoveDataset() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + final Dataset removed = datasetService.removeDataset(input); + assertThat(removed, not(nullValue())); + assertThat(removed, equalTo(input)); + datasetService.loadDataset(removed); + } + + @Test + public void testCreateDatasetForCopyDescriptors() { + final Descriptor savedDescriptor = descriptorService.createDescriptor(createDescriptor(partner, "D1", "1.0", DataType.NUMERIC)); + + final Dataset input2 = buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, null, false); + input2.setDescriptors(new ArrayList() { + /** + * + */ + private static final long serialVersionUID = 3885017184588921619L; + + { + add(savedDescriptor); + add(savedDescriptor); + } + }); + datasetService.createDataset(input2); + } + + @Test + public void testUpdateAccessionIdentifiersInDataset() { + Dataset input = buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, null, false); + input = datasetService.createDataset(input); + + final Set accessionIdentifiers = new HashSet() { + /** + * + */ + private static final long serialVersionUID = 8861481736874624612L; + + { + add(makeAccessionIdentifier(TEST_INSTCODE, "TestAcc", "TestGen", null)); + } + }; + + input = datasetService.updateAccessionIdentifiers(input, accessionIdentifiers); + assertThat(input, not(nullValue())); + assertThat(input.getAccessionIdentifiers().size(), is(1)); + assertThat(input.getAccessionIdentifiers().iterator().next(), is(accessionIdentifiers.iterator().next())); + } + + /** + * Fail to update Dataset when isPublished() = true + */ + @Test(expected = DataIntegrityViolationException.class) + public void testFailUpdatePublishedDataset() { + Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + input.setPublished(Boolean.TRUE); + input = datasetService.updateDataset(input); + input.setTitle(DATASET_TITLE_2); + datasetService.updateDataset(input); + } + + /** + * Fail to update when identifiers are missing + */ + @Test(expected = InvalidDataAccessApiUsageException.class) + public void testFailUpdateWithoutIdentifiers() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + input.setId(null); + datasetService.updateDataset(input); + } + + /** + * Fail to update when identifiers are missing + */ + @Test(expected = NotFoundElement.class) + public void testFailUpdateNonExistent() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + input.setId(-1l); + datasetService.updateDataset(input); + } + + @Test(expected = ConcurrencyFailureException.class) + public void testFailUpdateErrorVersion() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + input.setVersion(4); + datasetService.updateDataset(input); + } + + @Test + public void testUpdateDataset() { + final Dataset result = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + final Set accessionIdentifiers = new HashSet() { + /** + * + */ + private static final long serialVersionUID = 2971515839324312874L; + + { + add(makeAccessionIdentifier(TEST_INSTCODE, "TestAcc1", "TestGen1", null)); + } + }; + + final Dataset result2 = datasetService.createDataset(buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, accessionIdentifiers, false)); + + assertThat(result.isPublished(), is(false)); + + result.setTitle(DATASET_TITLE_2); + result.setDescription(DATASET_DESCRIPTION_2); + + final Dataset resultUpdated = datasetService.updateDataset(result); + assertThat(resultUpdated.getTitle(), is(DATASET_TITLE_2)); + assertThat(resultUpdated.getDescription(), is(DATASET_DESCRIPTION_2)); + assertThat(resultUpdated.getVersions().getAllVersions(), hasSize(1)); + + final List datasetVersionss = new ArrayList<>(); + datasetVersionss.addAll(resultUpdated.getVersions().getAllVersions()); + datasetVersionss.add(result2); + + resultUpdated.getVersions().setAllVersions(datasetVersionss); +// datasetVersionsRepository.save(resultUpdated.getVersions()); + assertThat(resultUpdated.getVersions().getAllVersions(), hasSize(2)); + } + + @Test + public void testUpdateDatasetCrops() { + Dataset result = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + assertThat(result.isPublished(), is(false)); + + result.setCrops(Sets.newHashSet("cassava", "yam")); + + result = datasetService.updateDataset(result); + assertThat(result.getCrops(), hasSize(2)); + assertThat(result.getCrops(), containsInAnyOrder("yam", "cassava")); + + result.getCrops().clear(); + result = datasetService.updateDataset(result); + assertThat(result.getCrops(), hasSize(0)); + } + + @Test + public void testAddDescriptorToDataset() { + Descriptor savedDescriptor = createDescriptor(partner, "D1", "1.0", DataType.NUMERIC); + savedDescriptor = descriptorService.createDescriptor(savedDescriptor); + + Dataset savedDataset = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + assertThat(savedDataset.getDescriptors(), hasSize(0)); + + savedDataset = datasetService.addDescriptors(savedDataset, savedDescriptor); + assertThat(savedDataset.getDescriptors(), not(nullValue())); + + assertThat(savedDataset.getDescriptors().contains(savedDescriptor), is(true)); + + // for {@link #testCannotDeleteDescriptor()} + savedDataset = datasetService.publishDataset(savedDataset); + } + + @Test + public void testRemoveDescriptorFromDataset() { + Descriptor descriptor1 = createDescriptor(partner, "D1", "1.0", DataType.NUMERIC); + descriptor1 = descriptorService.createDescriptor(descriptor1); + + Descriptor descriptor2 = createDescriptor(partner, "D2", "1.0", DataType.NUMERIC); + descriptor2 = descriptorService.createDescriptor(descriptor2); + + Dataset savedDataset = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + savedDataset = datasetService.addDescriptors(savedDataset, descriptor1); + savedDataset = datasetService.addDescriptors(savedDataset, descriptor2); + assertThat(savedDataset.getDescriptors().size(), is(2)); + assertThat(savedDataset.getDescriptors(), contains(descriptor1, descriptor2)); + + savedDataset = datasetService.removeDescriptors(savedDataset, descriptor1); + assertThat(savedDataset.getDescriptors().size(), is(1)); + assertThat(savedDataset.getDescriptors(), contains(descriptor2)); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testCannotDeleteDescriptor() { + testAddDescriptorToDataset(); + DatasetFilter filter = new DatasetFilter(); + Page loaded = datasetService.listDatasets(filter, new PageRequest(0, 1)); + assertThat(loaded.getContent(), hasSize(1)); + + Dataset savedDataset = loaded.getContent().get(0); + savedDataset = datasetService.loadDataset(savedDataset); + Descriptor referencedDescriptor = savedDataset.getDescriptors().get(0); + + assertThat(referencedDescriptor, not(nullValue())); + assertThat(referencedDescriptor.getId(), not(nullValue())); + + descriptorService.removeDescriptor(referencedDescriptor); + } + + @Test + public void testReorderDescriptors() { + + Descriptor descriptor1 = createDescriptor(partner, "D1", "1.0", DataType.NUMERIC); + descriptor1 = descriptorService.createDescriptor(descriptor1); + + Descriptor descriptor2 = createDescriptor(partner, "D2", "1.0", DataType.NUMERIC); + descriptor2 = descriptorService.createDescriptor(descriptor2); + + Descriptor descriptor3 = createDescriptor(partner, "D3", "1.1", DataType.TEXT); + descriptor3 = descriptorService.createDescriptor(descriptor3); + + Dataset savedDataset = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + savedDataset = datasetService.addDescriptors(savedDataset, descriptor1); + savedDataset = datasetService.addDescriptors(savedDataset, descriptor2); + assertThat(savedDataset.getDescriptors().size(), is(2)); + assertThat(savedDataset.getDescriptors(), contains(descriptor1, descriptor2)); + + savedDataset = datasetService.updateDescriptors(savedDataset, Lists.newArrayList(descriptor3, descriptor2, descriptor1)); + assertThat(savedDataset.getDescriptors(), contains(descriptor3, descriptor2, descriptor1)); + savedDataset = datasetService.updateDescriptors(savedDataset, Lists.newArrayList(descriptor3, descriptor1, descriptor2)); + assertThat(savedDataset.getDescriptors(), contains(descriptor3, descriptor1, descriptor2)); + } + + @Test + public void testDuplicateDescriptorsIgnored() { + Descriptor descriptor1 = createDescriptor(partner, "D1", "1.0", DataType.NUMERIC); + descriptor1 = descriptorService.createDescriptor(descriptor1); + + Descriptor descriptor2 = createDescriptor(partner, "D2", "1.0", DataType.NUMERIC); + descriptor2 = descriptorService.createDescriptor(descriptor2); + + Descriptor descriptor3 = createDescriptor(partner, "D3", "1.1", DataType.TEXT); + descriptor3 = descriptorService.createDescriptor(descriptor3); + + Dataset savedDataset = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + savedDataset = datasetService.updateDescriptors(savedDataset, Lists.newArrayList(descriptor3, descriptor1, descriptor2, descriptor3)); + + assertThat(savedDataset.getDescriptors(), hasSize(3)); + } + + @Test + public void testDuplicateDescriptorIgnoredOnUpdate() { + Descriptor descriptor1 = createDescriptor(partner, "D1", "1.0", DataType.NUMERIC); + descriptor1 = descriptorService.createDescriptor(descriptor1); + + final Dataset dataset = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + dataset.setDescriptors(Lists.newArrayList(descriptor1)); + Dataset savedDataset = datasetService.createDataset(dataset); + + assertThat(savedDataset.getDescriptors(), contains(descriptor1)); + + savedDataset = datasetService.addDescriptors(savedDataset, descriptor1); + assertThat(savedDataset.getDescriptors(), hasSize(1)); + } + + @Test + public void testNoFailOnEmptyDescriptorUpdate() { + final Dataset dataset = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + assertThat(dataset.getDescriptors(), hasSize(0)); + datasetService.addDescriptors(dataset, new Descriptor[] {}); + } + + @Test + public void testLoadList() { + // not listed + buildAndSaveDataset("Not published " + DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + // listed + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, true); + + final String[] strs = new String[] { "title" }; + final Pageable pageable = new PageRequest(0, Integer.min(50, 100), Sort.Direction.ASC, strs); + final Page page = datasetService.listDatasets(new DatasetFilter(), pageable); + assertThat(page.getTotalElements(), is(1L)); + assertThat(((Dataset) page.getContent().get(0)).getUuid(), is(input.getUuid())); + } + + @Test + public void testLoadCurrentVersionList() { + final Dataset result = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + final String[] strs = new String[] { "title" }; + final Pageable pageable = new PageRequest(0, Integer.min(50, 100), Sort.Direction.ASC, strs); + final Page page = datasetService.loadCurrentVersionList(pageable); + + assertThat(page.getTotalElements(), is(1L)); + assertThat(((Dataset) page.getContent().get(0)).getUuid(), is(result.getUuid())); + } + + @Test(expected = NotFoundElement.class) + public void testNonExistent() { + final Dataset result = datasetService.loadDataset(UUID.randomUUID()); + assertThat(result, is(nullValue())); + } + + @Test + public void testLoadDataset() { + final Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + final Dataset result = datasetService.loadDataset(input.getUuid()); + assertThat(result, not(nullValue())); + assertThat(result.getUuid().toString(), is(input.getUuid().toString())); + } + + @Test(expected = NotFoundElement.class) + public void testFailedLoadDataset() { + buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + datasetService.loadDataset(UUID.randomUUID()); + } + + @Test + public void testAddFile() throws IOException, InvalidRepositoryFileDataException, NotFoundElement, InvalidRepositoryPathException { + + final File file = new File(getClass().getResource("/mcpd20177.csv").getPath()); + final FileInputStream fileInputStream = new FileInputStream(file); + final MockMultipartFile mockMultipartFile = new MockMultipartFile("file", file.getName(), "multipart/form-data", fileInputStream); + + final Dataset created = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + Dataset dataset = datasetService.addDatasetFile(created, mockMultipartFile); + + final FileInputStream fileInputStream2 = new FileInputStream(file); + final MockMultipartFile mockMultipartFile2 = new MockMultipartFile("file", "2" + file.getName(), "multipart/form-data", fileInputStream2); + dataset = datasetService.addDatasetFile(dataset, mockMultipartFile2); + assertThat(dataset.getRepositoryFiles(), is(notNullValue())); + assertThat(dataset.getRepositoryFiles().size(), is(2)); + assertThat(dataset.getRepositoryFiles().get(0).getVersion(), is(1)); + } + + @Test + public void testUpdateFile() throws IOException, InvalidRepositoryFileDataException, NotFoundElement, InvalidRepositoryPathException, NoSuchRepositoryFileException { + final File file = new File(getClass().getResource("/mcpd20177.csv").getPath()); + final FileInputStream fileInputStream = new FileInputStream(file); + final MockMultipartFile mockMultipartFile = new MockMultipartFile("file", file.getName(), "multipart/form-data", fileInputStream); + + Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + input = datasetService.addDatasetFile(input, mockMultipartFile); + final RepositoryFile df = input.getRepositoryFiles().get(0); + df.setTitle("Updated file title"); + + final Dataset dataset = datasetService.updateDatasetFile(input, df); + + assertThat(dataset.getRepositoryFiles().size(), is(1)); + assertThat(dataset.getRepositoryFiles().get(0).getVersion(), is(2)); + assertThat(dataset.getRepositoryFiles().get(0).getTitle(), is(df.getTitle())); + } + + @Test + public void testRemoveFile() throws IOException, InvalidRepositoryFileDataException, NotFoundElement, InvalidRepositoryPathException, NoSuchRepositoryFileException { + final File file = new File(getClass().getResource("/mcpd20177.csv").getPath()); + final FileInputStream fileInputStream = new FileInputStream(file); + final MockMultipartFile mockMultipartFile = new MockMultipartFile("file", file.getName(), "multipart/form-data", fileInputStream); + + Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + + input = datasetService.addDatasetFile(input, mockMultipartFile); + + final Dataset dataset = datasetService.removeDatasetFile(input, input.getRepositoryFiles().get(0).getUuid()); + + assertThat(dataset.getRepositoryFiles().size(), is(0)); + assertThat(repositoryFilePersistence.findByUuid(input.getRepositoryFiles().get(0).getUuid()), nullValue()); + } + + @Test + public void testErrorPublish() { + final Dataset result = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + final Map errorMap = result.validation(); + assertThat(errorMap.size(), not(is(0))); + } + + @Test + public void upsertAccessions() { + Dataset result = datasetService.createDataset(buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, null, false)); + assertThat(result.getAccessionCount(), nullValue()); + + final Set accessionIdentifiers = new HashSet() { + /** + * + */ + private static final long serialVersionUID = 8018459783964588063L; + + { + add(makeAccessionIdentifier(TEST_INSTCODE, "TestAccNum", "TestGen", null)); + add(makeAccessionIdentifier(TEST_INSTCODE, "TestAccNum2", "TestGen", null)); + } + }; + + result = datasetService.upsertAccessions(result, accessionIdentifiers); + + assertThat(result, not(nullValue())); + assertThat(result.getAccessionIdentifiers(), not(nullValue())); + assertThat(result.getAccessionIdentifiers().size(), is(2)); + assertThat(result.getAccessionCount(), is(2)); + } + + @Test + public void testAccessionIdentifierFilter() { + final Set ids1 = new HashSet<>(); + ids1.add(makeAccessionIdentifier(TEST_INSTCODE, "A1", "Musa", null)); + ids1.add(makeAccessionIdentifier(TEST_INSTCODE, "A2", "Musa", null)); + ids1.add(makeAccessionIdentifier(TEST_INSTCODE, "A8", "Musa", null)); + final Dataset dataset1 = datasetService.createDataset(buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, ids1, true)); + assertThat(dataset1.getAccessionCount(), is(3)); + + final Set ids2 = new HashSet<>(); + ids2.add(makeAccessionIdentifier(TEST_INSTCODE, "A1", "Musa", null)); + ids2.add(makeAccessionIdentifier(TEST_INSTCODE, "A2", "Musa", null)); + ids2.add(makeAccessionIdentifier(TEST_INSTCODE, "A3", "Manihot", null)); + final Dataset dataset2 = datasetService.createDataset(buildDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, ids2, true)); + assertThat(dataset2.getAccessionCount(), is(3)); + + final DatasetFilter filter = new DatasetFilter(); + filter.accessionIdentifier = new AccessionIdentifierFilter(); + + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(2)); + + filter.accessionIdentifier.instCode(TEST_INSTCODE); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(2)); + + filter.accessionIdentifier.instCode.clear(); + filter.accessionIdentifier.genus("Musa"); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(2)); + + filter.accessionIdentifier.genus.clear(); + filter.accessionIdentifier.genus("Manihot"); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(1)); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent().stream().map(d -> d.getUuid()).collect(Collectors.toSet()), contains(dataset2 + .getUuid())); + + filter.accessionIdentifier.genus.clear(); + filter.accessionIdentifier.genus("Manihot"); + filter.accessionIdentifier.genus("Musa"); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(2)); + + filter.accessionIdentifier.genus.clear(); + filter.accessionIdentifier.genus("Manihot"); + filter.accessionIdentifier.genus("Vigna"); // no such genus + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(1)); + + filter.accessionIdentifier.genus.clear(); + filter.accessionIdentifier.genus("Vigna"); // no such genus + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(0)); + + filter.accessionIdentifier.genus.clear(); + filter.accessionIdentifier.acceNumb = new StringFilter(); + + filter.accessionIdentifier.acceNumb.eq = "A8"; // only in dataset1 + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(1)); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent().stream().map(d -> d.getUuid()).collect(Collectors.toSet()), contains(dataset1 + .getUuid())); + + filter.accessionIdentifier.acceNumb.eq = "A1"; // in both + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(2)); + + filter.accessionIdentifier.acceNumb.eq = "A8"; // only in dataset1 + filter.accessionIdentifier.genus("Musa"); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent(), hasSize(1)); + assertThat(datasetService.listDatasets(filter, new PageRequest(0, 3)).getContent().stream().map(d -> d.getUuid()).collect(Collectors.toSet()), contains(dataset1 + .getUuid())); + } + + @Test(expected = InvalidApiUsageException.class) + public void failUpdateDatasetOwner() throws Exception { + Dataset input = buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, partner, false); + input.setOwner(partner2); + input = datasetService.updateDataset(input); + assertThat(input.getOwner(), not(partner2)); + } +} diff --git a/src/test/java/org/genesys/test/catalog/services/DescriptorListServiceTest.java b/src/test/java/org/genesys/test/catalog/services/DescriptorListServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..df6c564f3e25b4aed7e7a89866625a013b3e0753 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/DescriptorListServiceTest.java @@ -0,0 +1,509 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.FileReader; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang3.StringUtils; +import org.genesys.catalog.exceptions.InvalidApiUsageException; +import org.genesys.catalog.exceptions.NotFoundElement; +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.model.traits.Descriptor.Category; +import org.genesys.catalog.model.traits.DescriptorList; +import org.genesys.catalog.persistence.vocab.ControlledVocabularyRepository; +import org.genesys.catalog.service.DescriptorListService; +import org.genesys.catalog.service.impl.DescriptorListServiceImpl; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.ConcurrencyFailureException; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.opencsv.CSVReader; + +/** + * Test for {@link DescriptorListServiceImpl} + * + * @author Andrey Lugovskoy + */ +// @RunWith(JUnitParamsRunner.class) +public class DescriptorListServiceTest extends CatalogServiceTest { + + private static final String DESCRIPTOR_TITLE_1 = "D1"; + private static final String DESCRIPTOR_TITLE_2 = "D2"; + private static final String VERSION_1_0 = "1.0"; + private static final String VERSION_2_0 = "2.0"; + private static final String DESCRIPTION_1 = "Some description"; + private static final String DESCRIPTION_2 = "Some description"; + + private static final String PARTNER_2 = "International Partner Institute2"; + private static URL URL_2; + private static final String PARTNER_ACRONYM_2 = "IPI2"; + + private static final String DESCRIPTION_LIST_TITLE1 = "Title 1"; + private static final String DESCRIPTION_LIST_TITLE2 = "Title 2"; + + @Autowired + private DescriptorListService descriptorListService; + + private static final String DESCRIPTOR_TITLE_OF_CSV = "Accession name"; + private static final Descriptor.DataType DESCRIPTOR_DATATYPE_OF_CSV = Descriptor.DataType.TEXT; + + @Autowired + private ControlledVocabularyRepository controlledVocabularyRepository; + + protected Partner partnerSecond; + + { + try { + URL_2 = new URL("http://url2"); + } catch (final MalformedURLException e) { + } + } + + @Override + public void cleanup() throws Exception { + descriptorListRepository.deleteAll(); + descriptorRepository.deleteAll(); + partnerRepository.deleteAll(); + super.cleanup(); + partnerSecond = setupPartner(PARTNER_2, PARTNER_ACRONYM_2, Sets.newHashSet(URL_2), "RRR000", "RRR001"); + } + + @Test(expected = NotFoundElement.class) + public void testNonExistent() { + descriptorListService.getDescriptorList(UUID.randomUUID()); + } + + @Test(expected = NotFoundElement.class) + public void findNullDescriptorListById() { + assertNull(descriptorListService.getDescriptorList(10L)); + } + + @Test + public void createDescriptorList() throws Exception { + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getPublisher(), is("Publisher")); + assertThat(result.getDescriptors(), hasSize(0)); + assertEquals(partner.getId(), descriptorList.getOwner().getId()); + } + + @Test + public void findDescriptorListByUUIDTest() throws Exception { + DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + final UUID uuid = UUID.randomUUID(); + descriptorList.setUuid(uuid); + + descriptorList = descriptorListService.createDescriptorList(descriptorList); + final DescriptorList result = descriptorListService.getDescriptorList(uuid); + assertThat(result, not(nullValue())); + assertEquals(descriptorList.getId(), result.getId()); + assertEquals(descriptorList.getUuid(), result.getUuid()); + } + + @Test + public void findDescriptorListByIdTest() throws Exception { + DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList = descriptorListService.createDescriptorList(descriptorList); + + final DescriptorList result = descriptorListService.getDescriptorList(descriptorList.getId()); + assertThat(result, not(nullValue())); + assertEquals(descriptorList.getId(), result.getId()); + assertEquals(descriptorList.getUuid(), result.getUuid()); + } + + @Test + public void deleteDescriptorList() { + DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList = descriptorListService.createDescriptorList(descriptorList); + + final DescriptorList result = descriptorListService.deleteDescriptorList(descriptorList); + assertThat(result, not(nullValue())); + assertEquals(descriptorList.getId(), result.getId()); + assertEquals(descriptorList.getUuid(), result.getUuid()); + } + + @Test + public void deleteDescriptorList1() { + DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList = descriptorListService.createDescriptorList(descriptorList); + + final DescriptorList result = descriptorListService.deleteDescriptorList(descriptorList); + assertThat(result, not(nullValue())); + assertEquals(descriptorList.getId(), result.getId()); + assertEquals(descriptorList.getUuid(), result.getUuid()); + } + + @Test(expected = ConcurrencyFailureException.class) + @Ignore + public void failDeleteDescriptorList() { + DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList = descriptorListService.createDescriptorList(descriptorList); + + // This should change the version + descriptorList.setTitle(DESCRIPTION_LIST_TITLE2); + descriptorListService.updateDescriptorList(descriptorList); + + // pass outdated version + descriptorListService.deleteDescriptorList(descriptorList); + } + + @Test + public void createDescriptorListWithDescriptor() throws Exception { + + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + + final List descriptors = Lists.newArrayList(descriptorOne); + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList.setDescriptors(descriptors); + + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + + assertThat(result.getDescriptors(), hasSize(1)); + assertThat(result.getDescriptors(), contains(descriptorOne)); + } + + @Test + public void createDescriptorListWithDescriptors() throws Exception { + + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + final Descriptor descriptorTwo = setupDescriptor(partnerSecond, DESCRIPTOR_TITLE_2, VERSION_2_0, Descriptor.DataType.NUMERIC); + + final List descriptors = Lists.newArrayList(descriptorOne, descriptorTwo); + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList.setDescriptors(descriptors); + + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + + assertThat(result.getDescriptors(), hasSize(2)); + assertThat(result.getDescriptors(), contains(descriptorOne, descriptorTwo)); + } + + @Test(expected = ConcurrencyFailureException.class) + public void testFailUpdateWithoutIdentifiers() { + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + + result.setId(null); + result.setUuid(null); + result.setDescription(DESCRIPTION_1); + descriptorListService.updateDescriptorList(result); + } + + @Test(expected = ConcurrencyFailureException.class) + public void testFailUpdateNonExistent() { + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + + result.setId(null); + result.setUuid(UUID.randomUUID()); + result.setDescription(DESCRIPTION_1); + descriptorListService.updateDescriptorList(result); + } + + @Test(expected = ConcurrencyFailureException.class) + public void testFailUpdateErrorVersion() { + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + result.setVersion(result.getVersion() + 1); + descriptorListService.updateDescriptorList(result); + } + + @Test + public void updateDescriptorList() throws Exception { + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + + final List descriptors = Lists.newArrayList(descriptorOne); + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList.setDescriptors(descriptors); + + final DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + result.setDescription(DESCRIPTION_2); + result.setTitle(DESCRIPTION_LIST_TITLE2); + + // set new descriptor + final Descriptor descriptorTwo = setupDescriptor(partner, DESCRIPTOR_TITLE_2, VERSION_1_0, Descriptor.DataType.NUMERIC); + + result.setDescriptors(Lists.newArrayList(descriptorTwo)); + + final DescriptorList result2 = descriptorListService.updateDescriptorList(result); + assertThat(result2, not(nullValue())); + assertThat(result2.getId(), not(nullValue())); + assertEquals(result2.getDescription(), DESCRIPTION_2); + assertEquals(result2.getTitle(), DESCRIPTION_LIST_TITLE2); + assertThat(result.getDescriptors(), contains(descriptorTwo)); + } + + @Test + public void removeDescriptorOfDescriptorList() throws Exception { + + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + final Descriptor descriptorTwo = setupDescriptor(partnerSecond, DESCRIPTOR_TITLE_2, VERSION_2_0, Descriptor.DataType.NUMERIC); + + final List descriptors = Lists.newArrayList(descriptorOne, descriptorTwo); + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList.setDescriptors(descriptors); + + DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + assertThat(result.getDescriptors(), hasSize(2)); + result = descriptorListService.removeDescriptors(result, descriptorTwo); + assertThat(result.getDescriptors(), hasSize(1)); + assertThat(result.getDescriptors(), contains(descriptorOne)); + + assertEquals(descriptorTwo.getUuid(), descriptorRepository.findByUuid(descriptorTwo.getUuid()).getUuid()); + } + + @Test + public void removeDescriptorListButKeepDescriptors() throws Exception { + + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + final Descriptor descriptorTwo = setupDescriptor(partnerSecond, DESCRIPTOR_TITLE_2, VERSION_2_0, Descriptor.DataType.NUMERIC); + + final List descriptors = Lists.newArrayList(descriptorOne, descriptorTwo); + + DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + descriptorList.setDescriptors(descriptors); + + descriptorList = descriptorListService.createDescriptorList(descriptorList); + assertThat(descriptorList.getDescriptors(), hasSize(2)); + final DescriptorList result = descriptorListService.deleteDescriptorList(descriptorList); + assertEquals(descriptorList.getUuid(), result.getUuid()); + assertThat(descriptorListRepository.findByUuid(descriptorList.getUuid()), nullValue()); + + assertThat(descriptorRepository.findByUuid(descriptorOne.getUuid()), not(nullValue())); + assertThat(descriptorRepository.findByUuid(descriptorTwo.getUuid()), not(nullValue())); + } + + @Test + public void addDescriptorToDescriptorList() throws Exception { + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + final Descriptor descriptorTwo = setupDescriptor(partnerSecond, DESCRIPTOR_TITLE_2, VERSION_2_0, Descriptor.DataType.NUMERIC); + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + + DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + assertThat(result.getDescriptors(), hasSize(0)); + result = descriptorListService.addDescriptors(result, descriptorOne); + assertThat(result.getDescriptors(), hasSize(1)); + assertThat(result.getDescriptors(), contains(descriptorOne)); + result = descriptorListService.addDescriptors(result, descriptorTwo); + assertThat(result.getDescriptors(), hasSize(2)); + assertThat(result.getDescriptors(), contains(descriptorOne, descriptorTwo)); + } + + @Test + public void addDescriptorToManyLists() throws Exception { + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + final Descriptor descriptorTwo = setupDescriptor(partnerSecond, DESCRIPTOR_TITLE_2, VERSION_2_0, Descriptor.DataType.NUMERIC); + + final DescriptorList descriptorList1 = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + final DescriptorList descriptorList2 = setupDescriptorList(DESCRIPTION_LIST_TITLE2, VERSION_1_0, DESCRIPTION_1); + + DescriptorList list1 = descriptorListService.createDescriptorList(descriptorList1); + list1 = descriptorListService.addDescriptors(list1, descriptorOne); + list1 = descriptorListService.addDescriptors(list1, descriptorTwo); + assertThat(list1.getDescriptors(), hasSize(2)); + assertThat(list1.getDescriptors(), contains(descriptorOne, descriptorTwo)); + + DescriptorList list2 = descriptorListService.createDescriptorList(descriptorList2); + list2 = descriptorListService.addDescriptors(list2, descriptorOne); + assertThat(list2.getDescriptors(), contains(descriptorOne)); + + Descriptor descriptor1 = descriptorService.getDescriptor(descriptorOne.getUuid()); + assertThat(descriptor1.getDescriptorLists(), containsInAnyOrder(list1, list2)); + list2 = descriptorListService.removeDescriptors(list2, descriptorOne); + + descriptor1 = descriptorService.getDescriptor(descriptorOne.getUuid()); + assertThat(descriptor1.getDescriptorLists(), containsInAnyOrder(list1)); + } + + /** + * Ensure that descriptors in descriptor list get published when list is + * published. + */ + @Test + public void publishDescriptorList() throws Exception { + final Descriptor descriptorOne = setupDescriptor(partner, DESCRIPTOR_TITLE_1, VERSION_1_0, Descriptor.DataType.NUMERIC); + final Descriptor descriptorTwo = setupDescriptor(partnerSecond, DESCRIPTOR_TITLE_2, VERSION_2_0, Descriptor.DataType.NUMERIC); + + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + + DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + result = descriptorListService.addDescriptors(result, descriptorOne); + result = descriptorListService.addDescriptors(result, descriptorTwo); + + for (final Descriptor d : result.getDescriptors()) { + assertThat(d.isPublished(), is(false)); + } + + assertThat(result.getDescriptors(), contains(descriptorOne, descriptorTwo)); + assertThat(result.isPublished(), is(false)); + + result = descriptorListService.publishDescriptorList(result); + assertThat(result.isPublished(), is(true)); + + for (final Descriptor d : result.getDescriptors()) { + assertThat(d.isPublished(), is(true)); + } + } + + @Test + public void uploadDescriptorListOfCSV() throws IOException { + + final List descriptors = new ArrayList<>(); + + try (CSVReader reader = new CSVReader(new FileReader("src/test/resources/mcpd20177.csv"))) { + + String[] row; + int i = 0; + while ((row = reader.readNext()) != null) { + if (row != null && i != 0) { + // LOG.debug(Arrays.toString(row)); + + final Descriptor descriptor = new Descriptor(); + descriptor.setTitle(row[0]); + + try { + descriptor.setDataType(Descriptor.DataType.valueOf(row[1].toUpperCase())); + } catch (final IllegalArgumentException e) { + // LOG.error("Parse column for Descriptor.DataType has error.", e); + // throw new NullPointerException("Parse column for Descriptor.DataType has + // error."); + continue; + } + + descriptor.setDescription(row[2]); + descriptor.setIntegerOnly(Boolean.valueOf(row[3])); + + try { + if (StringUtils.isNotBlank(row[4])) { + descriptor.setMaxValue(Double.valueOf(row[4])); + } + } catch (final NumberFormatException e) { + LOG.error("Parsing column for MaxValue has error", e); + } + + try { + if (StringUtils.isNotBlank(row[5])) { + descriptor.setMinValue(Double.valueOf(row[5])); + } + } catch (final NumberFormatException e) { + LOG.error("Parsing column for MinValue has error", e); + } + + descriptor.setPublished(Boolean.valueOf(row[6])); + descriptor.setVersionTag(row[7]); + try { + if (StringUtils.isNotBlank(row[8])) { + descriptor.setVocabulary(controlledVocabularyRepository.findOne(Long.valueOf(row[8]))); + } + } catch (final NumberFormatException e) { + LOG.error("Parsing column for Vocabulary has error"); + } + descriptor.setColumnName(row[9]); + try { + descriptor.setUom(row[10]); + } catch (final ArrayIndexOutOfBoundsException e) { + descriptor.setUom(""); + } + descriptors.add(descriptor); + } + i++; + } + + assertThat(descriptors, hasSize(not(nullValue()))); + assertThat(descriptors, hasSize(18)); + assertThat(descriptors.get(0).getTitle(), equalTo(DESCRIPTOR_TITLE_OF_CSV)); + assertThat(descriptors.get(0).getDataType(), equalTo(DESCRIPTOR_DATATYPE_OF_CSV)); + assertThat(descriptors.get(0).getVocabulary(), nullValue()); + } + } + + @Override + public DescriptorList setupDescriptorList(final String title, final String version, final String description) { + final DescriptorList descriptorList = new DescriptorList(); + descriptorList.setOwner(partner); + descriptorList.setTitle(title); + descriptorList.setVersionTag(version); + descriptorList.setDescription(description); + descriptorList.setPublisher("Publisher"); + return descriptorList; + } + + @Override + protected Descriptor setupDescriptor(final Partner partner, final String title, final String version, final Descriptor.DataType dataType) { + final Descriptor descriptorOne = new Descriptor(); + descriptorOne.setCategory(Category.CHARACTERIZATION); + descriptorOne.setTitle(title); + descriptorOne.setVersionTag(version); + descriptorOne.setDataType(dataType); + descriptorOne.setOwner(partner); + return descriptorService.createDescriptor(descriptorOne); + } + + @Test(expected = InvalidApiUsageException.class) + public void failUpdateDescriptorListOwner() throws Exception { + DescriptorList result = descriptorListService.createDescriptorList(setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1)); + result.setOwner(partner2); + result = descriptorListService.updateDescriptorList(result); + assertThat(result.getOwner(), not(partner2)); + } + + @Test + @Ignore + public void updateDescriptorListExtras() throws Exception { + final DescriptorList descriptorList = setupDescriptorList(DESCRIPTION_LIST_TITLE1, VERSION_1_0, DESCRIPTION_1); + + DescriptorList result = descriptorListService.createDescriptorList(descriptorList); + assertThat(result.getExtras(), is(nullValue())); + + // set extra + result.setExtras(new HashMap<>()); + result.getExtras().put(DescriptorList.Extra.JSON_MAPPING, "This is JSON extra"); + result = descriptorListService.updateDescriptorList(result); + + assertThat(result.getExtras(), not(nullValue())); + assertThat(result.getExtras().keySet(), hasSize(1)); + + result.getExtras().clear(); + result = descriptorListService.updateDescriptorList(result); + assertThat(result.getExtras(), not(nullValue())); + assertThat(result.getExtras().keySet(), hasSize(0)); + } + +} diff --git a/src/test/java/org/genesys/test/catalog/services/DescriptorServiceTest.java b/src/test/java/org/genesys/test/catalog/services/DescriptorServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b73e46f0b3fa9c1af9b7655e2315790305f58fdd --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/DescriptorServiceTest.java @@ -0,0 +1,515 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang3.RandomStringUtils; +import org.genesys.catalog.exceptions.InvalidApiUsageException; +import org.genesys.catalog.exceptions.NotFoundElement; +import org.genesys.catalog.model.filters.DescriptorFilter; +import org.genesys.catalog.model.traits.Descriptor; +import org.genesys.catalog.model.traits.Descriptor.Category; +import org.genesys.catalog.model.traits.Descriptor.DataType; +import org.genesys.catalog.model.traits.DescriptorList; +import org.genesys.catalog.model.vocab.ControlledVocabulary; +import org.genesys.catalog.model.vocab.VocabularyTerm; +import org.junit.Test; +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; + +import com.google.common.collect.Lists; + +public class DescriptorServiceTest extends CatalogServiceTest { + + private static final String DESCRIPTOR_TITLE_1 = "D1"; + private static final String DESCRIPTOR_TITLE_2 = "D2"; + private static final String VERSION_1_0 = "1.0"; + // private static final String VERSION_1_1 = "1.1"; + private static final String VERSION_2_0 = "2.0"; + private static final String DESCRIPTION_1 = "Some description"; + + @Override + public void cleanup() throws Exception { + descriptorRepository.deleteAll(); + super.cleanup(); + } + + @Test(expected = NotFoundElement.class) + public void testNonExistent() throws NotFoundElement { + descriptorService.getDescriptor(UUID.randomUUID()); + } + + private Descriptor setupDescriptor(final UUID uuid, final String title, final Category category, final DataType type, final String versionTag, final boolean published) { + final Descriptor input = new Descriptor(); + input.setOwner(partner); + + input.setUuid(uuid); + input.setTitle(title); + input.setVersionTag(versionTag); + input.setDataType(type); + input.setCategory(category); + input.setPublished(published); + return input; + } + + @Test + public void testCreateDescriptor() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + Descriptor result = descriptorService.createDescriptor(input); + + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertEquals(partner.getUuid(), result.getOwner().getUuid()); + + result = descriptorService.getDescriptor(result.getUuid()); + assertThat(result, notNullValue()); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testCreateDescriptorWithoutTerms() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.CODED, VERSION_1_0, false); + descriptorService.createDescriptor(input); + } + + @Test + public void testCreateDescriptorWithTerms() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.CODED, VERSION_1_0, false); + input.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2))); + final Descriptor result = descriptorService.createDescriptor(input); + + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getTerms(), not(hasSize(0))); + } + + @Test(expected = NotFoundElement.class) + public void testRemoveDescriptor() { + final UUID uuid = UUID.randomUUID(); + final Descriptor input = setupDescriptor(uuid, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + input.setMinValue(10D); + input.setMaxValue(10D); + + Descriptor result = descriptorService.createDescriptor(input); + result = descriptorService.removeDescriptor(result); + descriptorService.getDescriptor(result.getUuid(), result.getVersion()); + } + + @Test + public void createDescriptorWithVocabularyForDataTypeTEXT() { + final UUID uuid = UUID.randomUUID(); + + final ControlledVocabulary vocab1 = new ControlledVocabulary(); + vocab1.setTitle("TEST vocabulary"); + vocab1.setOwner(partner); + final ControlledVocabulary vocabularyResult = vocabularyService.createVocabulary(vocab1); + + final Descriptor input = setupDescriptor(uuid, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.TEXT, VERSION_1_0, false); + input.setVocabulary(vocabularyResult); + + Descriptor result = descriptorService.createDescriptor(input); + result = descriptorService.getDescriptor(uuid); + assertThat(result.getVocabulary(), nullValue()); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testCreateScaleDescriptorWithVocabulary() { + ControlledVocabulary vocab = new ControlledVocabulary(); + vocab.setTitle("TEST vocabulary"); + vocab.setOwner(partner); + vocab = vocabularyService.createVocabulary(vocab); + + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.SCALE, VERSION_1_0, false); + input.setVocabulary(vocab); + input.setMinValue(0d); + input.setMaxValue(10d); + + descriptorService.createDescriptor(input); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testCreateScaleDescriptorWithoutMaxAndMinValues() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.SCALE, VERSION_1_0, false); + input.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2))); + + descriptorService.createDescriptor(input); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testCreateScaleDescriptorWithoutMinvalue() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.SCALE, VERSION_1_0, false); + input.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2))); + + input.setMaxValue(10D); + descriptorService.createDescriptor(input); + } + + @Test(expected = DataIntegrityViolationException.class) + public void testCreateScaleDescriptorWithoutMaxvalue() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.SCALE, VERSION_1_0, false); + input.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2))); + + input.setMinValue(10D); + descriptorService.createDescriptor(input); + } + + @Test + public void testCreateScaleDescriptor() { + final UUID uuid = UUID.randomUUID(); + final Descriptor input = setupDescriptor(uuid, DESCRIPTOR_TITLE_1, Category.EVALUATION, DataType.SCALE, VERSION_1_0, false); + input.setMinValue(0d); + input.setMaxValue(10d); + input.setTerms(Lists.newArrayList(VocabularyTerm.fromData(TERM_CODE_1, TERM_TITLE_1), VocabularyTerm.fromData(TERM_CODE_2, TERM_TITLE_2))); + + final Descriptor result = descriptorService.createDescriptor(input); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.getDataType(), is(DataType.SCALE)); + assertThat(result.getMinValue(), is(0d)); + assertThat(result.getMaxValue(), is(10d)); + assertThat(result.getTerms(), hasSize(2)); + } + + @Test + public void testCreateDescriptorWithUuid() { + final UUID uuid = UUID.randomUUID(); + final Descriptor input = setupDescriptor(uuid, DESCRIPTOR_TITLE_1, Category.CHARACTERIZATION, DataType.TEXT, VERSION_1_0, false); + final Descriptor result = descriptorService.createDescriptor(input); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.isPublished(), is(false)); + assertThat(result.getCategory(), is(Category.CHARACTERIZATION)); + } + + @Test + public void testGetDescriptorByUuid() { + final UUID uuid = UUID.randomUUID(); + final Descriptor input = setupDescriptor(uuid, DESCRIPTOR_TITLE_1, Category.CHARACTERIZATION, DataType.NUMERIC, VERSION_1_0, false); + + Descriptor result = descriptorService.createDescriptor(input); + result = descriptorService.getDescriptor(uuid); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.isPublished(), is(false)); + assertThat(result.getCategory(), is(Category.CHARACTERIZATION)); + } + + @Test + public void testUpdateDescriptorByUuidAndVersion() { + final UUID uuid = UUID.randomUUID(); + final Descriptor input = setupDescriptor(uuid, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + + Descriptor result = descriptorService.createDescriptor(input); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getTitle(), is(DESCRIPTOR_TITLE_1)); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + + result.setTitle(DESCRIPTOR_TITLE_2); + result.setDescription(DESCRIPTION_1); + result = descriptorService.updateDescriptor(result); + + assertThat(result.getTitle(), is(DESCRIPTOR_TITLE_2)); + assertThat(result.getDescription(), is(DESCRIPTION_1)); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + + result.setDataType(DataType.DATE); + result = descriptorService.updateDescriptor(result); + assertThat(result.getDataType(), equalTo(DataType.DATE)); + assertThat(result.getVocabulary(), nullValue()); + } + + @Test + public void testUpdateDescriptor() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + Descriptor result = descriptorService.createDescriptor(input); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getUuid(), not(nullValue())); + assertThat(result.getTitle(), is(DESCRIPTOR_TITLE_1)); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + + input.setUuid(result.getUuid()); + input.setVersion(result.getVersion()); + input.setTitle(DESCRIPTOR_TITLE_2); + input.setDescription(DESCRIPTION_1); + result = descriptorService.updateDescriptor(input); + assertThat(result.getCategory(), is(Category.PASSPORT)); + assertThat(result.getTitle(), is(DESCRIPTOR_TITLE_2)); + assertThat(result.getDescription(), is(DESCRIPTION_1)); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + + input.setVersion(result.getVersion()); + input.setMinValue(1.0); + input.setMaxValue(10.0); + result = descriptorService.updateDescriptor(input); + assertThat(result.getMinValue(), is(1.0)); + assertThat(result.getMaxValue(), is(10.0)); + + input.setVersion(result.getVersion()); + input.setMinValue(0.0); + input.setMaxValue(null); + result = descriptorService.updateDescriptor(input); + assertThat(result.getMinValue(), is(0.0)); + assertThat(result.getMaxValue(), is(nullValue())); + } + + @Test + public void createDescriptorWithDescriptorLists() { + final DescriptorList descriptorList = setupDescriptorList("DescriptorTitle 1", VERSION_1_0, DESCRIPTION_1); + + final List descriptorLists = new ArrayList() { + /** + * + */ + private static final long serialVersionUID = -5681752165895145466L; + + { + add(descriptorList); + } + }; + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.EVALUATION, DataType.NUMERIC, VERSION_1_0, false); + input.setDescriptorLists(descriptorLists); + final Descriptor result = descriptorRepository.save(input); + assertThat(result, not(nullValue())); + assertThat(result.getDescriptorLists(), not(nullValue())); + assertThat(result.getDescriptorLists(), hasSize(1)); + assertEquals(result.getDescriptorLists().get(0), descriptorList); + } + + /** + * Fail to update descriptor when isPublish() = true + */ + @Test(expected = DataIntegrityViolationException.class) + public void testFailOnUpdateDescriptorWithPublished() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.EVALUATION, DataType.NUMERIC, VERSION_1_0, false); + input.setPublished(Boolean.TRUE); + final Descriptor result = descriptorService.createDescriptor(input); + + result.setUuid(result.getUuid()); + result.setTitle(DESCRIPTOR_TITLE_2); + result.setDescription(DESCRIPTION_1); + descriptorService.updateDescriptor(result); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public void testFailUpdateWithoutIdentifiers() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.EVALUATION, DataType.NUMERIC, VERSION_1_0, false); + input.setPublished(Boolean.TRUE); + final Descriptor result = descriptorService.createDescriptor(input); + + result.setUuid(null); + result.setId(null); + result.setDescription(DESCRIPTION_1); + descriptorService.updateDescriptor(result); + } + + @Test(expected = ConcurrencyFailureException.class) + public void testFailConcurrentUpdate() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + input.setPublished(Boolean.TRUE); + final Descriptor result = descriptorService.createDescriptor(input); + + result.setVersion(result.getVersion() + 1); + result.setDescription(DESCRIPTION_1); + descriptorService.updateDescriptor(result); + } + + @Test(expected = DataRetrievalFailureException.class) + public void testFailUpdateNonExistent() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + input.setPublished(Boolean.TRUE); + final Descriptor result = descriptorService.createDescriptor(input); + + result.setId(null); + result.setUuid(UUID.randomUUID()); + result.setDescription(DESCRIPTION_1); + descriptorService.updateDescriptor(result); + } + + @Test + public void testNeverUpdateDescriptorVersion() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false); + Descriptor result = descriptorService.createDescriptor(input); + assertThat(result, not(nullValue())); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + + result.setVersionTag(VERSION_2_0); + descriptorService.updateDescriptor(result); + result = descriptorService.getDescriptor(result.getUuid()); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + } + + @Test + public void listDescriptorsTest() { + // unpublished descriptor + descriptorService.createDescriptor(setupDescriptor(null, "Not published " + DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, false)); + + // published descriptor to be listed + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.NUMERIC, VERSION_1_0, true); + final Descriptor result = descriptorService.createDescriptor(input); + + final String[] strs = new String[] { "title" }; + final Pageable pageable = new PageRequest(0, Integer.min(50, 100), Sort.Direction.ASC, strs); + final Page pageResult = descriptorService.listDescriptors(new DescriptorFilter(), pageable); + assertThat(pageResult.getContent(), not(nullValue())); + assertThat(pageResult.getContent(), hasSize(1)); + assertThat(pageResult.getContent().get(0), equalTo(result)); + } + + @Test + public void updateDescriptorForDataType() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.BOOLEAN, VERSION_1_0, false); + final Descriptor result = descriptorService.createDescriptor(input); + assertThat(result.getVocabulary(), nullValue()); + assertThat(result.getMinValue(), nullValue()); + assertThat(result.getMaxValue(), nullValue()); + } + + @Test + public void testUpsertMultiple() { + final List descriptors = new ArrayList<>(); + final long timestamp = System.currentTimeMillis(); + final String description = RandomStringUtils.randomAlphabetic(50, 100); + for (int i = 0; i < 5; i++) { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1 + timestamp + "-" + i, Category.PASSPORT, DataType.TEXT, VERSION_1_0, false); + input.setDescription(description + "-" + i); + descriptors.add(input); + } + + final List descriptors2 = descriptorService.upsertDescriptors(descriptors); + assertThat(descriptors2, hasSize(descriptors.size())); + + // Update some + for (final Descriptor d : descriptors2) { + assertThat(d.getUuid(), not(nullValue())); + assertThat(d.getId(), not(nullValue())); + assertThat(d.getVersion(), not(nullValue())); + + d.setDataType(DataType.NUMERIC); + d.setCategory(Category.EVALUATION); + d.setIntegerOnly(true); + d.setMinValue(0d); + d.setMaxValue(10d); + } + // Add some + for (int i = 0; i < 5; i++) { + final Descriptor d = setupDescriptor(null, DESCRIPTOR_TITLE_1 + timestamp + "-" + i, Category.EVALUATION, DataType.TEXT, VERSION_2_0, false); + d.setDescription(description + "-" + i); + descriptors2.add(d); + } + + final List descriptors3 = descriptorService.upsertDescriptors(descriptors2); + assertThat(descriptors3, hasSize(descriptors2.size())); + + for (int i = 0; i < descriptors3.size(); i++) { + final Descriptor d3 = descriptors3.get(i), d2 = descriptors2.get(i); + assertThat(d3.getUuid(), not(nullValue())); + assertThat(d3.getId(), not(nullValue())); + assertThat(d3.getVersion(), not(nullValue())); + + assertThat(d3.getCategory(), is(d2.getCategory())); + assertThat(d3.getTitle(), is(d2.getTitle())); + assertThat(d3.getDescription(), is(d2.getDescription())); + assertThat(d3.getDataType(), is(d2.getDataType())); + assertThat(d3.getIntegerOnly(), is(d2.getIntegerOnly())); + assertThat(d3.getMinValue(), is(d2.getMinValue())); + assertThat(d3.getMaxValue(), is(d2.getMaxValue())); + } + } + + @Test(expected = InvalidApiUsageException.class) + public void failUpdateDescriptorOwner() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.BOOLEAN, VERSION_1_0, false); + Descriptor result = descriptorService.createDescriptor(input); + result.setOwner(partner2); + result = descriptorService.updateDescriptor(result); + assertThat(result.getOwner(), not(partner2)); + } + + @Test + public void testKeywordSearch() { + descriptorService.createDescriptor(setupDescriptor(null, "AAA CCDD", Category.PASSPORT, DataType.BOOLEAN, VERSION_1_0, true)); + descriptorService.createDescriptor(setupDescriptor(null, "AAA BBEE1", Category.PASSPORT, DataType.BOOLEAN, VERSION_1_0, true)); + + final Pageable page = new PageRequest(0, 10); + final DescriptorFilter descriptorFilter = new DescriptorFilter(); + Page paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(2)); + + descriptorFilter._text = "AAA"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(2)); + + descriptorFilter._text = "BBEE"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(1)); + + descriptorFilter._text = "BB"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(1)); + + descriptorFilter._text = "BB CC"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(0)); + + descriptorFilter._text = "AAA FF"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(0)); + + descriptorFilter._text = "AAA BB"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(1)); + + descriptorFilter._text = "AAA 1"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(1)); + + descriptorFilter._text = "# AAA 1!"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(1)); + + descriptorFilter._text = "NOSUCHTHING"; + paged = descriptorService.listDescriptors(descriptorFilter, page); + assertThat(paged.getContent(), hasSize(0)); + } + + @Test + public void newDescriptorVersion() { + final Descriptor input = setupDescriptor(null, DESCRIPTOR_TITLE_1, Category.PASSPORT, DataType.BOOLEAN, VERSION_1_0, false); + final Descriptor result = descriptorService.createDescriptor(input); + assertThat(result.getVersionTag(), is(VERSION_1_0)); + Descriptor newVersion = descriptorService.nextVersion(result, false); + assertThat(newVersion.getUuid(), not(result.getUuid())); + assertThat(newVersion.getVersionTag(), is("1.1")); + + newVersion = descriptorService.nextVersion(result, true); + assertThat(newVersion.getUuid(), not(result.getUuid())); + assertThat(newVersion.getVersionTag(), is("2.0")); + + newVersion = descriptorService.nextVersion(newVersion, false); + assertThat(newVersion.getVersionTag(), is("2.1")); + } + +} diff --git a/src/test/java/org/genesys/test/catalog/services/PartnerServiceTest.java b/src/test/java/org/genesys/test/catalog/services/PartnerServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8a2158d5f8b6f53b20f58d9e02c7518a18eb0b56 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/PartnerServiceTest.java @@ -0,0 +1,294 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; + +import org.apache.commons.lang3.RandomStringUtils; +import org.genesys.catalog.model.Partner; +import org.genesys.catalog.model.filters.PartnerFilter; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.transaction.annotation.Transactional; + +import com.google.common.collect.Sets; + +public class PartnerServiceTest extends CatalogServiceTest { + + private static final String PARTNER_1 = "International Partner Institute"; + private static final String PARTNER_2 = "Regional Partner Organization"; + private static final String PARTNER_ACRONYM_1 = "IPI"; + private static final String PARTNER_ACRONYM_2 = "RPO"; + private static final String URL_1 = "http://url1"; + private static final String URL_2 = "http://url2"; + private static final String EMAIL_1 = "test1@email.com"; + private static final String EMAIL_2 = "test2@email.com"; + private static final String ADDRESS_1 = "test address 1"; + private static final String ADDRESS_2 = "test address 2"; + private static final String PHONE_1 = "123456789"; + private static final String PHONE_2 = "987654321"; + // private static final String URL_3 = "http://url3"; + + @Before + @Transactional + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + + partnerRepository.deleteAll(); + assertThat(partnerRepository.count(), is(0l)); + } + + @After + @Transactional + @Override + public void cleanup() throws Exception { + partnerRepository.deleteAll(); + super.cleanup(); + } + + @Test + public void testCreatePartner() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + input.setUrls(Sets.newHashSet(new URL(URL_1), new URL(URL_2))); + input.setWiewsCodes(Sets.newHashSet("XXX001", "XXX002", "YYY003")); + final String description = RandomStringUtils.randomAlphanumeric(60, 100); + input.setDescription(description); + input.setEmail(EMAIL_1); + input.setAddress(ADDRESS_1); + input.setPhone(PHONE_1); + + final Partner result = partnerService.createPartner(input); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getUrls(), hasSize(2)); + assertThat(result.getUrls(), containsInAnyOrder(new URL(URL_1), new URL(URL_2))); + assertThat(result.getWiewsCodes(), hasSize(3)); + assertThat(result.getWiewsCodes(), containsInAnyOrder("XXX001", "XXX002", "YYY003")); + assertThat(result.getDescription(), is(description)); + assertThat(result.getEmail(), is(EMAIL_1)); + assertThat(result.getAddress(), is(ADDRESS_1)); + assertThat(result.getPhone(), is(PHONE_1)); + } + + /** + * I should be able to specify the UUID of Partner on create + */ + @Test + public void testCreatePartnerWithUuid() { + final Partner input = new Partner(); + final UUID uuid = UUID.randomUUID(); + input.setUuid(uuid); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + final Partner result = partnerService.createPartner(input); + assertThat(result, not(nullValue())); + assertThat(result.getId(), not(nullValue())); + assertThat(result.getUuid(), is(uuid)); + } + + /** + * I should not be able to insert a conflicting shortName. + * {@link Partner#shortName} is unique + */ + @Test(expected = DataIntegrityViolationException.class) + @Ignore + public void testFailDuplicateShortName() { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + final Partner result = partnerService.createPartner(input); + assertThat(result.getId(), not(nullValue())); + + input.setName(PARTNER_2); + partnerService.createPartner(input); + } + + /** + * I need to update Partner data, including URLs and associated WIEWS codes + */ + @Test + public void testUpdatePartner() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + input.setEmail(EMAIL_1); + input.setAddress(ADDRESS_1); + input.setPhone(PHONE_1); + + Partner result = partnerService.createPartner(input); + final UUID uuid = result.getUuid(); + assertThat(result.getName(), is(PARTNER_1)); + assertThat(result.getShortName(), is(PARTNER_ACRONYM_1)); + assertThat(result.getEmail(), is(EMAIL_1)); + assertThat(result.getAddress(), is(ADDRESS_1)); + assertThat(result.getPhone(), is(PHONE_1)); + + // update + result.setName(PARTNER_2); + result.setShortName(PARTNER_ACRONYM_2); + result.getUrls().add(new URL(URL_1)); + result.setWiewsCodes(Sets.newHashSet("XXX001", "XXX002", "YYY003")); + final String description = RandomStringUtils.random(100); + result.setDescription(description); + result.setEmail(EMAIL_2); + result.setAddress(ADDRESS_2); + result.setPhone(PHONE_2); + result = partnerService.updatePartner(result); + assertThat(result.getUuid(), is(uuid)); + assertThat(result.getName(), is(PARTNER_2)); + assertThat(result.getShortName(), is(PARTNER_ACRONYM_2)); + assertThat(result.getUrls(), hasSize(1)); + assertThat(result.getUrls(), containsInAnyOrder(new URL(URL_1))); + assertThat(result.getWiewsCodes(), containsInAnyOrder("XXX001", "XXX002", "YYY003")); + assertThat(result.getDescription(), is(description)); + assertThat(result.getEmail(), is(EMAIL_2)); + assertThat(result.getAddress(), is(ADDRESS_2)); + assertThat(result.getPhone(), is(PHONE_2)); + } + + @Test + public void testUpdatePartnerById() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + + Partner result = partnerService.createPartner(input); + + // update + input.setName(PARTNER_2); + final String description = RandomStringUtils.random(100); + input.setDescription(description); + input.setId(result.getId()); + input.setVersion(result.getVersion()); + result = partnerService.updatePartner(input); + assertThat(result.getName(), is(PARTNER_2)); + assertThat(result.getDescription(), is(description)); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public void testFailUpdatePartnerWithoutIdentifiers() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + + // update + input.setId(null); + partnerService.updatePartner(input); + } + + /** + * I should not be able to update the record if it was updated by another entity + */ + @Test(expected = ConcurrencyFailureException.class) + public void testUpdatePartnerConflict() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + final Partner result = partnerService.createPartner(input); + + // update 1 + result.setName(PARTNER_2); + final Partner result2 = partnerService.updatePartner(result); + assertThat(result2.getName(), is(PARTNER_2)); + + // update again and fail + partnerService.updatePartner(result); + } + + @Test(expected = DataRetrievalFailureException.class) + public void testUpdatePartnerNull() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + final Partner result = partnerService.createPartner(input); + + result.setId(100L); + result.setUuid(UUID.randomUUID()); + partnerService.updatePartner(result); + } + + @Test + public void testListPartner() { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + final Partner result = partnerService.createPartner(input); + + final String[] strs = new String[] { "shortName" }; + final Pageable pageable = new PageRequest(0, Integer.min(50, 100), Sort.Direction.ASC, strs); + final Page page = partnerService.listPartners(new PartnerFilter(), pageable); + + assertThat(page.getTotalElements(), is(1L)); + assertThat(page.getContent().get(0).getUuid(), is(result.getUuid())); + } + + @Test + public void testPartnerByUuid() { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + + Partner result = partnerService.createPartner(input); + final UUID uuid = result.getUuid(); + + result = partnerService.loadPartner(uuid); + + assertThat(result.getUuid(), is(uuid)); + } + + /** + * I need to update Partner country codes + */ + @Test + public void testUpdatePartnerCountries() throws MalformedURLException { + final Partner input = new Partner(); + input.setName(PARTNER_1); + input.setShortName(PARTNER_ACRONYM_1); + + Partner result = partnerService.createPartner(input); + final UUID uuid = result.getUuid(); + + // update + result.setCountryCodes(Sets.newHashSet("NGA", "DEU", "SVN")); + result = partnerService.updatePartner(result); + + assertThat(result.getUuid(), is(uuid)); + assertThat(result.getCountryCodes(), containsInAnyOrder("NGA", "DEU", "SVN")); + + result.setCountryCodes(Sets.newHashSet("BAR", "FOO")); + result = partnerService.updatePartner(result); + assertThat(result.getCountryCodes(), containsInAnyOrder("FOO", "BAR")); + } + +} diff --git a/src/test/java/org/genesys/test/catalog/services/ShortFilterServiceTest.java b/src/test/java/org/genesys/test/catalog/services/ShortFilterServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..511212ed9c30d1975120b7ba630e669902da3c70 --- /dev/null +++ b/src/test/java/org/genesys/test/catalog/services/ShortFilterServiceTest.java @@ -0,0 +1,172 @@ +/* + * 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.test.catalog.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.RandomStringUtils; +import org.genesys.blocks.model.filters.StringFilter; +import org.genesys.catalog.model.ShortFilter; +import org.genesys.catalog.model.filters.DescriptorListFilter; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * @author Maxym Borodenko + */ +public class ShortFilterServiceTest extends CatalogServiceTest { + + private static final String SHORT_NAME_1 = "v1cf4c01a7efed4f6697ddac7a974c4859"; + private static final String SHORT_NAME_2 = "v18a0c1ab8180c48208776fcbc1e016cff"; + private static final String JSON_FILTERS_1 = "{\"crop\":[\"apple\",\"banana\",\"barley\",\"potato\"],\"title\":{\"contains\":\"test\"}}"; + private static final String JSON_FILTERS_2 = "{\"crop\":[\"apple\",\"banana\",\"barley\",\"potato\"]}"; + + @Override + public void cleanup() throws Exception { + shortFilterRepository.deleteAll(); + super.cleanup(); + } + + @Test + public void testSave() { + final ShortFilter shortFilter = shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_1)); + assertThat(shortFilter, not(nullValue())); + assertThat(shortFilter.getCode(), is(SHORT_NAME_1)); + assertThat(shortFilter.getJson(), is(JSON_FILTERS_1)); + } + + @Test + public void testCreate() throws IOException { + final DescriptorListFilter filter = new DescriptorListFilter(); + filter.title = new StringFilter(); + filter.title.eq = "TEST"; + filter.description = new StringFilter(); + final String [] cropValues = { "yam", "banana", "wheat", "rice", "barley", "apple" }; + filter.description.eq = "THIS IS description"; + filter.description.contains = "contains description"; + filter.crop = Arrays.stream(cropValues).collect(Collectors.toSet()); + + String shortName = shortFilterService.getCode(filter); + final ShortFilter shortFilter = shortFilterService.loadByCode(shortName); + assertThat(shortFilter, not(nullValue())); + assertThat(shortFilterRepository.findAll().size(), is(1)); + + // try to get ShortFilter from already used filter + final String shortName2 = shortFilterService.getCode(filter); + assertThat(shortName2, is(shortName)); + + // no new record should be added in the ShortFilter table + assertThat(shortFilterRepository.findAll().size(), is(1)); + } + + @Test + public void testLoadByShortName() { + final ShortFilter shortFilter1 = shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_1)); + assertThat(shortFilter1, not(nullValue())); + + final ShortFilter shortFilter2 = shortFilterRepository.save(new ShortFilter(SHORT_NAME_2, JSON_FILTERS_2)); + assertThat(shortFilter2, not(nullValue())); + + assertThat(shortFilterRepository.findAll().size(), is(2)); + + final ShortFilter foundShortFilter = shortFilterService.loadByCode(SHORT_NAME_1); + assertTrue(foundShortFilter.equals(shortFilter1)); + } + + @Test + public void testLoadByJsonFilters() { + final ShortFilter shortFilter = shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_1)); + assertThat(shortFilter, not(nullValue())); + + final ShortFilter foundShortFilter = shortFilterService.loadByJSON(JSON_FILTERS_1); + assertTrue(foundShortFilter.equals(shortFilter)); + } + + @Test + public void testLoad() { + final ShortFilter shortFilter = shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_2)); + assertThat(shortFilter, not(nullValue())); + + final ShortFilter foundShortFilter1 = shortFilterService.load(JSON_FILTERS_2); + final ShortFilter foundShortFilter2 = shortFilterService.load(SHORT_NAME_1); + + assertTrue(foundShortFilter1.equals(shortFilter) && foundShortFilter1.equals(foundShortFilter2)); + } + + /** + * It should not be able to insert a conflicting shortName. + * {@link ShortFilter#shortName} is unique + */ + @Test(expected = DataIntegrityViolationException.class) + @Ignore + public void testSaveWithNotUniqueShortName() { + final ShortFilter shortFilter1 = shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_1)); + assertThat(shortFilter1, not(nullValue())); + + // create a new ShortFilter with the same shortName + shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_2)); + } + + /** + * It should be able to insert a conflicting json. + * {@link ShortFilter#json} is indexed + */ + @Test + public void testSaveWithNotUniqueJsonFilters() { + final ShortFilter shortFilter1 = shortFilterRepository.save(new ShortFilter(SHORT_NAME_1, JSON_FILTERS_1)); + assertThat(shortFilter1, not(nullValue())); + + // create a new ShortFilter with the same jsonFilters + shortFilterRepository.save(new ShortFilter(SHORT_NAME_2, JSON_FILTERS_1)); + } + + @Test + public void testNormalizeFilters() throws IOException { + final String [] unsortedCropValues1 = { "Banana", "Wheat", "apple", "yam", "rice", "barley" }; + final String [] unsortedCropValues2 = { "yam", "Banana", "Wheat", "rice", "barley", "apple" }; + + final DescriptorListFilter filter1 = new DescriptorListFilter(); + filter1.crop = Arrays.stream(unsortedCropValues1).collect(Collectors.toSet()); + + final DescriptorListFilter filter2 = new DescriptorListFilter(); + filter2.crop = Arrays.stream(unsortedCropValues2).collect(Collectors.toSet()); + + final String normalizedFilter1 = shortFilterService.normalizeFilter(filter1); + final String normalizedFilter2 = shortFilterService.normalizeFilter(filter2); + + assertEquals(normalizedFilter1, normalizedFilter2); + } + + /** + * ShortFilter returns a code for very long filters. + * + * {"_text":""} .. 12 characters + */ + @Test + public void testVeryLongFilter() throws IOException { + final DescriptorListFilter filter = new DescriptorListFilter(); + + filter._text=RandomStringUtils.randomAlphabetic(1000); + String code = shortFilterService.getCode(filter); + assertThat(code, not(nullValue())); + } +} diff --git a/src/test/java/org/genesys/test/config/ApplicationConfig.java b/src/test/java/org/genesys/test/config/ApplicationConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..44aba6b704ddc6de2393daecb45cc8693d941731 --- /dev/null +++ b/src/test/java/org/genesys/test/config/ApplicationConfig.java @@ -0,0 +1,256 @@ +package org.genesys.test.config; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.genesys.blocks.util.CurrentApplicationContext; +import org.genesys2.server.security.SecurityUtils; +import org.genesys2.spring.config.AuditConfig; +import org.genesys2.spring.config.CacheConfig; +import org.genesys2.spring.config.DatabaseConfig; +import org.genesys2.spring.config.FileRepositoryConfig; +import org.genesys2.spring.config.MailConfig; +import org.genesys2.spring.config.OAuth2ServerConfig; +import org.genesys2.spring.config.SameOriginCorsProcessor; +import org.genesys2.spring.config.SchedulerConfig; +import org.genesys2.spring.config.SecurityConfig; +import org.genesys2.spring.config.SwaggerConfig; +import org.genesys2.spring.config.TemplatingConfig; +import org.genesys2.spring.config.WebSecurityConfig; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.context.annotation.Import; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.core.annotation.Order; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.web.cors.CorsProcessor; +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.handler.AbstractHandlerMapping; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; + +public final class ApplicationConfig { + + /** + * This Spring context configuration is almost a copy of the server application. + * + * Excluding Hazelcast and Elasticsearch. + */ + @Configuration + @Import({ NoHazelcastConfig.class, SchedulerConfig.class, DatabaseConfig.class, TestElasticsearchConfig.class, TemplatingConfig.class, MailConfig.class, SecurityConfig.class, CacheConfig.class, + FileRepositoryConfig.class, AuditConfig.class }) + @ComponentScan(basePackages = { "org.genesys.catalog.service.impl", "org.genesys2.brapi.service", "org.genesys2.server.service.impl", "org.genesys2.server.service.worker" } ) + @EnableAspectJAutoProxy + public static class BaseConfig { + + @Bean + public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() { + final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); + propertyPlaceholderConfigurer.setIgnoreResourceNotFound(false); + propertyPlaceholderConfigurer.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); + propertyPlaceholderConfigurer.setFileEncoding("utf-8"); + + final List locations = new ArrayList<>(); + locations.add(new ClassPathResource("application.properties")); + locations.add(new ClassPathResource("junit.properties")); + propertyPlaceholderConfigurer.setLocations(locations.toArray(new Resource[] {})); + return propertyPlaceholderConfigurer; + } + + @Bean + public ResourceBundleMessageSource messageSource() { + final ResourceBundleMessageSource source = new ResourceBundleMessageSource(); + source.setBasename("content/language"); + source.setDefaultEncoding("UTF-8"); + source.setUseCodeAsDefaultMessage(true); + return source; + } + + /** + * localeURLFilter in web.xml: en es de fr fa ar ru zh pt + */ + @Bean + public static Set supportedLocales() { + final Set supportedLocales = new HashSet<>(); + supportedLocales.add("en"); + supportedLocales.add("es"); + supportedLocales.add("de"); + supportedLocales.add("fr"); + supportedLocales.add("fa"); + supportedLocales.add("ar"); + supportedLocales.add("ru"); + supportedLocales.add("zh"); + supportedLocales.add("pt"); + return supportedLocales; + } + + /** + * Current application context. + * + * @return the current application context + */ + @Bean + @Order(Integer.MIN_VALUE) + public CurrentApplicationContext currentApplicationContext() { + // This provides static access to current application context + return new CurrentApplicationContext(); + } + + @Bean + public SecurityUtils securityUtils() { + return new SecurityUtils(); + } + + @Bean + public ObjectMapper objectMapper() { + return new ObjectMapper(); + } + } + + @Configuration + @EnableAspectJAutoProxy + @EnableWebSecurity + @EnableWebMvc + @Import({ WebAppConfig.Config.class, OAuth2ServerConfig.class, WebSecurityConfig.class, SwaggerConfig.class }) + @ComponentScan(basePackages = { "org.genesys2.server.brapi", "org.genesys2.server.api.v0", "org.genesys2.server.api.admin.v0", "org.genesys2.server.api.v1", "org.genesys.catalog.api", "org.genesys.catalog.mvc", + "org.genesys.catalog.service.worker" }) + public static class WebAppConfig extends BaseConfig { + + /** + * Almost a copy of the WebConfiguration.class of the main app. + */ + @Configuration + public static class Config extends WebMvcConfigurerAdapter { + + @Value("${base.url}") + private String baseUrl; + + @Override + public void configurePathMatch(final PathMatchConfigurer configurer) { + configurer.setUseTrailingSlashMatch(true); + configurer.setUseSuffixPatternMatch(false); + configurer.setUseRegisteredSuffixPatternMatch(false); + } + + @Bean + public InternalResourceViewResolver jstlViewResolver() { + final InternalResourceViewResolver resolver = new InternalResourceViewResolver(); + resolver.setPrefix("/WEB-INF/jsp"); + resolver.setSuffix(".jsp"); + resolver.setExposeContextBeansAsAttributes(true); + resolver.setExposedContextBeanNames(new String[] { "jspHelper" }); + resolver.setRedirectHttp10Compatible(false); + resolver.setRequestContextAttribute("requestContext"); + resolver.setViewClass(JstlView.class); + return resolver; + } + + @Override + public void configureViewResolvers(final ViewResolverRegistry registry) { + registry.viewResolver(jstlViewResolver()); + } + + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(false); + } + + @Override + public void addCorsMappings(final CorsRegistry registry) { + registry.addMapping("/api/**") + // .allowedOrigins(uiOrigin) + .allowedMethods("PUT", "POST", "GET", "DELETE"); + // .allowedHeaders("header1", "header2", "header3") + // .exposedHeaders("header1", "header2") + // .allowCredentials(false).maxAge(3600); + + registry.addMapping("/html/**").allowCredentials(false).allowedMethods("GET", "OPTIONS", "HEAD").allowedOrigins(baseUrl).maxAge(3600); + } + + @Bean + public CorsProcessor corsProcessor() { + return new SameOriginCorsProcessor(); + } + + /** + * This bean post-processor sets our {@link #corsProcessor()} on all + * AbstractHandlerMapping beans + */ + @Bean + public BeanPostProcessor useCustomCorsProcessor() { + return new BeanPostProcessor() { + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof AbstractHandlerMapping) { + ((AbstractHandlerMapping) bean).setCorsProcessor(corsProcessor()); + } + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + }; + } + + public MappingJackson2HttpMessageConverter jacksonMessageConverter() { + final MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); + + final ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Hibernate4Module()); + // serialization + mapper.disable(SerializationFeature.EAGER_SERIALIZER_FETCH); + // deserialization + mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); + // // Never ignore stuff we don't understand + // mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + // ignore stuff we don't understand + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + // explicit json views: every fields needs to be annotated, therefore enabled + mapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION); + + messageConverter.setObjectMapper(mapper); + return messageConverter; + + } + + @Override + public void configureMessageConverters(final List> converters) { + // Here we add our custom-configured HttpMessageConverter + converters.add(jacksonMessageConverter()); + // Raw request body -- needed for uploading raw files + converters.add(new ByteArrayHttpMessageConverter()); + // HTTP string + converters.add(new StringHttpMessageConverter()); + super.configureMessageConverters(converters); + } + + } + } +} diff --git a/src/test/java/org/genesys/test/config/NoHazelcastConfig.java b/src/test/java/org/genesys/test/config/NoHazelcastConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..ab48e0edb3365f122622961fcf3b5da9618a45ca --- /dev/null +++ b/src/test/java/org/genesys/test/config/NoHazelcastConfig.java @@ -0,0 +1,96 @@ +/* + * 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.test.config; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.genesys2.server.service.worker.ElasticUpdater.ElasticNode; +import org.springframework.cache.CacheManager; +import org.springframework.cache.support.NoOpCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The Class NoHazelcastConfig. + */ +@Configuration +public class NoHazelcastConfig { + + /** + * Cache manager. + * + * @return the cache manager + */ + @Bean + public CacheManager cacheManager() { + return new NoOpCacheManager(); + } + + /** + * Account lockout map. + * + * @return the map + */ + @Bean + public Map accountLockoutMap() { + return new HashMap(); + } + + /** + * Elastic remove queue. + * + * @return the blocking queue + */ + @Bean + public BlockingQueue elasticRemoveQueue() { + return new ArrayBlockingQueue(100); + } + + /** + * Elastic update queue. + * + * @return the blocking queue + */ + @Bean + public BlockingQueue elasticUpdateQueue() { + return new ArrayBlockingQueue(100); + } + + /** + * Elasticsearch admin lock. + * + * @return the lock + */ + @Bean + public Lock elasticsearchAdminLock() { + return new ReentrantLock(true); + } + + /** + * Taxonomy update lock. + * + * @return the lock + */ + @Bean + public Lock taxonomyUpdateLock() { + return new ReentrantLock(true); + } +} diff --git a/src/test/java/org/genesys/test/config/TestElasticsearchConfig.java b/src/test/java/org/genesys/test/config/TestElasticsearchConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..c76c7cf1cc30b661d2b6e23ec14cdcb97d90e473 --- /dev/null +++ b/src/test/java/org/genesys/test/config/TestElasticsearchConfig.java @@ -0,0 +1,129 @@ +/* + * 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.test.config; + +import static org.elasticsearch.node.NodeBuilder.nodeBuilder; + +import java.io.IOException; + +import org.elasticsearch.client.Client; +import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.settings.ImmutableSettings; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.EntityMapper; +import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * ElasticsearchConfig for JUnit + */ +@Configuration +@EnableElasticsearchRepositories +public class TestElasticsearchConfig implements InitializingBean { + + /** The data path. */ + private String dataPath; + + /** The cluster name. */ + private String clusterName; + + /* (non-Javadoc) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ + @Override + public void afterPropertiesSet() throws Exception { + this.clusterName = "es-test-" + System.currentTimeMillis(); + this.dataPath = "target/test-es/" + System.currentTimeMillis(); + } + + /** + * Node client. + * + * @return the node client + */ + @Bean(destroyMethod = "close") + public NodeClient nodeClient() { + final ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder() + .put("http.enabled", String.valueOf(false)).put("path.home", this.dataPath); + + return (NodeClient) nodeBuilder().settings(settings).clusterName(this.clusterName).local(true).node().client(); + } + + /** + * Elasticsearch template. + * + * @param client the client + * @param entityMapper the entity mapper + * @return the elasticsearch template + */ + @Bean + public ElasticsearchTemplate elasticsearchTemplate(final Client client, final EntityMapper entityMapper) { + final ElasticsearchTemplate t = new ElasticsearchTemplate(client, entityMapper); + return t; + } + + /** + * Entity mapper. + * + * @return the entity mapper + */ + @Bean + public EntityMapper entityMapper() { + return new GenesysEntityMapper(); + } + + /** + * The Class GenesysEntityMapper. + */ + public class GenesysEntityMapper implements EntityMapper { + + /** The object mapper. */ + private final ObjectMapper objectMapper; + + /** + * Instantiates a new genesys entity mapper. + */ + public GenesysEntityMapper() { + objectMapper = new ObjectMapper(); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + objectMapper.setSerializationInclusion(Include.NON_EMPTY); + } + + /* (non-Javadoc) + * @see org.springframework.data.elasticsearch.core.EntityMapper#mapToString(java.lang.Object) + */ + @Override + public String mapToString(final Object object) throws IOException { + return objectMapper.writeValueAsString(object); + } + + /* (non-Javadoc) + * @see org.springframework.data.elasticsearch.core.EntityMapper#mapToObject(java.lang.String, java.lang.Class) + */ + @Override + public T mapToObject(final String source, final Class clazz) throws IOException { + return objectMapper.readValue(source, clazz); + } + } + +} diff --git a/src/test/java/org/genesys2/tests/resttests/CacheControllerTest.java b/src/test/java/org/genesys/test/server/api/v0/CacheControllerTest.java similarity index 78% rename from src/test/java/org/genesys2/tests/resttests/CacheControllerTest.java rename to src/test/java/org/genesys/test/server/api/v0/CacheControllerTest.java index 3256e5021480eca158d8077a69825683bb4b39df..bc6b5d846086a0510d88c1f0292f147728d03a9d 100644 --- a/src/test/java/org/genesys2/tests/resttests/CacheControllerTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/CacheControllerTest.java @@ -1,12 +1,12 @@ -package org.genesys2.tests.resttests; +package org.genesys.test.server.api.v0; import static org.hamcrest.Matchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - +import org.genesys.test.base.AbstractApiTest; +import org.genesys2.server.api.admin.v0.CacheController; +import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -17,10 +17,14 @@ import org.springframework.cache.annotation.EnableCaching; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + @EnableCaching -public class CacheControllerTest extends AbstractRestTest { +public class CacheControllerTest extends AbstractApiTest { private static final Logger LOG = LoggerFactory.getLogger(CacheControllerTest.class); @@ -29,21 +33,29 @@ public class CacheControllerTest extends AbstractRestTest { MockMvc mockMvc; + @Transactional @Before - public void setUp() { + @Override + public void beforeTest() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - + } + + @After + @Transactional + @Override + public void cleanup() throws Exception { + super.cleanup(); } @Test public void cacheStatsTest() throws Exception { LOG.info("Start test-method cacheStatsTest"); - mockMvc.perform(get("/api/v0/cache") + mockMvc.perform(get(CacheController.API_URL) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(jsonPath("$.cacheMaps", hasSize(greaterThan(0)))) + .andExpect(jsonPath("$.cacheMaps", hasSize(0))) .andExpect(jsonPath("$.cacheOther", hasSize(0))); LOG.info("Test cacheStatsTest passed."); @@ -58,7 +70,7 @@ public class CacheControllerTest extends AbstractRestTest { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(JSON_OK); - mockMvc.perform(post("/api/v0/cache/clearTilesCache") + mockMvc.perform(post(CacheController.API_URL + "/clearTilesCache") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) @@ -75,7 +87,7 @@ public class CacheControllerTest extends AbstractRestTest { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(JSON_OK); - mockMvc.perform(post("/api/v0/cache/clearCaches") + mockMvc.perform(post(CacheController.API_URL + "/clearCaches") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(jsonNode))); diff --git a/src/test/java/org/genesys2/tests/resttests/CropsControllerTest.java b/src/test/java/org/genesys/test/server/api/v0/CropsControllerTest.java similarity index 90% rename from src/test/java/org/genesys2/tests/resttests/CropsControllerTest.java rename to src/test/java/org/genesys/test/server/api/v0/CropsControllerTest.java index 2ad9c405adf0c00a7c40b50059a9525a52008c21..5019a568c3e693c5dd1d67c8a6d3cf312b1cc08f 100644 --- a/src/test/java/org/genesys2/tests/resttests/CropsControllerTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/CropsControllerTest.java @@ -1,29 +1,22 @@ -package org.genesys2.tests.resttests; - -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; -import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; -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; +package org.genesys.test.server.api.v0; + +import static org.hamcrest.Matchers.*; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.request.RequestDocumentation.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.util.ArrayList; import java.util.List; +import org.genesys.test.base.AbstractApiTest; +import org.genesys2.server.api.v0.CropsController; import org.genesys2.server.model.impl.Crop; import org.genesys2.server.model.impl.CropRule; +import org.genesys2.server.persistence.CropRepository; +import org.genesys2.server.persistence.CropRuleRepository; +import org.genesys2.server.service.CropService; import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -44,10 +37,9 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; @Transactional(transactionManager = "transactionManager") -public class CropsControllerTest extends AbstractRestTest { +public class CropsControllerTest extends AbstractApiTest { private static final Logger LOG = LoggerFactory.getLogger(CropsControllerTest.class); @@ -60,19 +52,29 @@ public class CropsControllerTest extends AbstractRestTest { MockMvc mockMvc; private static final ObjectMapper objectMapper; + @Autowired + private CropRepository cropRepository; + @Autowired + private CropRuleRepository cropRuleRepository; + @Autowired + private CropService cropService; + private Crop crop; private CropRule cropRule; + static { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); objectMapper.setSerializationInclusion(Include.NON_EMPTY); } + @Transactional @Before - public void setUp() { + @Override + public void beforeTest() throws Exception { + super.beforeTest(); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(this.restDocumentation).uris() .withScheme("https") .withHost("sandbox.genesys-pgr.org") @@ -83,9 +85,13 @@ public class CropsControllerTest extends AbstractRestTest { crop = cropRule.getCrop(); } + @Transactional @After - public void tearDown() { - cropRepository.delete(crop); + @Override + public void cleanup() throws Exception { + cropRuleRepository.deleteAll(); + cropRepository.deleteAll(); + super.cleanup(); } @Test @@ -109,16 +115,19 @@ public class CropsControllerTest extends AbstractRestTest { } @Test + @SuppressWarnings("unused") public void createCropTest() throws Exception { LOG.info("Start test-method createCropTest"); - mockMvc.perform(post("/api/v0/crops") + /*@formatter:off*/ + mockMvc.perform(post(CropsController.CONTROLLER_URL + "/save") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(objectMapper.writeValueAsString(new Object() { - public String shortName="rice"; + public String shortName="rice"; public String name="Rice"; public String description="Crop description in EN"; }))) + // .andDo(MockMvcResultHandlers.print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", is(notNullValue()))) @@ -151,6 +160,7 @@ public class CropsControllerTest extends AbstractRestTest { fieldWithPath("lastModifiedDate").ignored() ))); + /*@formatter:on*/ LOG.info("Test createCropTest passed"); } @@ -158,6 +168,7 @@ public class CropsControllerTest extends AbstractRestTest { public void getCropTest() throws Exception { LOG.info("Start test-method getCropTest"); + /*@formatter:off*/ mockMvc.perform(get("/api/v0/crops/{shortName}", crop.getShortName()) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) @@ -187,19 +198,18 @@ public class CropsControllerTest extends AbstractRestTest { fieldWithPath("lastModifiedBy").ignored(), fieldWithPath("lastModifiedDate").ignored() ))); - + /*@formatter:on*/ LOG.info("Test getCropTest passed"); } @Test public void deleteCropTest() throws Exception { - LOG.info("Start test-method deleteCropTest"); - createCropTest(); - + /*@formatter:off*/ mockMvc.perform(delete("/api/v0/crops/{shortName}", "rice") .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", is(nullValue()))) .andExpect(jsonPath("$.version", is(1))) @@ -210,14 +220,14 @@ public class CropsControllerTest extends AbstractRestTest { .andDo(document("crop-delete", pathParameters( parameterWithName("shortName").description("Crop short name or code (e.g. maize)") ))); - - LOG.info("Test deleteCropTest passed"); + /*@formatter:on*/ } @Test public void getCropDescriptorsTest() throws Exception { LOG.info("Start test-method getCropDescriptorsTest"); + /*@formatter:off*/ mockMvc.perform(get("/api/v0/crops/{shortName}/descriptors", crop.getShortName()) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) @@ -235,6 +245,7 @@ public class CropsControllerTest extends AbstractRestTest { parameterWithName("shortName").description("Crop short name or code (e.g. maize)") ))); + /*@formatter:on*/ LOG.info("Test getCropDescriptorsTest passed"); } @@ -242,6 +253,7 @@ public class CropsControllerTest extends AbstractRestTest { public void getCropRulesTest() throws Exception { LOG.info("Start test-method getCropRulesTest"); + /*@formatter:off*/ mockMvc.perform(get("/api/v0/crops/{shortName}/rules", crop.getShortName()) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) @@ -256,6 +268,7 @@ public class CropsControllerTest extends AbstractRestTest { parameterWithName("shortName").description("Crop short name or code (e.g. maize)") ))); + /*@formatter:on*/ LOG.info("Test getCropRulesTest passed"); } @@ -274,6 +287,7 @@ public class CropsControllerTest extends AbstractRestTest { cropRule.setSubtaxa("var. foobaria"); cropRules.add(cropRule); + /*@formatter:off*/ mockMvc.perform(put("/api/v0/crops/{shortName}/rules", crop.getShortName()) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(objectMapper.writeValueAsString(cropRules))) @@ -295,6 +309,7 @@ public class CropsControllerTest extends AbstractRestTest { fieldWithPath("[].subtaxa").optional().description("Accession is included in the crop when its subtaxa matches specified value.") ))); + /*@formatter:on*/ LOG.info("Test updateCropRulesTest passed"); } @@ -302,6 +317,7 @@ public class CropsControllerTest extends AbstractRestTest { public void getCropTaxaTest() throws Exception { LOG.info("Start test-method getCropTaxaTest"); + /*@formatter:off*/ mockMvc.perform(get("/api/v0/crops/{shortName}/taxa", crop.getShortName()) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) @@ -316,6 +332,7 @@ public class CropsControllerTest extends AbstractRestTest { .andExpect(jsonPath("$.totalPages", is(0))) .andExpect(jsonPath("$.size", is(50))); + /*@formatter:on*/ LOG.info("Test getCropTaxaTest passed"); } @@ -329,17 +346,18 @@ public class CropsControllerTest extends AbstractRestTest { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(JSON_OK); + /*@formatter:off*/ mockMvc.perform(post("/api/v0/crops/rebuild") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(content().string(objectMapper.writeValueAsString(jsonNode))); + /*@formatter:on*/ LOG.info("Test rebuildTest passed"); } @Test - @Transactional public void rebuildCropTest() throws Exception { LOG.info("Start test-method rebuildCropTest"); @@ -347,12 +365,13 @@ public class CropsControllerTest extends AbstractRestTest { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(JSON_OK); + /*@formatter:off*/ mockMvc.perform(post("/api/v0/crops/{shortName}/rebuild", crop.getShortName()) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(content().string(objectMapper.writeValueAsString(jsonNode))); - + /*@formatter:on*/ LOG.info("Test rebuildCropTest passed"); } } diff --git a/src/test/java/org/genesys2/tests/resttests/LookupControllerTest.java b/src/test/java/org/genesys/test/server/api/v0/LookupControllerTest.java similarity index 87% rename from src/test/java/org/genesys2/tests/resttests/LookupControllerTest.java rename to src/test/java/org/genesys/test/server/api/v0/LookupControllerTest.java index 21c655a89bdf18fb183284124f6db3fb08a9de37..fd559e94c5d9b33d89b5c980b1ed86409be722b4 100644 --- a/src/test/java/org/genesys2/tests/resttests/LookupControllerTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/LookupControllerTest.java @@ -1,16 +1,15 @@ -package org.genesys2.tests.resttests; +package org.genesys.test.server.api.v0; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.util.HashMap; import java.util.Map; -import com.fasterxml.jackson.databind.ObjectMapper; - import org.genesys.blocks.security.UserException; +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.model.impl.Country; -import org.genesys2.server.model.impl.User; +import org.genesys2.server.persistence.CountryRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -22,7 +21,9 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -public class LookupControllerTest extends AbstractRestTest { +import com.fasterxml.jackson.databind.ObjectMapper; + +public class LookupControllerTest extends AbstractApiTest { private static final Logger LOG = LoggerFactory.getLogger(LookupControllerTest.class); @@ -31,7 +32,9 @@ public class LookupControllerTest extends AbstractRestTest { MockMvc mockMvc; - User user; + @Autowired + private CountryRepository countryRepository; + @Before public void startUp() throws UserException { diff --git a/src/test/java/org/genesys2/tests/resttests/PermissionControllerTest.java b/src/test/java/org/genesys/test/server/api/v0/PermissionControllerTest.java similarity index 51% rename from src/test/java/org/genesys2/tests/resttests/PermissionControllerTest.java rename to src/test/java/org/genesys/test/server/api/v0/PermissionControllerTest.java index dd367530d2c38323d2223e8a7c1cc863afa1e292..a4e6012f0fcf0e7ffb28fe65c42ec1d2ab34dae6 100644 --- a/src/test/java/org/genesys2/tests/resttests/PermissionControllerTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/PermissionControllerTest.java @@ -1,38 +1,41 @@ -package org.genesys2.tests.resttests; +package org.genesys.test.server.api.v0; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.genesys.blocks.security.UserException; import org.genesys.blocks.security.model.BasicUser.AccountType; -import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException; +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.model.impl.FaoInstitute; import org.genesys2.server.model.impl.User; +import org.genesys2.server.persistence.FaoInstituteRepository; +import org.genesys2.server.persistence.FaoInstituteSettingRepository; +import org.genesys2.server.persistence.UserRepository; +import org.genesys2.server.service.InstituteService; +import org.genesys2.server.service.UserService; import org.genesys2.server.servlet.model.PermissionJson; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -// FIXME No permissions -@Ignore -public class PermissionControllerTest extends AbstractRestTest { +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PermissionControllerTest extends AbstractApiTest { private static final Logger LOG = LoggerFactory.getLogger(PermissionControllerTest.class); @@ -41,17 +44,33 @@ public class PermissionControllerTest extends AbstractRestTest { MockMvc mockMvc; - private User user = new User(); + @Autowired + private UserService userService; + @Autowired + private InstituteService instituteService; + @Autowired + private UserRepository userPersistence; + @Autowired + private FaoInstituteSettingRepository instituteSettingRepository; + @Autowired + private FaoInstituteRepository instituteRepository; + + private User user; private FaoInstitute faoInstitute; private List institutes = new ArrayList<>(); private PermissionJson permissionJson; private JsonNode JSON_OK; @Before - public void setUp() throws UserException, IOException, PasswordPolicyException { + @Override + public void beforeTest() throws Exception { + super.beforeTest(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - user = userService.createUser("salexandrbasov@gmail.com", "SYS_ADMIN", "Alexandr19011990", AccountType.LOCAL); + user = userService.createUser("salexandrbasov@gmail.com", "SYS_ADMIN", "This123#", AccountType.LOCAL); + assertThat(user.getUuid(), notNullValue()); + assertThat(user.getId(), greaterThan(0l)); faoInstitute = new FaoInstitute(); faoInstitute.setFullName("This is name of institute"); @@ -64,7 +83,9 @@ public class PermissionControllerTest extends AbstractRestTest { faoInstitute.setCode("Code"); institutes.add(faoInstitute); - instituteService.update(institutes); + institutes = instituteService.update(institutes); + faoInstitute = institutes.get(0); + assertThat(faoInstitute.getId(), greaterThan(0l)); ObjectMapper objectMapper = new ObjectMapper(); JSON_OK = objectMapper.readTree("{\"result\":true}"); @@ -82,10 +103,11 @@ public class PermissionControllerTest extends AbstractRestTest { } @After - public void tearDown() { + public void cleanup() throws Exception { userPersistence.deleteAll(); instituteSettingRepository.deleteAll(); instituteRepository.deleteAll(); + super.cleanup(); } @Test @@ -93,10 +115,17 @@ public class PermissionControllerTest extends AbstractRestTest { LOG.info("Start test-method addPermissionTest"); ObjectMapper objectMapper = new ObjectMapper(); + // LOG.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(permissionJson)); - mockMvc.perform(post("/api/v0/permission/add").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(permissionJson))).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(JSON_OK))); + /*@formatter:off*/ + mockMvc.perform(post("/api/v0/permission/add") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(permissionJson)) + ).andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().string(objectMapper.writeValueAsString(JSON_OK))); + /*@formatter:on*/ LOG.info("Test addPermissionTest is passed"); } @@ -106,8 +135,15 @@ public class PermissionControllerTest extends AbstractRestTest { ObjectMapper objectMapper = new ObjectMapper(); - mockMvc.perform(post("/api/v0/permission/update").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(permissionJson))).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(JSON_OK))); + /*@formatter:off*/ + mockMvc.perform(post("/api/v0/permission/update") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(permissionJson)) + ) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string(objectMapper.writeValueAsString(JSON_OK))); + /*@formatter:on*/ LOG.info("Test updatePermissionsTest is passed"); } @@ -116,13 +152,18 @@ public class PermissionControllerTest extends AbstractRestTest { public void acUserTest() throws Exception { LOG.info("Start test-method acUserTest"); - ObjectMapper objectMapper = new ObjectMapper(); - List userEmails = new ArrayList<>(); - userEmails.add(user.getEmail()); + Map userEmails = new HashMap<>(); + userEmails.put(user.getEmail(), user.getId()); - mockMvc.perform(get("/api/v0/permission/autocompleteuser").contentType(MediaType.APPLICATION_JSON).param("term", user.getEmail())).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(userEmails))); + /*@formatter:off*/ + mockMvc.perform(get("/api/v0/permission/autocompleteuser") + .contentType(MediaType.APPLICATION_JSON).param("term", user.getEmail()) + ).andExpect(status().isOk()) + // .andDo(MockMvcResultHandlers.print()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string(objectMapper.writeValueAsString(userEmails))); + /*@formatter:on*/ LOG.info("Test acUserTest is completed"); } } diff --git a/src/test/java/org/genesys2/tests/resttests/docs/ApiCropsTest.java b/src/test/java/org/genesys/test/server/api/v0/docs/ApiCropsTest.java similarity index 97% rename from src/test/java/org/genesys2/tests/resttests/docs/ApiCropsTest.java rename to src/test/java/org/genesys/test/server/api/v0/docs/ApiCropsTest.java index ef429538af05aba8146a3dd058c7f48f618fa3b3..3ebd403776aa42a58c768ce3f1a148dbf4f64ddb 100644 --- a/src/test/java/org/genesys2/tests/resttests/docs/ApiCropsTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/docs/ApiCropsTest.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package org.genesys2.tests.resttests.docs; +package org.genesys.test.server.api.v0.docs; -import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; @@ -27,15 +27,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.ArrayList; import java.util.List; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.model.impl.Crop; import org.genesys2.server.model.impl.CropRule; -import org.genesys2.tests.resttests.AbstractRestTest; +import org.genesys2.server.persistence.CropRepository; +import org.genesys2.server.service.CropService; import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -52,7 +48,12 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; -public class ApiCropsTest extends AbstractRestTest { +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ApiCropsTest extends AbstractApiTest { private static final Logger LOG = LoggerFactory.getLogger(ApiCropsTest.class); @@ -65,6 +66,11 @@ public class ApiCropsTest extends AbstractRestTest { MockMvc mockMvc; private static final ObjectMapper objectMapper; + @Autowired + private CropRepository cropRepository; + @Autowired + private CropService cropService; + private Crop crop; private CropRule cropRule; @@ -72,7 +78,6 @@ public class ApiCropsTest extends AbstractRestTest { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); objectMapper.setSerializationInclusion(Include.NON_EMPTY); } @@ -110,6 +115,7 @@ public class ApiCropsTest extends AbstractRestTest { } @Test + @SuppressWarnings("unused") public void createCropTest() throws Exception { LOG.info("Start test-method createCropTest"); diff --git a/src/test/java/org/genesys2/tests/resttests/docs/ApiImagesDocsTest.java b/src/test/java/org/genesys/test/server/api/v0/docs/ApiImagesDocsTest.java similarity index 55% rename from src/test/java/org/genesys2/tests/resttests/docs/ApiImagesDocsTest.java rename to src/test/java/org/genesys/test/server/api/v0/docs/ApiImagesDocsTest.java index 8550e569554a81ccf5119264b9288d7736448169..6e83d7ec0da31c87fdd2c6310a3045717006dd12 100644 --- a/src/test/java/org/genesys2/tests/resttests/docs/ApiImagesDocsTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/docs/ApiImagesDocsTest.java @@ -14,46 +14,36 @@ * limitations under the License. */ -package org.genesys2.tests.resttests.docs; +package org.genesys.test.server.api.v0.docs; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; -import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; -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.hamcrest.Matchers.*; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.request.RequestDocumentation.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - import org.elasticsearch.common.collect.Lists; import org.genesys.filerepository.model.RepositoryImage; import org.genesys.filerepository.persistence.ImageGalleryPersistence; +import org.genesys.filerepository.persistence.RepositoryFilePersistence; +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.model.genesys.Accession; import org.genesys2.server.model.genesys.AccessionId; import org.genesys2.server.model.genesys.Taxonomy2; import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.test.filerepository.TestImage; -import org.genesys2.tests.resttests.AbstractRestTest; +import org.genesys2.server.persistence.AccessionRepository; +import org.genesys2.server.persistence.FaoInstituteRepository; +import org.genesys2.server.persistence.Taxonomy2Repository; +import org.genesys2.server.service.GenesysService; +import org.genesys2.server.service.InstituteService; +import org.genesys2.server.service.TaxonomyService; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -68,7 +58,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; -public class ApiImagesDocsTest extends AbstractRestTest { +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ApiImagesDocsTest extends AbstractApiTest { private static final String ACCENUMB = "ACC001"; @@ -88,6 +82,20 @@ public class ApiImagesDocsTest extends AbstractRestTest { @Autowired private ImageGalleryPersistence imageGalleryPersistence; + @Autowired + private AccessionRepository accessionRepository; + @Autowired + private Taxonomy2Repository taxonomy2Repository; + @Autowired + private FaoInstituteRepository instituteRepository; + @Autowired + private RepositoryFilePersistence repositoryFileRepository; + @Autowired + private GenesysService genesysService; + @Autowired + private TaxonomyService taxonomyService; + @Autowired + private InstituteService instituteService; private FaoInstitute institute; @@ -95,7 +103,6 @@ public class ApiImagesDocsTest extends AbstractRestTest { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); objectMapper.setSerializationInclusion(Include.NON_EMPTY); } @@ -160,33 +167,44 @@ public class ApiImagesDocsTest extends AbstractRestTest { sb.append(ri.getUuid()); }).andExpect(jsonPath("$.id", greaterThan(0))).andExpect(jsonPath("$.path", is("/wiews/" + TEST_INSTCODE + "/acn/" + ACCENUMB))) .andExpect(jsonPath("$.originalFilename", is(image1.getOriginalFilename()))).andExpect(jsonPath("$.contentType", is("image/jpeg"))) + /*@formatter:off*/ + // .andDo(MockMvcResultHandlers.print()) .andDo(document("img-instgallery-put", - pathParameters(parameterWithName("instCode").description("Institute WIEWS code (e.g. NGA039)"), - parameterWithName("acceNumb").description("Existing ACCENUMB in the institute")), - requestParameters(parameterWithName("originalFilename").description("Filename of the image (e.g. IMG00121.jpg)")), - responseFields(fieldWithPath("uuid").description("UUID of the image in the Genesys repository"), - fieldWithPath("identifier").description("Unique identifier assigned to the image by Genesys"), - fieldWithPath("originalFilename").description("The original filename that you have provided"), - fieldWithPath("extension").description("Image extension derived from original filename (e.g. '.jpg')"), - fieldWithPath("contentType").description("The content type of the image (autodetected when possible)"), fieldWithPath("format").description("Image format"), - fieldWithPath("path").description("Location (directory) of the image in the Genesys repository"), - fieldWithPath("size").description("Image size in bytes"), - fieldWithPath("filename").description("The new generated filename of the image"), - fieldWithPath("metadataFilename").description("The generated filename for image metadata"), - fieldWithPath("url").description("The relative URL to the image in Genesys repository [path+filename]"), - fieldWithPath("sha1Sum").description("SHA1 hash of the image bytes"), fieldWithPath("md5Sum").description("MD5 hash of the image bytes"), - fieldWithPath("width").description("Image width in pixels (autodetected)"), fieldWithPath("height").description("Image height in pixels (autodetected)"), - fieldWithPath("orientation").description("LANDSCAPE or PORTRAIT orientation of the image (autodetected)"), - // Ignored stuff - fieldWithPath("_class").ignored(), - fieldWithPath("_permissions.*").ignored(), - fieldWithPath("id").ignored(), fieldWithPath("title").ignored(), fieldWithPath("subject").ignored(), fieldWithPath("description").ignored(), - fieldWithPath("creator").ignored(), fieldWithPath("created").ignored(), fieldWithPath("rightsHolder").ignored(), fieldWithPath("accessRights").ignored(), - fieldWithPath("license").ignored(), fieldWithPath("extent").ignored(), fieldWithPath("bibliographicCitation").ignored(), fieldWithPath("createdDate").ignored(), - fieldWithPath("lastModifiedDate").ignored(), fieldWithPath("lastModifiedBy").ignored(), fieldWithPath("originalUrl").ignored(), fieldWithPath("dateRetrieved").ignored(), fieldWithPath("dateSubmitted").ignored(), - fieldWithPath("modified").ignored(), fieldWithPath("version").ignored(), fieldWithPath("active").ignored(), fieldWithPath("createdBy").ignored(), - fieldWithPath("thumbnailPath").ignored(), fieldWithPath("storagePath").ignored(), fieldWithPath("storageFullPath").ignored()))); - + pathParameters( + parameterWithName("instCode").description("Institute WIEWS code (e.g. NGA039)"), + parameterWithName("acceNumb").description("Existing ACCENUMB in the institute") + ), + requestParameters( + parameterWithName("originalFilename").description("Filename of the image (e.g. IMG00121.jpg)") + ), + responseFields( + fieldWithPath("uuid").description("UUID of the image in the Genesys repository"), + fieldWithPath("identifier").description("Unique identifier assigned to the image by Genesys"), + fieldWithPath("originalFilename").description("The original filename that you have provided"), + fieldWithPath("extension").description("Image extension derived from original filename (e.g. '.jpg')"), + fieldWithPath("contentType").description("The content type of the image (autodetected when possible)"), + fieldWithPath("format").description("Image format"), + fieldWithPath("path").description("Location (directory) of the image in the Genesys repository"), + fieldWithPath("size").description("Image size in bytes"), + fieldWithPath("filename").description("The new generated filename of the image"), + fieldWithPath("metadataFilename").description("The generated filename for image metadata"), + fieldWithPath("url").description("The relative URL to the image in Genesys repository [path+filename]"), + fieldWithPath("sha1Sum").description("SHA1 hash of the image bytes"), + fieldWithPath("md5Sum").description("MD5 hash of the image bytes"), + fieldWithPath("width").description("Image width in pixels (autodetected)"), fieldWithPath("height").description("Image height in pixels (autodetected)"), + fieldWithPath("orientation").description("LANDSCAPE or PORTRAIT orientation of the image (autodetected)"), + // Ignored stuff + fieldWithPath("_class").ignored(), + fieldWithPath("_permissions.*").ignored(), + fieldWithPath("id").ignored(), fieldWithPath("title").ignored(), fieldWithPath("subject").ignored(), fieldWithPath("description").ignored(), + fieldWithPath("creator").ignored(), fieldWithPath("created").ignored(), fieldWithPath("rightsHolder").ignored(), fieldWithPath("accessRights").ignored(), + fieldWithPath("license").ignored(), fieldWithPath("extent").ignored(), fieldWithPath("bibliographicCitation").ignored(), fieldWithPath("createdDate").ignored(), + fieldWithPath("lastModifiedDate").ignored(), fieldWithPath("lastModifiedBy").ignored(), fieldWithPath("originalUrl").ignored(), fieldWithPath("dateRetrieved").ignored(), fieldWithPath("dateSubmitted").ignored(), + fieldWithPath("modified").ignored(), fieldWithPath("version").ignored(), fieldWithPath("active").ignored(), fieldWithPath("createdBy").ignored(), + fieldWithPath("thumbnailPath").ignored(), fieldWithPath("storagePath").ignored(), fieldWithPath("storageFullPath").ignored()) + ) + ); + /*@formatter:on*/ UUID uuid = UUID.fromString(sb.toString()); LOG.info("UUID={}", uuid); @@ -205,60 +223,67 @@ public class ApiImagesDocsTest extends AbstractRestTest { .content(objectMapper.writeValueAsString(ri))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(r -> { LOG.info("Image metadata put: {}", r.getResponse().getContentAsString()); }) + // .andDo(MockMvcResultHandlers.print()) .andDo(document("img-instgallery-metadata-put", - pathParameters(parameterWithName("instCode").description("Institute WIEWS code (e.g. NGA039)"), parameterWithName("acceNumb").description("Existing ACCENUMB in the institute"), - parameterWithName("uuid").description("UUID of the image in the gallery of this accession")), + /*@formatter:off*/ + pathParameters( + parameterWithName("instCode").description("Institute WIEWS code (e.g. NGA039)"), + parameterWithName("acceNumb").description("Existing ACCENUMB in the institute"), + parameterWithName("uuid").description("UUID of the image in the gallery of this accession") + ), requestFields( - fieldWithPath("title").description("Title is a property that refers to the name or names by which a resource is formally known"), - fieldWithPath("subject").description("The Subject described or pictured in the resource, accession number"), - fieldWithPath("description").description( - "Description of the content of a resource. The description is a potentially rich source of indexable terms and assist the users in their selection of an appropriate resource."), - fieldWithPath("creator").description("An entity primarily responsible for making the resource"), - fieldWithPath("created").description("A point or period of time when the resource was created by the Creator"), - fieldWithPath("rightsHolder").description("Person or an organization owning or managing rights over this resource"), - fieldWithPath("accessRights").description( - "Access rights provides information about restrictions to view, search or use a resource based on attributes of the resource itself or the category of user."), - fieldWithPath("license").description("Legal document giving official permission to do something with the resource. E.g. http://www.gnu.org/licenses/gpl.html"), - fieldWithPath("extent").description("Size (e.g. bytes, pages, inches, etc.) or duration (e.g. hours, minutes, days, etc.) of a resource"), - fieldWithPath("bibliographicCitation").description("Formal bibliographic citation for the resource"), - // ignored - fieldWithPath("active").ignored(), - fieldWithPath("size").ignored(), - fieldWithPath("width").ignored(), - fieldWithPath("height").ignored(), - fieldWithPath("_class").ignored(), - fieldWithPath("_permissions.*").ignored(), - fieldWithPath("id").ignored(), fieldWithPath("thumbnailPath").ignored(), fieldWithPath("url").ignored(), fieldWithPath("storageFullPath").ignored()), - responseFields(fieldWithPath("uuid").ignored(), fieldWithPath("originalFilename").description("The original filename that you have provided"), - fieldWithPath("extension").ignored(), fieldWithPath("contentType").ignored(), fieldWithPath("path").ignored(), - fieldWithPath("filename").ignored(), - fieldWithPath("metadataFilename").ignored(), - fieldWithPath("url").ignored(), fieldWithPath("sha1Sum").ignored(), fieldWithPath("md5Sum").ignored(), - // Updated stuff - fieldWithPath("width").description("Image width in pixels (autodetected)"), fieldWithPath("height").description("Image height in pixels (autodetected)"), - fieldWithPath("orientation").description("LANDSCAPE or PORTRAIT orientation of the image (autodetected)"), fieldWithPath("format").description("Image format"), - fieldWithPath("identifier").description("Permanent unique identifier of the resource. Commonly a Uniform Resource Locator (URL)."), - fieldWithPath("title").description("Title is a property that refers to the name or names by which a resource is formally known"), - fieldWithPath("subject").description("The Subject described or pictured in the resource, accession number"), - fieldWithPath("description").description( - "Description of the content of a resource. The description is a potentially rich source of indexable terms and assist the users in their selection of an appropriate resource."), - fieldWithPath("creator").description("An entity primarily responsible for making the resource"), - fieldWithPath("created").description("A point or period of time when the resource was created by the Creator"), - fieldWithPath("rightsHolder").description("Person or an organization owning or managing rights over this resource"), - fieldWithPath("accessRights").description( - "Access rights provides information about restrictions to view, search or use a resource based on attributes of the resource itself or the category of user."), - fieldWithPath("license").description("Legal document giving official permission to do something with the resource. E.g. http://www.gnu.org/licenses/gpl.html"), - fieldWithPath("extent").description("Size (e.g. bytes, pages, inches, etc.) or duration (e.g. hours, minutes, days, etc.) of a resource"), - fieldWithPath("bibliographicCitation").description("Formal bibliographic citation for the resource"), - fieldWithPath("size").description("Image size in bytes"), - fieldWithPath("width").description("Image width in pixels"), - fieldWithPath("height").description("Image height in pixels"), - // ignored - fieldWithPath("_class").ignored(), - fieldWithPath("_permissions.*").ignored(), - fieldWithPath("id").ignored(), fieldWithPath("version").ignored(), - fieldWithPath("createdDate").ignored(), fieldWithPath("createdBy").ignored(), fieldWithPath("lastModifiedDate").ignored(), fieldWithPath("lastModifiedBy").ignored(), fieldWithPath("originalUrl").ignored(), fieldWithPath("dateRetrieved").ignored(), - fieldWithPath("dateSubmitted").ignored(), fieldWithPath("modified").ignored(), fieldWithPath("active").ignored(), fieldWithPath("thumbnailPath").ignored(), fieldWithPath("url").ignored(), fieldWithPath("storageFullPath").ignored(), fieldWithPath("storagePath").ignored()))); + fieldWithPath("title").description("Title is a property that refers to the name or names by which a resource is formally known"), + fieldWithPath("subject").description("The Subject described or pictured in the resource, accession number"), + fieldWithPath("description").description("Description of the content of a resource. The description is a potentially rich source of indexable terms and assist the users in their selection of an appropriate resource."), + fieldWithPath("creator").description("An entity primarily responsible for making the resource"), + fieldWithPath("created").description("A point or period of time when the resource was created by the Creator"), + fieldWithPath("rightsHolder").description("Person or an organization owning or managing rights over this resource"), + fieldWithPath("accessRights").description("Access rights provides information about restrictions to view, search or use a resource based on attributes of the resource itself or the category of user."), + fieldWithPath("license").description("Legal document giving official permission to do something with the resource. E.g. http://www.gnu.org/licenses/gpl.html"), + fieldWithPath("extent").description("Size (e.g. bytes, pages, inches, etc.) or duration (e.g. hours, minutes, days, etc.) of a resource"), + fieldWithPath("bibliographicCitation").description("Formal bibliographic citation for the resource"), + // ignored + fieldWithPath("active").ignored(), + fieldWithPath("size").ignored(), + fieldWithPath("width").ignored(), + fieldWithPath("height").ignored(), + fieldWithPath("_class").ignored(), + fieldWithPath("_permissions.*").ignored(), + fieldWithPath("id").ignored(), fieldWithPath("thumbnailPath").ignored(), fieldWithPath("url").ignored(), fieldWithPath("storageFullPath").ignored() + ), + responseFields( + fieldWithPath("uuid").ignored(), + fieldWithPath("originalFilename").description("The original filename that you have provided"), + fieldWithPath("extension").ignored(), fieldWithPath("contentType").ignored(), fieldWithPath("path").ignored(), + fieldWithPath("filename").ignored(), + fieldWithPath("metadataFilename").ignored(), + fieldWithPath("url").ignored(), fieldWithPath("sha1Sum").ignored(), fieldWithPath("md5Sum").ignored(), + // Updated stuff + fieldWithPath("width").description("Image width in pixels (autodetected)"), fieldWithPath("height").description("Image height in pixels (autodetected)"), + fieldWithPath("orientation").description("LANDSCAPE or PORTRAIT orientation of the image (autodetected)"), fieldWithPath("format").description("Image format"), + fieldWithPath("identifier").description("Permanent unique identifier of the resource. Commonly a Uniform Resource Locator (URL)."), + fieldWithPath("title").description("Title is a property that refers to the name or names by which a resource is formally known"), + fieldWithPath("subject").description("The Subject described or pictured in the resource, accession number"), + fieldWithPath("description").description("Description of the content of a resource. The description is a potentially rich source of indexable terms and assist the users in their selection of an appropriate resource."), + fieldWithPath("creator").description("An entity primarily responsible for making the resource"), + fieldWithPath("created").description("A point or period of time when the resource was created by the Creator"), + fieldWithPath("rightsHolder").description("Person or an organization owning or managing rights over this resource"), + fieldWithPath("accessRights").description("Access rights provides information about restrictions to view, search or use a resource based on attributes of the resource itself or the category of user."), + fieldWithPath("license").description("Legal document giving official permission to do something with the resource. E.g. http://www.gnu.org/licenses/gpl.html"), + fieldWithPath("extent").description("Size (e.g. bytes, pages, inches, etc.) or duration (e.g. hours, minutes, days, etc.) of a resource"), + fieldWithPath("bibliographicCitation").description("Formal bibliographic citation for the resource"), + fieldWithPath("size").description("Image size in bytes"), + fieldWithPath("width").description("Image width in pixels"), + fieldWithPath("height").description("Image height in pixels"), + // ignored + fieldWithPath("_class").ignored(), + fieldWithPath("_permissions.*").ignored(), + fieldWithPath("id").ignored(), fieldWithPath("version").ignored(), + fieldWithPath("createdDate").ignored(), fieldWithPath("createdBy").ignored(), fieldWithPath("lastModifiedDate").ignored(), fieldWithPath("lastModifiedBy").ignored(), fieldWithPath("originalUrl").ignored(), fieldWithPath("dateRetrieved").ignored(), + fieldWithPath("dateSubmitted").ignored(), fieldWithPath("modified").ignored(), fieldWithPath("active").ignored(), fieldWithPath("thumbnailPath").ignored(), fieldWithPath("url").ignored(), fieldWithPath("storageFullPath").ignored(), fieldWithPath("storagePath").ignored()) + ) + ); + /*@formatter:on*/ mockMvc.perform(get("/api/v0/img/{instCode}/acn/{acceNumb}/{uuid}/_metadata", TEST_INSTCODE, ACCENUMB, uuid)).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(r -> { diff --git a/src/test/java/org/genesys2/tests/resttests/docs/ApiRequestsDocsTest.java b/src/test/java/org/genesys/test/server/api/v0/docs/ApiRequestsDocsTest.java similarity index 88% rename from src/test/java/org/genesys2/tests/resttests/docs/ApiRequestsDocsTest.java rename to src/test/java/org/genesys/test/server/api/v0/docs/ApiRequestsDocsTest.java index b1baeb60c7353918fa7424e3a12b9179d7d6aafb..80e818fd4e300901ec59ae5484f64a829624f23a 100644 --- a/src/test/java/org/genesys2/tests/resttests/docs/ApiRequestsDocsTest.java +++ b/src/test/java/org/genesys/test/server/api/v0/docs/ApiRequestsDocsTest.java @@ -1,8 +1,8 @@ -package org.genesys2.tests.resttests.docs; +package org.genesys.test.server.api.v0.docs; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.restdocs.request.RequestDocumentation.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -11,21 +11,18 @@ import java.util.ArrayList; import java.util.Collection; import java.util.UUID; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.model.genesys.MaterialRequest; import org.genesys2.server.model.genesys.MaterialSubRequest; import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.tests.resttests.AbstractRestTest; +import org.genesys2.server.persistence.FaoInstituteRepository; +import org.genesys2.server.persistence.MaterialRequestRepository; +import org.genesys2.server.persistence.MaterialSubRequestRepository; +import org.genesys2.server.service.InstituteService; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.restdocs.JUnitRestDocumentation; @@ -34,19 +31,30 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + @Transactional(transactionManager = "transactionManager") -public class ApiRequestsDocsTest extends AbstractRestTest { +public class ApiRequestsDocsTest extends AbstractApiTest { private static final String TEST_INSTCODE = "XXX001"; - private static final Logger LOG = LoggerFactory.getLogger(ApiRequestsDocsTest.class); - @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets"); @Autowired WebApplicationContext webApplicationContext; + @Autowired + private InstituteService instituteService; + @Autowired + private MaterialRequestRepository materialRequestRepository; + @Autowired + private MaterialSubRequestRepository materialSubRequestRepository; + @Autowired + private FaoInstituteRepository instituteRepository; + MockMvc mockMvc; private static final ObjectMapper objectMapper; @@ -58,7 +66,6 @@ public class ApiRequestsDocsTest extends AbstractRestTest { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); objectMapper.setSerializationInclusion(Include.NON_EMPTY); } @@ -99,7 +106,7 @@ public class ApiRequestsDocsTest extends AbstractRestTest { public void listRequestsTest() throws Exception { mockMvc.perform(get("/api/v0/requests/{instCode}", TEST_INSTCODE).param("page", "0")).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(r -> { - System.err.println(r.getResponse().getContentAsString()); + LOG.info(r.getResponse().getContentAsString()); }).andExpect(jsonPath("$.size", is(10))).andExpect(jsonPath("$.first", is(true))) .andDo(document("requests-inst-list", pathParameters(parameterWithName("instCode").description("Institute WIEWS code (e.g. NGA039)")), requestParameters(parameterWithName("page").description("Page to request from the server")), @@ -126,7 +133,7 @@ public class ApiRequestsDocsTest extends AbstractRestTest { public void getRequestInfoTest() throws Exception { mockMvc.perform(get("/api/v0/requests//{instCode}/r/{uuid}", TEST_INSTCODE, requestUuid.toString()).contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(r -> { - System.err.println(r.getResponse().getContentAsString()); + LOG.info(r.getResponse().getContentAsString()); }) // .andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$.uuid", is(requestUuid.toString()))).andExpect(jsonPath("$.instCode", is(TEST_INSTCODE))) diff --git a/src/test/java/org/genesys2/tests/resttests/docs/BrAPITest.java b/src/test/java/org/genesys/test/server/api/v0/docs/BrAPITest.java similarity index 93% rename from src/test/java/org/genesys2/tests/resttests/docs/BrAPITest.java rename to src/test/java/org/genesys/test/server/api/v0/docs/BrAPITest.java index 038143f3593844c54f02ae5d65685139856f3638..9f73886975bb71cf872f535395ae0fc4e7fd8a2b 100644 --- a/src/test/java/org/genesys2/tests/resttests/docs/BrAPITest.java +++ b/src/test/java/org/genesys/test/server/api/v0/docs/BrAPITest.java @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.genesys2.tests.resttests.docs; +package org.genesys.test.server.api.v0.docs; -import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.restdocs.request.RequestDocumentation.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -27,14 +27,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.ArrayList; import java.util.List; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.model.impl.Crop; import org.genesys2.server.model.impl.CropRule; -import org.genesys2.tests.resttests.AbstractRestTest; +import org.genesys2.server.persistence.CropRepository; +import org.genesys2.server.service.CropService; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -48,7 +45,11 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -public class BrAPITest extends AbstractRestTest { +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class BrAPITest extends AbstractApiTest { private static final Logger LOG = LoggerFactory.getLogger(BrAPITest.class); @@ -61,6 +62,12 @@ public class BrAPITest extends AbstractRestTest { MockMvc mockMvc; private static final ObjectMapper objectMapper; + + @Autowired + private CropRepository cropRepository; + @Autowired + private CropService cropService; + private Crop crop; private CropRule cropRule; @@ -68,7 +75,6 @@ public class BrAPITest extends AbstractRestTest { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); objectMapper.setSerializationInclusion(Include.NON_EMPTY); } @@ -99,7 +105,7 @@ public class BrAPITest extends AbstractRestTest { mockMvc.perform(get("/brapi/v1/crops?page=0&pageSize=2").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) // peek .andDo(r -> { - System.err.println(r.getResponse().getContentAsString()); + LOG.info(r.getResponse().getContentAsString()); }) // metadta .andExpect(jsonPath("$.metadata", is(notNullValue()))).andExpect(jsonPath("$.metadata.status", hasSize(0))).andExpect(jsonPath("$.metadata.datafiles", hasSize(0))) @@ -129,7 +135,7 @@ public class BrAPITest extends AbstractRestTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) // peek .andDo(r -> { - System.err.println(r.getResponse().getContentAsString()); + LOG.info(r.getResponse().getContentAsString()); }) // metadta .andExpect(jsonPath("$.metadata", is(notNullValue()))).andExpect(jsonPath("$.metadata.status", hasSize(0))).andExpect(jsonPath("$.metadata.datafiles", hasSize(0))) @@ -163,7 +169,7 @@ public class BrAPITest extends AbstractRestTest { // .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) // peek .andDo(r -> { - System.err.println(r.getResponse().getContentAsString()); + LOG.info(r.getResponse().getContentAsString()); }) // metadta .andExpect(jsonPath("$.metadata", is(notNullValue()))).andExpect(jsonPath("$.metadata.status", not(nullValue()))).andExpect(jsonPath("$.metadata.datafiles", hasSize(0))) diff --git a/src/test/java/org/genesys2/server/test/filerepository/TestImage.java b/src/test/java/org/genesys/test/server/api/v0/docs/TestImage.java similarity index 66% rename from src/test/java/org/genesys2/server/test/filerepository/TestImage.java rename to src/test/java/org/genesys/test/server/api/v0/docs/TestImage.java index 940f93dd5ee6bb09c6c249868ed6870363f1fd74..cdafc53fc94575645902b4f5e2983e1c848a1636 100644 --- a/src/test/java/org/genesys2/server/test/filerepository/TestImage.java +++ b/src/test/java/org/genesys/test/server/api/v0/docs/TestImage.java @@ -1,20 +1,4 @@ -/* - * Copyright 2016 Global Crop Diversity Trust, www.croptrust.org - * - * 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.genesys2.server.test.filerepository; +package org.genesys.test.server.api.v0.docs; import java.io.IOException; import java.io.InputStream; diff --git a/src/test/java/org/genesys2/server/servlet/controller/rest/api/v1/SubsetRestControllerTest.java b/src/test/java/org/genesys/test/server/api/v1/SubsetRestControllerTest.java similarity index 89% rename from src/test/java/org/genesys2/server/servlet/controller/rest/api/v1/SubsetRestControllerTest.java rename to src/test/java/org/genesys/test/server/api/v1/SubsetRestControllerTest.java index 5f8110ce3c193001903ca3a1b1b4fc821750fcb2..174dd25ae607b762820d7336f8fb2fbd28e6738b 100644 --- a/src/test/java/org/genesys2/server/servlet/controller/rest/api/v1/SubsetRestControllerTest.java +++ b/src/test/java/org/genesys/test/server/api/v1/SubsetRestControllerTest.java @@ -14,21 +14,14 @@ * limitations under the License. */ -package org.genesys2.server.servlet.controller.rest.api.v1; - -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +package org.genesys.test.server.api.v1; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -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 java.util.ArrayList; import java.util.List; @@ -36,7 +29,9 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; +import org.apache.commons.lang3.RandomUtils; import org.elasticsearch.common.collect.Lists; +import org.genesys.test.base.AbstractApiTest; import org.genesys2.server.api.v1.SubsetController; import org.genesys2.server.model.genesys.Accession; import org.genesys2.server.model.genesys.AccessionId; @@ -44,16 +39,17 @@ import org.genesys2.server.model.genesys.Taxonomy2; import org.genesys2.server.model.impl.FaoInstitute; import org.genesys2.server.model.impl.Subset; import org.genesys2.server.persistence.AccessionIdRepository; +import org.genesys2.server.persistence.AccessionRepository; +import org.genesys2.server.persistence.FaoInstituteRepository; import org.genesys2.server.persistence.SubsetRepository; +import org.genesys2.server.service.InstituteService; import org.genesys2.server.service.SubsetService; +import org.genesys2.server.service.TaxonomyService; import org.genesys2.server.service.filter.SubsetFilter; -import org.genesys2.tests.resttests.AbstractRestTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.restdocs.JUnitRestDocumentation; @@ -71,10 +67,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; * * @author Maxym Borodenko */ -@Transactional -public class SubsetRestControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(SubsetRestControllerTest.class); +public class SubsetRestControllerTest extends AbstractApiTest { private static final String TITLE = "Subset test title"; private static final String TITLE_2 = "Subset test title 2"; @@ -89,15 +82,20 @@ public class SubsetRestControllerTest extends AbstractRestTest { @Autowired private WebApplicationContext webApplicationContext; - @Autowired private SubsetService subsetService; - @Autowired private SubsetRepository subsetRepository; - @Autowired private AccessionIdRepository accessionIdRepository; + @Autowired + private FaoInstituteRepository instituteRepository; + @Autowired + private InstituteService instituteService; + @Autowired + private AccessionRepository accessionRepository; + @Autowired + private TaxonomyService taxonomyService; MockMvc mockMvc; @@ -115,14 +113,25 @@ public class SubsetRestControllerTest extends AbstractRestTest { } @After - public void cleanup() { + @Override + @Transactional + public void cleanup() throws Exception { + for (Subset subset : subsetRepository.findAll()) { + subset.setAccessionIds(new ArrayList<>()); + subsetRepository.save(subset); + } subsetRepository.deleteAll(); + accessionRepository.deleteAll(); accessionIdRepository.deleteAll(); instituteRepository.deleteAll(); + super.cleanup(); } @Before - public void setUp() { + @Override + @Transactional + public void beforeTest() throws Exception { + super.beforeTest(); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(documentationConfiguration(this.restDocumentation).uris().withScheme("https").withHost( "sandbox.genesys-pgr.org").withPort(443)).build(); institute = new FaoInstitute(); @@ -298,8 +307,8 @@ public class SubsetRestControllerTest extends AbstractRestTest { Accession a = new Accession(); a.setAccessionId(new AccessionId()); a.setInstitute(institute); - a.setAccessionNumber("ACC"+System.currentTimeMillis()); - Taxonomy2 taxon=new Taxonomy2(); + a.setAccessionNumber("ACC" + System.currentTimeMillis() + "-" + RandomUtils.nextLong(0, 100)); + Taxonomy2 taxon = new Taxonomy2(); taxon.setGenus("Hordeum"); a.setTaxonomy(taxonomyService.ensureTaxonomy(taxon)); return a; diff --git a/src/test/java/org/genesys/test/server/services/AbstractServicesTest.java b/src/test/java/org/genesys/test/server/services/AbstractServicesTest.java new file mode 100644 index 0000000000000000000000000000000000000000..074492f9081ecea44d761a1dacb3dd6229146344 --- /dev/null +++ b/src/test/java/org/genesys/test/server/services/AbstractServicesTest.java @@ -0,0 +1,114 @@ +/** + * Copyright 2015 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.test.server.services; + +import org.genesys.blocks.persistence.ClassPKRepository; +import org.genesys.test.base.AbstractServiceTest; +import org.genesys2.server.persistence.ActivityPostRepository; +import org.genesys2.server.persistence.ArticleRepository; +import org.genesys2.server.persistence.CropRepository; +import org.genesys2.server.persistence.CropRuleRepository; +import org.genesys2.server.persistence.CropTaxonomyRepository; +import org.genesys2.server.persistence.Taxonomy2Repository; +import org.genesys2.server.persistence.TeamRepository; +import org.genesys2.server.persistence.UserRepository; +import org.genesys2.server.persistence.VerificationTokenRepository; +import org.genesys2.server.persistence.dataset.DSDescriptorRepository; +import org.genesys2.server.service.CropService; +import org.genesys2.server.service.DescriptorService; +import org.genesys2.server.service.EMailVerificationService; +import org.genesys2.server.service.GenesysFilterService; +import org.genesys2.server.service.HtmlSanitizer; +import org.genesys2.server.service.InstituteService; +import org.genesys2.server.service.MappingService; +import org.genesys2.server.service.TaxonomyService; +import org.genesys2.server.service.TeamService; +import org.genesys2.server.service.TokenVerificationService; +import org.genesys2.server.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; + + +public abstract class AbstractServicesTest extends AbstractServiceTest { + + @Autowired + public UserRepository userPersistence; + + @Autowired + public ActivityPostRepository postRepository; + + @Autowired + public ClassPKRepository classPkRepository; + + @Autowired + public DescriptorService descriptorService; + + @Autowired + public DSDescriptorRepository dSDescriptorRepository; + + @Autowired + public VerificationTokenRepository verificationTokenRepository; + + @Autowired + public EMailVerificationService emailVerificationService; + + @Autowired + public ArticleRepository articleRepository; + + @Autowired + public HtmlSanitizer htmlSanitizer; + + @Autowired + public TaxonomyService taxonomyService; + + @Autowired + public TokenVerificationService tokenVerificationService; + + @Autowired + public VerificationTokenRepository tokenRepository; + + @Autowired + public InstituteService instituteService; + + @Autowired + public TeamRepository teamRepository; + + @Autowired + public TeamService teamService; + + @Autowired + public UserService userService; + + @Autowired + public CropService cropService; + + @Autowired + public CropRepository cropRepository; + + @Autowired + public CropRuleRepository cropRuleRepository; + + @Autowired + public CropTaxonomyRepository cropTaxonomyRepository; + + @Autowired + public Taxonomy2Repository taxonomy2Repository; + + @Autowired + public GenesysFilterService genesysFilterService; + + @Autowired + public MappingService mappingService; +} diff --git a/src/test/java/org/genesys/test/server/services/AccessionCounterTest.java b/src/test/java/org/genesys/test/server/services/AccessionCounterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..566b8ea4a7c61b8b7f7b65bc003c692eb2f60ed8 --- /dev/null +++ b/src/test/java/org/genesys/test/server/services/AccessionCounterTest.java @@ -0,0 +1,33 @@ +package org.genesys.test.server.services; + +import org.apache.commons.lang3.RandomUtils; +import org.genesys.test.base.AbstractServiceTest; +import org.genesys2.server.model.impl.FaoInstitute; +import org.genesys2.server.service.worker.AccessionCounter; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +@Ignore +public class AccessionCounterTest extends AbstractServiceTest { + + @Autowired + private AccessionCounter accessionCounter; + + @Test + public void test1() throws InterruptedException { + FaoInstitute inst = new FaoInstitute(); + inst.setCode("bbb001"); + FaoInstitute inst2 = new FaoInstitute(); + inst2.setCode("AAA001"); + for (int i=0; i<10; i++) { + if (RandomUtils.nextBoolean()) { + accessionCounter.recountInstitute(inst); + } else { + accessionCounter.recountInstitute(inst2); + } + Thread.sleep(RandomUtils.nextLong(2000, 5000)); + } + Thread.sleep(11000); + } +} diff --git a/src/test/java/org/genesys2/tests/unit/AuthUserDetailsServiceTest.java b/src/test/java/org/genesys/test/server/services/AuthUserDetailsServiceTest.java similarity index 82% rename from src/test/java/org/genesys2/tests/unit/AuthUserDetailsServiceTest.java rename to src/test/java/org/genesys/test/server/services/AuthUserDetailsServiceTest.java index 9af99aeec6af86fd9d3df06c13262d6876d53cc7..25d06779a3c2d00905bedbad6d6762aa22a2bb67 100644 --- a/src/test/java/org/genesys2/tests/unit/AuthUserDetailsServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/AuthUserDetailsServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import static org.junit.Assert.assertTrue; @@ -21,26 +21,24 @@ import org.genesys.blocks.security.UserException; import org.genesys.blocks.security.model.BasicUser.AccountType; import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException; import org.genesys2.server.model.impl.User; -import org.junit.Ignore; +import org.genesys2.server.service.UserService; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class AuthUserDetailsServiceTest extends AbstractServicesTest { - private final Logger LOG = LoggerFactory.getLogger(AuthUserDetailsServiceTest.class); - - // FIXME Transactional? - @Ignore + @Autowired + private UserService userService; + @Test public void loadUserByUsernameTest() throws PasswordPolicyException { LOG.info("Start test-method loadUserByUsernameTest"); try { User user = userService.createUser("email@mail.com", "UserName", "User1Password!", AccountType.LOCAL); - UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); + UserDetails userDetails = userService.loadUserByUsername(user.getEmail()); assertTrue(userDetails != null); assertTrue(userDetails.getPassword().equals(user.getPassword())); userService.deleteUser(user); @@ -56,7 +54,7 @@ public class AuthUserDetailsServiceTest extends AbstractServicesTest { public void loadUserByUsernameTestUserNotFound() { LOG.info("Start test-method loadUserByUsernameTestUserNotFound"); - assertTrue(null == userDetailsService.loadUserByUsername("WrongMail")); + assertTrue(null == userService.loadUserByUsername("WrongMail")); LOG.info("Test loadUserByUsernameTestUserNotFound passed!"); } diff --git a/src/test/java/org/genesys2/tests/unit/ClassPKTest.java b/src/test/java/org/genesys/test/server/services/ClassPKTest.java similarity index 87% rename from src/test/java/org/genesys2/tests/unit/ClassPKTest.java rename to src/test/java/org/genesys/test/server/services/ClassPKTest.java index e1c62d2ae6eb89076634dbf1b8301d6c8e7a8c10..38bf61f304d4b9f1e1524ef1b714c8b673f925ad 100644 --- a/src/test/java/org/genesys2/tests/unit/ClassPKTest.java +++ b/src/test/java/org/genesys/test/server/services/ClassPKTest.java @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import org.genesys.blocks.model.ClassPK; import org.genesys2.server.service.ContentService; import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,8 +31,9 @@ public class ClassPKTest extends AbstractServicesTest { @Autowired public ContentService contentService; - @After - public void teardown() { + @Before + @Override + public void cleanup() { // delete activity post classPkRepository.deleteAll(); } @@ -41,7 +43,7 @@ public class ClassPKTest extends AbstractServicesTest { ClassPK classPk1 = contentService.ensureClassPK(ClassPKTest.Test1.class); LOG.info("{} = {}", classPk1.getShortName(), classPk1.getClassname()); - ClassPK classPk2 = contentService.ensureClassPK(org.genesys2.tests.unit.Test1.class); + ClassPK classPk2 = contentService.ensureClassPK(org.genesys.test.server.services.Test1.class); LOG.info("{} = {}", classPk2.getShortName(), classPk2.getClassname()); } diff --git a/src/test/java/org/genesys2/tests/unit/ContentServiceTest.java b/src/test/java/org/genesys/test/server/services/ContentServiceTest.java similarity index 89% rename from src/test/java/org/genesys2/tests/unit/ContentServiceTest.java rename to src/test/java/org/genesys/test/server/services/ContentServiceTest.java index 6b2a3719756877001a7e2280579c00c2e9558328..e932add5dbfa9ea45cc6205805d5e4b813559608 100644 --- a/src/test/java/org/genesys2/tests/unit/ContentServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/ContentServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -38,6 +38,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; +import org.springframework.transaction.annotation.Transactional; public class ContentServiceTest extends AbstractServicesTest { @@ -46,8 +47,13 @@ public class ContentServiceTest extends AbstractServicesTest { public ContentService contentService; private Article testArticle = null; + @Transactional @Before - public void setUp() throws CRMException { + @Override + public void beforeTest() throws Exception { + articleRepository.deleteAll(); + super.beforeTest(); + // create activity post for test contentService.createActivityPost("title of activity post", "body of activity post"); @@ -55,13 +61,13 @@ public class ContentServiceTest extends AbstractServicesTest { testArticle = contentService.createGlobalArticle(ContentService.SMTP_EMAIL_VERIFICATION, contentService.getDefaultLocale(), "title of article", "

body of article

", null, false); } + @Transactional @After - public void teardown() { - // delete activity post + @Override + public void cleanup() throws Exception { postRepository.deleteAll(); - - // delete articles articleRepository.deleteAll(); + super.cleanup(); } @Test @@ -145,13 +151,11 @@ public class ContentServiceTest extends AbstractServicesTest { public void updateArticleTest() { LOG.info("Start test-method updateArticleTest"); - contentService.updateArticle(testArticle.getId(), "new slug for update test", "title for update test", "

Body for update testBody for update test

", null); - assertThat("Article body not updated", testArticle.getBody(), equalTo(afterUpdateArticle.getBody())); - assertThat("Article title not updated", testArticle.getTitle(), equalTo(afterUpdateArticle.getTitle())); - assertThat("Article slug not updated", testArticle.getSlug(), equalTo(afterUpdateArticle.getSlug())); + assertThat("Article body not updated", afterUpdateArticle.getBody(), equalTo("

Body for update test

")); + assertThat("Article title not updated", afterUpdateArticle.getTitle(), equalTo("title for update test")); + assertThat("Article slug not updated", afterUpdateArticle.getSlug(), equalTo("new-slug-for-test")); LOG.info("Test updateArticleTest is passed!"); } @@ -182,16 +186,16 @@ public class ContentServiceTest extends AbstractServicesTest { String title = "Update Global Article Title"; String body = "

Update Global Article Body

"; - Article globalArticle = contentService.createGlobalArticle(ContentService.SMTP_EMAIL_VERIFICATION, locale, title, body, null, false); + Article globalArticle = contentService.createGlobalArticle("some-global-article", locale, title, body, null, false); - assertThat("Articles list size mismatch", contentService.listArticles(new PageRequest(0, 6)).getContent().size(), is(1)); + assertThat("Articles list size mismatch", contentService.listArticles(new PageRequest(0, 6)).getContent().size(), is(2)); assertThat("Article body not updated", globalArticle.getBody(), equalTo("

Update Global Article Body

")); assertThat("Article title must be updated", globalArticle.getTitle(), equalTo("Update Global Article Title")); title="The title"; body = "

Updated body

"; String summary="Summary"; - Article updatedArticle = contentService.updateGlobalArticle(ContentService.SMTP_EMAIL_VERIFICATION, locale, title, body, summary); + Article updatedArticle = contentService.updateGlobalArticle("some-global-article", locale, title, body, summary); assertThat(updatedArticle.getId(), is(globalArticle.getId())); assertThat(updatedArticle.getTitle(), is(title)); assertThat(updatedArticle.getBody(), is(body)); diff --git a/src/test/java/org/genesys2/tests/unit/CropServiceTest.java b/src/test/java/org/genesys/test/server/services/CropServiceTest.java similarity index 99% rename from src/test/java/org/genesys2/tests/unit/CropServiceTest.java rename to src/test/java/org/genesys/test/server/services/CropServiceTest.java index 216f94c720490836ea9b96072195ad1db3ca8a20..7a120c9238740e3659b25f2593be63d593478819 100644 --- a/src/test/java/org/genesys2/tests/unit/CropServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/CropServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import static org.junit.Assert.*; diff --git a/src/test/java/org/genesys2/tests/unit/DS2DescriptorServiceTest.java b/src/test/java/org/genesys/test/server/services/DS2DescriptorServiceTest.java similarity index 98% rename from src/test/java/org/genesys2/tests/unit/DS2DescriptorServiceTest.java rename to src/test/java/org/genesys/test/server/services/DS2DescriptorServiceTest.java index 5e531629ebbfce943071095ec99033c30e86be89..eabc1e7a1430300fd6760ea9cde3c7320b1af195 100644 --- a/src/test/java/org/genesys2/tests/unit/DS2DescriptorServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/DS2DescriptorServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import static org.junit.Assert.*; diff --git a/src/test/java/org/genesys2/tests/unit/EmailServiceTest.java b/src/test/java/org/genesys/test/server/services/EmailServiceTest.java similarity index 84% rename from src/test/java/org/genesys2/tests/unit/EmailServiceTest.java rename to src/test/java/org/genesys/test/server/services/EmailServiceTest.java index 2ae6ba024191a3d1dfe14456a42ca1844ea818e9..e422d8dbac08b50b322029c1924b96717c5156d6 100644 --- a/src/test/java/org/genesys2/tests/unit/EmailServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/EmailServiceTest.java @@ -13,19 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; +import org.genesys2.server.service.EMailService; import org.junit.After; +import org.junit.Ignore; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessagePreparator; +@Ignore +// FIXME public class EmailServiceTest extends AbstractServicesTest { private final Logger LOG = LoggerFactory.getLogger(EmailServiceTest.class); @@ -36,6 +42,10 @@ public class EmailServiceTest extends AbstractServicesTest { @Value("${mail.requests.to}") String emailTo; + public JavaMailSender mailSender = Mockito.mock(JavaMailSenderImpl.class); + + public EMailService eMailService = Mockito.mock(EMailService.class); + @After public void teardown() { Mockito.reset(mailSender); diff --git a/src/test/java/org/genesys2/tests/unit/EmailVerificationServiceTest.java b/src/test/java/org/genesys/test/server/services/EmailVerificationServiceTest.java similarity index 92% rename from src/test/java/org/genesys2/tests/unit/EmailVerificationServiceTest.java rename to src/test/java/org/genesys/test/server/services/EmailVerificationServiceTest.java index d5c48309f91ec6ec7ba0ad29f6da5da51da5ab1b..1f996cb2a309fee7a2c3c96703c7cbcbc47d7427 100644 --- a/src/test/java/org/genesys2/tests/unit/EmailVerificationServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/EmailVerificationServiceTest.java @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.isA; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.isA; import java.util.ArrayList; import java.util.List; @@ -28,8 +27,8 @@ import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyExceptio import org.genesys2.server.model.UserRole; import org.genesys2.server.model.impl.User; import org.genesys2.server.model.impl.VerificationToken; -import org.genesys2.server.service.CRMException; import org.genesys2.server.service.ContentService; +import org.genesys2.server.service.EMailService; import org.genesys2.server.service.TokenVerificationService; import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException; import org.genesys2.server.service.TokenVerificationService.TokenExpiredException; @@ -43,12 +42,16 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; +@Ignore +// FIXME public class EmailVerificationServiceTest extends AbstractServicesTest { private final Logger LOG = LoggerFactory.getLogger(EmailVerificationServiceTest.class); @@ -60,8 +63,12 @@ public class EmailVerificationServiceTest extends AbstractServicesTest { @Autowired public ContentService contentService; + public JavaMailSender mailSender = Mockito.mock(JavaMailSenderImpl.class); + + public EMailService eMailService = Mockito.mock(EMailService.class); + @Before - public void setUp() throws PasswordPolicyException, CRMException { + public void beforeTest() throws Exception { LOG.info("set up"); try { @@ -74,16 +81,16 @@ public class EmailVerificationServiceTest extends AbstractServicesTest { } catch (UserException e) { e.printStackTrace(); } - LOG.info("finish set up"); + super.beforeTest(); } @After - public void teardown() { + public void cleanup() throws Exception { for (User user : userService.listUsers(new PageRequest(0, 10)).getContent()) { userService.deleteUser(user); } articleRepository.deleteAll(); - Mockito.reset(mailSender); + super.cleanup(); } private void doAuthentication(User user) { diff --git a/src/test/java/org/genesys2/tests/unit/MappingServiceTest.java b/src/test/java/org/genesys/test/server/services/MappingServiceTest.java similarity index 96% rename from src/test/java/org/genesys2/tests/unit/MappingServiceTest.java rename to src/test/java/org/genesys/test/server/services/MappingServiceTest.java index 9de065ddfe14d55e2f90db1d5d8cc2393fa43a2c..8a575e812346819967e6d64fc5ce7c072b3ea810 100644 --- a/src/test/java/org/genesys2/tests/unit/MappingServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/MappingServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import org.junit.Test; import org.slf4j.Logger; diff --git a/src/test/java/org/genesys2/tests/unit/OWASPSanitaizerTest.java b/src/test/java/org/genesys/test/server/services/OWASPSanitizerTest.java similarity index 86% rename from src/test/java/org/genesys2/tests/unit/OWASPSanitaizerTest.java rename to src/test/java/org/genesys/test/server/services/OWASPSanitizerTest.java index 87fee0b3999716fdf0b89b7fcddd64c3b4dee3ec..c2b00e0b1ccd992861c0b8f63220b7879edf6323 100644 --- a/src/test/java/org/genesys2/tests/unit/OWASPSanitaizerTest.java +++ b/src/test/java/org/genesys/test/server/services/OWASPSanitizerTest.java @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; import org.junit.Test; -public class OWASPSanitaizerTest extends AbstractServicesTest { +public class OWASPSanitizerTest extends AbstractServicesTest { @Test public void sanitizeTest() { diff --git a/src/test/java/org/genesys2/tests/unit/TaxonomyServiceTest.java b/src/test/java/org/genesys/test/server/services/TaxonomyServiceTest.java similarity index 96% rename from src/test/java/org/genesys2/tests/unit/TaxonomyServiceTest.java rename to src/test/java/org/genesys/test/server/services/TaxonomyServiceTest.java index 3f00f5d72a2d79bc4b70fdd57f376f0a3bbe9963..3d78752ed230237087aa391cfd35cb83c12f357f 100644 --- a/src/test/java/org/genesys2/tests/unit/TaxonomyServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/TaxonomyServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import org.junit.Test; import org.slf4j.Logger; diff --git a/src/test/java/org/genesys2/tests/unit/TeamServiceTest.java b/src/test/java/org/genesys/test/server/services/TeamServiceTest.java similarity index 99% rename from src/test/java/org/genesys2/tests/unit/TeamServiceTest.java rename to src/test/java/org/genesys/test/server/services/TeamServiceTest.java index 8cd079398db75aa3b23979856b774ebe73c9b76a..bad21d68e842606fbe1e6712fe09f48a77fcbb3b 100644 --- a/src/test/java/org/genesys2/tests/unit/TeamServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/TeamServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import static org.junit.Assert.*; diff --git a/src/test/java/org/genesys/test/server/services/Test1.java b/src/test/java/org/genesys/test/server/services/Test1.java new file mode 100644 index 0000000000000000000000000000000000000000..0e14154a94caa554bfc603b7ada2a31c753205cd --- /dev/null +++ b/src/test/java/org/genesys/test/server/services/Test1.java @@ -0,0 +1,5 @@ +package org.genesys.test.server.services; + +public class Test1 { + +} diff --git a/src/test/java/org/genesys2/tests/unit/TokenVerificationServiceTest.java b/src/test/java/org/genesys/test/server/services/TokenVerificationServiceTest.java similarity index 98% rename from src/test/java/org/genesys2/tests/unit/TokenVerificationServiceTest.java rename to src/test/java/org/genesys/test/server/services/TokenVerificationServiceTest.java index a3fbb59325471303e78ec37a5493f473509692a2..9e250ab00553275a2c0a83039aff63e80bb436f0 100644 --- a/src/test/java/org/genesys2/tests/unit/TokenVerificationServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/TokenVerificationServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; import static org.junit.Assert.*; diff --git a/src/test/java/org/genesys2/tests/unit/UserServiceTest.java b/src/test/java/org/genesys/test/server/services/UserServiceTest.java similarity index 65% rename from src/test/java/org/genesys2/tests/unit/UserServiceTest.java rename to src/test/java/org/genesys/test/server/services/UserServiceTest.java index f4c21febe235ab8658f4ce8e221eaba4a4f9c238..d00302a42c06197007bd7c860c5f02212bee4aa9 100644 --- a/src/test/java/org/genesys2/tests/unit/UserServiceTest.java +++ b/src/test/java/org/genesys/test/server/services/UserServiceTest.java @@ -13,17 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ -package org.genesys2.tests.unit; +package org.genesys.test.server.services; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; import java.util.List; import java.util.Set; @@ -31,80 +25,83 @@ import java.util.UUID; import org.elasticsearch.common.collect.Sets; import org.genesys.blocks.security.NoUserFoundException; -import org.genesys.blocks.security.NotUniqueUserException; import org.genesys.blocks.security.UserException; import org.genesys.blocks.security.model.BasicUser.AccountType; import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException; import org.genesys2.server.model.UserRole; import org.genesys2.server.model.impl.User; import org.genesys2.server.model.wrapper.UserWrapper; +import org.genesys2.server.persistence.UserRepository; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; -// FIXME Transactional? -//@Ignore public class UserServiceTest extends AbstractServicesTest { private static final String SYSTEM_PASSWORD = "THIS-IS-NOT-A-PASSWORD"; - private String email; + private final String initialPassword = "PassW03d!"; + private final String email = "test@example.com"; + private final String fullName = "Alechandro"; - private String initialPassword; + private User user; - private String fullName; + @Autowired + private PasswordEncoder passwordEncoder; - private User user; + @Autowired + private UserRepository userRepository; @Before - public void setUp() throws NotUniqueUserException, PasswordPolicyException, UserException { - email = "test@example.com"; - initialPassword = "Alexandr19011990!"; - fullName = "Alechandro"; + @Override + public void beforeTest() throws Exception { + super.beforeTest(); user = userService.createUser(email, fullName, initialPassword, AccountType.LOCAL); assertEquals(user.getAccountType(), AccountType.LOCAL); + assertThat(passwordEncoder.matches(initialPassword, user.getPassword()), is(true)); } @After - public void teardown() { - if (userService.exists(email)) { - User forRemoveUser = userService.getUserByEmail(email); - userService.deleteUser(forRemoveUser); - } + @Override + public void cleanup() throws Exception { + userRepository.deleteAll(); + super.cleanup(); } @Test public void listAvailableRolesTest() { - assertTrue(userService.listAvailableRoles().size() == UserRole.values().length); + assertThat(userService.listAvailableRoles().size(), is(UserRole.values().length)); } @Test public void getUserdetailsTest() throws PasswordPolicyException { User userDetails = (User) userService.getUserDetails(user); - assertTrue(userDetails != null); - assertTrue(userDetails == user); + assertThat(userDetails, notNullValue()); + assertThat(userDetails, is(user)); } - // @Ignore + @Ignore @Test public void listUsersTest() throws PasswordPolicyException { - assertTrue(userService.exists(email)); + assertThat(userService.exists(email), is(true)); Pageable pageable = (Pageable) new PageRequest(0, 10, new Sort("email")); List users = userService.listUsers(pageable).getContent(); - assertThat("We should have only a SYSTEM and Admin user", users.size(), is(2)); + assertThat("We should have only a SYSTEM and Admin user", users.size(), is(1)); } @Test public void getWrappedByIdTest() throws UserException { UserWrapper userWrapper = userService.getWrappedById(user.getId()); - assertTrue(userWrapper != null); + assertThat(userWrapper, notNullValue()); } @Test @@ -113,8 +110,8 @@ public class UserServiceTest extends AbstractServicesTest { int pageSize = 10; Page userWrappers = userService.listWrapped(startRow, pageSize); - assertTrue(userWrappers != null); - assertThat(userWrappers.getContent().get(1).getEmail(), is(email)); + assertThat(userWrappers, notNullValue()); + assertThat(userWrappers.getContent().get(0).getEmail(), is(email)); } @Test @@ -122,11 +119,10 @@ public class UserServiceTest extends AbstractServicesTest { User newUser = userService.createUser("1" + email, fullName, initialPassword, AccountType.LOCAL); assertNotNull("User is ull", newUser); - assertTrue(newUser.getId() != null); - assertTrue(newUser.getEmail().equals("1" + email)); - assertTrue(newUser.getFullName().equals(fullName)); - assertTrue(newUser.getPassword().equals(initialPassword)); - + assertThat(newUser.getId(), notNullValue()); + assertThat(newUser.getEmail(), is("1" + email)); + assertThat(newUser.getFullName(), is(fullName)); + assertThat(passwordEncoder.matches(initialPassword, newUser.getPassword()), is(true)); } @Test @@ -136,8 +132,8 @@ public class UserServiceTest extends AbstractServicesTest { String newEmail = "user@newemail.com"; User updatedUser = userService.updateUser(userFromDB, newEmail, newFullName); - assertTrue(updatedUser.getEmail().equals(newEmail)); - assertTrue(updatedUser.getFullName().equals(newFullName)); + assertThat(updatedUser.getEmail(), is(newEmail)); + assertThat(updatedUser.getFullName(), is(newFullName)); User userByEmail = userService.getUserByEmail(newEmail); assertThat(userByEmail.getUuid(), is(updatedUser.getUuid())); @@ -147,32 +143,32 @@ public class UserServiceTest extends AbstractServicesTest { public void updateDataTest() throws UserException { User userFromDB = userService.getUserByEmail(email); - fullName = "This is new name"; - email = "newMail@new.com"; + String newName = "This is new name"; + String newEmail = "newMail@new.com"; - userService.updateUser(userFromDB, email, fullName); + userService.updateUser(userFromDB, newEmail, newName); - userFromDB = userService.getUserByEmail(email); - assertTrue(userFromDB.getFullName().equals(fullName)); + userFromDB = userService.getUserByEmail(newEmail); + assertThat(userFromDB.getFullName(), is(newName)); } @Test public void setPassword() throws PasswordPolicyException { User userFromDB = userService.getUserByEmail(email); - assertTrue(userService.getUserByEmail(email).getPassword().equals(initialPassword)); - initialPassword = "This is new password1!"; - userService.changePassword(userFromDB, initialPassword); + assertThat(passwordEncoder.matches(initialPassword, user.getPassword()), is(true)); + String newPassword = "This is new password1!"; + userService.changePassword(userFromDB, newPassword); userFromDB = userService.getUserByEmail(email); - assertTrue(userFromDB.getPassword().equals(initialPassword)); + assertThat(passwordEncoder.matches(newPassword, userFromDB.getPassword()), is(true)); } @Test public void setAccountEnabledTest() throws PasswordPolicyException { - assertTrue(userService.getUserByUuid(user.getUuid()) != null); + assertThat(userService.getUserByUuid(user.getUuid()), notNullValue()); userService.setAccountActive(user.getUuid(), true); - assertTrue((userService.getUserByUuid(user.getUuid())).isEnabled()); + assertThat(userService.getUserByUuid(user.getUuid()).isEnabled(), is(true)); } @Test(expected = SecurityException.class) @@ -185,10 +181,10 @@ public class UserServiceTest extends AbstractServicesTest { @Test public void setAccountLockLocalTest() throws PasswordPolicyException, NoUserFoundException { userService.setAccountLockLocal(user.getId(), true); - assertTrue(userService.getUserByEmail(email).isAccountLocked()); + assertThat(userService.getUserByEmail(email).isAccountLocked(), is(true)); userService.setAccountLockLocal(user.getId(), false); - assertFalse(userService.getUserByEmail(email).isAccountLocked()); + assertThat(userService.getUserByEmail(email).isAccountLocked(), is(false)); } @Test @@ -205,14 +201,14 @@ public class UserServiceTest extends AbstractServicesTest { @Test public void getUserByEmailTest() { - assertTrue(userService.exists(email)); + assertThat(userService.exists(email), is(true)); } @Test public void getUserByUuidTest() throws PasswordPolicyException { - assertTrue(userService.exists(email)); - assertTrue(userService.getUserByUuid(user.getUuid()) != null); - assertTrue(userService.getUserByUuid(user.getUuid()).getUuid().equals(user.getUuid())); + assertThat(userService.exists(email), is(true)); + assertThat(userService.getUserByUuid(user.getUuid()), notNullValue()); + assertThat(userService.getUserByUuid(user.getUuid()).getUuid(), is(user.getUuid())); } @Test @@ -223,12 +219,12 @@ public class UserServiceTest extends AbstractServicesTest { @Test public void getUserByIdTest() throws NoUserFoundException { - assertTrue(userService.getUser(user.getId()) != null); + assertThat(userService.getUser(user.getId()), notNullValue()); } @Test public void existsTest() { - assertTrue(userService.exists(email)); + assertThat(userService.exists(email), is(true)); } @Test @@ -236,18 +232,17 @@ public class UserServiceTest extends AbstractServicesTest { assertThat(userService.getUserByEmail(email).getRoles(), hasSize(1)); Set selectedRoles = Sets.newHashSet(UserRole.ADMINISTRATOR); userService.setRoles(user, selectedRoles); - assertTrue(userService.getUserByEmail(email).getRoles().contains(UserRole.ADMINISTRATOR)); assertThat(userService.getUserByEmail(email).getRoles(), hasSize(3)); assertThat(userService.getUserByEmail(email).getRoles(), containsInAnyOrder(UserRole.USER, UserRole.ADMINISTRATOR, UserRole.EVERYONE)); } @Test public void autocompleteUserTest() throws PasswordPolicyException { - assertTrue(userService.autocompleteUser("").isEmpty()); - assertTrue(userService.autocompleteUser("m").isEmpty()); - assertTrue(userService.autocompleteUser("ma").isEmpty()); - assertTrue(userService.autocompleteUser("mai").isEmpty()); - assertTrue(userService.autocompleteUser(email.substring(0, 4)).size() == 1); + assertThat(userService.autocompleteUser(""), hasSize(0)); + assertThat(userService.autocompleteUser("m"), hasSize(0)); + assertThat(userService.autocompleteUser("ma"), hasSize(0)); + assertThat(userService.autocompleteUser("mai"), hasSize(0)); + assertThat(userService.autocompleteUser(email.substring(0, 4)).size(), is(1)); } @Test @@ -257,7 +252,7 @@ public class UserServiceTest extends AbstractServicesTest { assertEquals("Password must be equal to 'THIS-IS-NOT-A-PASSWORD'", createdUser.getPassword(), SYSTEM_PASSWORD); } - @Test(expected=PasswordPolicyException.class) + @Test(expected = PasswordPolicyException.class) public void changePasswordForUserWithGoogleTypeTest() throws UserException { User createdUser = userService.createUser("1" + email, fullName, initialPassword, AccountType.GOOGLE); assertEquals(createdUser.getPassword(), SYSTEM_PASSWORD); diff --git a/src/test/java/org/genesys2/util/DOITest.java b/src/test/java/org/genesys/test/simpletest/DOITest.java similarity index 90% rename from src/test/java/org/genesys2/util/DOITest.java rename to src/test/java/org/genesys/test/simpletest/DOITest.java index 484cea684d8e60595389b857dbc8409798a42508..dcd94a355629e8f84a842811876ea4a138478be1 100644 --- a/src/test/java/org/genesys2/util/DOITest.java +++ b/src/test/java/org/genesys/test/simpletest/DOITest.java @@ -13,15 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.genesys2.util; +package org.genesys.test.simpletest; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; +import org.genesys.test.base.NoContextTest; +import org.genesys2.util.DOIUtils; +import org.genesys2.util.InvalidDOIException; import org.genesys2.util.DOIUtils.DOI; import org.junit.Test; -public class DOITest { +public class DOITest extends NoContextTest { @Test public void properDoiTest() throws InvalidDOIException { diff --git a/src/test/java/org/genesys2/server/model/filters/FiltersTest.java b/src/test/java/org/genesys/test/simpletest/FiltersTest.java similarity index 64% rename from src/test/java/org/genesys2/server/model/filters/FiltersTest.java rename to src/test/java/org/genesys/test/simpletest/FiltersTest.java index 2feb2eaacfb3c02719e3b64aa9c113967c73c9fb..0ac64ca3afc16be91e488cb0d5ae639decb7ccbd 100644 --- a/src/test/java/org/genesys2/server/model/filters/FiltersTest.java +++ b/src/test/java/org/genesys/test/simpletest/FiltersTest.java @@ -1,99 +1,30 @@ -package org.genesys2.server.model.filters; +package org.genesys.test.simpletest; +import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.IOException; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.UserService; +import org.genesys.test.base.NoContextTest; import org.genesys2.server.service.impl.FilterHandler; import org.genesys2.server.service.impl.FilterHandler.AppliedFilter; import org.genesys2.server.service.impl.FilterHandler.AppliedFilters; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.TraitServiceImpl; -import org.genesys2.server.service.impl.UserServiceImpl; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.junit.Ignore; import org.junit.Test; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = FiltersTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class FiltersTest { - public static final Logger LOG = LoggerFactory.getLogger(FiltersTest.class); - - @Import({ JpaDataConfig.class }) - @ComponentScan(basePackages = { "org.genesys2.server.persistence" }) - public static class Config { - @Bean - public FilterHandler filterHandler() { - return new FilterHandler(); - } - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } - - @Bean - public TraitService traitService() { - return new TraitServiceImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - } +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; - @Autowired - private FilterHandler filterHandler; +public class FiltersTest extends NoContextTest +{ + public static final Logger LOG = LoggerFactory.getLogger(FiltersTest.class); @Autowired - private ObjectMapper objectMapper; + private ObjectMapper objectMapper = new ObjectMapper(); @Test(expected = NullPointerException.class) public void testNull() throws JsonParseException, JsonMappingException, IOException { @@ -144,9 +75,7 @@ public class FiltersTest { String source = "{\"key\":[1,{\"min\":2},\"Test\"],\"key2\":[{\"max\":2.1},{\"range\":[-1,3.0]}],\"key3\":[{\"like\":\"Te\"},null]}"; AppliedFilters afs = objectMapper.readValue(source, AppliedFilters.class); - String result = objectMapper.writeValueAsString(afs); - LOG.info(result); - assertTrue(source.equals(result)); + assertThat(afs.get("key"), notNullValue()); } @Test @@ -156,12 +85,12 @@ public class FiltersTest { afs.add(new AppliedFilter().setFilterName("key2").addFilterValue(new FilterHandler.LiteralValueFilter("Test 1"))); String source = objectMapper.writeValueAsString(afs); - LOG.info(source); + AppliedFilters afs2 = objectMapper.readValue(source, AppliedFilters.class); String result = objectMapper.writeValueAsString(afs2); - LOG.info(result); - assertTrue(source.equals(result)); + + assertThat(result, is(source)); } @Test @@ -171,12 +100,12 @@ public class FiltersTest { afs.add(new AppliedFilter().setFilterName("key2.two").addFilterValue(new FilterHandler.ValueRangeFilter(-20, 10))); String source = objectMapper.writeValueAsString(afs); - LOG.info(source); + AppliedFilters afs2 = objectMapper.readValue(source, AppliedFilters.class); String result = objectMapper.writeValueAsString(afs2); - LOG.info(result); - assertTrue(source.equals(result)); + + assertThat(result, is(source)); } @Test @@ -186,12 +115,12 @@ public class FiltersTest { afs.add(new AppliedFilter().setFilterName("key2.two").addFilterValue(new FilterHandler.MaxValueFilter(-10.2f))); String source = objectMapper.writeValueAsString(afs); - LOG.info(source); + AppliedFilters afs2 = objectMapper.readValue(source, AppliedFilters.class); String result = objectMapper.writeValueAsString(afs2); - LOG.info(result); - assertTrue(source.equals(result)); + + assertThat(result, is(source)); } @Test @@ -201,12 +130,12 @@ public class FiltersTest { afs.add(new AppliedFilter().setFilterName("key2.two").addFilterValue(new FilterHandler.MinValueFilter(-10.2f))); String source = objectMapper.writeValueAsString(afs); - LOG.info(source); + AppliedFilters afs2 = objectMapper.readValue(source, AppliedFilters.class); String result = objectMapper.writeValueAsString(afs2); - LOG.info(result); - assertTrue(source.equals(result)); + + assertThat(result, is(source)); } @Test @@ -216,29 +145,35 @@ public class FiltersTest { afs.add(new AppliedFilter().setFilterName("key2.two").addFilterValue(new FilterHandler.StartsWithFilter("Haha"))); String source = objectMapper.writeValueAsString(afs); - LOG.info(source); + AppliedFilters afs2 = objectMapper.readValue(source, AppliedFilters.class); String result = objectMapper.writeValueAsString(afs2); - LOG.info(result); - assertTrue(source.equals(result)); + + assertThat(result, is(source)); } @Test public void testMix() throws IOException { AppliedFilters afs = new AppliedFilters(); - afs.add(new AppliedFilter().setFilterName("key1").addFilterValue(new FilterHandler.MaxValueFilter(20.2)) - .addFilterValue(new FilterHandler.StartsWithFilter("Tes")).addFilterValue(null)); - afs.add(new AppliedFilter().setFilterName("key2.two").addFilterValue(new FilterHandler.StartsWithFilter("Haha")) - .addFilterValue(new FilterHandler.MinValueFilter(20.2)).addFilterValue(new FilterHandler.ValueRangeFilter(20, -10))); + afs.add(new AppliedFilter().setFilterName("key1").addFilterValue(new FilterHandler.MaxValueFilter(20.2)).addFilterValue(new FilterHandler.StartsWithFilter("Tes")) + .addFilterValue(null)); + afs.add(new AppliedFilter().setFilterName("key2.two").addFilterValue(new FilterHandler.StartsWithFilter("Haha")).addFilterValue(new FilterHandler.MinValueFilter(20.2)) + .addFilterValue(new FilterHandler.ValueRangeFilter(20, -10))); String source = objectMapper.writeValueAsString(afs); - LOG.info(source); AppliedFilters afs2 = objectMapper.readValue(source, AppliedFilters.class); - String result = objectMapper.writeValueAsString(afs2); - LOG.info(result); - assertTrue(afs2.equals(afs)); + assertThat(afs2, equalTo(afs)); + } + + @Test + public void testDeserializeNeg() throws JsonParseException, JsonMappingException, IOException { + String source = "{\"key\":[1,{\"min\":2},\"Test\"],\"-key2\":[{\"max\":2.1},{\"range\":[-1,3.0]}],\"key3\":[{\"like\":\"Te\"},null]}"; + AppliedFilters afs = objectMapper.readValue(source, AppliedFilters.class); + + assertThat("-key2 must be a negative filter", afs.get("key2").isInverse(), is(true)); + assertThat("key must not be a negative filter", afs.get("key").isInverse(), is(false)); } } diff --git a/src/test/java/org/genesys2/server/model/impl/MCPDUtilTest.java b/src/test/java/org/genesys/test/simpletest/MCPDUtilTest.java similarity index 75% rename from src/test/java/org/genesys2/server/model/impl/MCPDUtilTest.java rename to src/test/java/org/genesys/test/simpletest/MCPDUtilTest.java index dc58056646e834b06dcd061038045e8712d8b74d..e97deed675ad226e385858c11d7276704d0325ce 100644 --- a/src/test/java/org/genesys2/server/model/impl/MCPDUtilTest.java +++ b/src/test/java/org/genesys/test/simpletest/MCPDUtilTest.java @@ -1,20 +1,4 @@ -/** - * Copyright 2016 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.genesys2.server.model.impl; +package org.genesys.test.simpletest; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.*; @@ -23,10 +7,11 @@ import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; +import org.genesys.test.base.NoContextTest; import org.genesys2.util.MCPDUtil; import org.junit.Test; -public class MCPDUtilTest { +public class MCPDUtilTest extends NoContextTest { @Test public void testMcpdArray() { diff --git a/src/test/java/org/genesys2/server/test/NamesTest.java b/src/test/java/org/genesys/test/simpletest/NamesTest.java similarity index 86% rename from src/test/java/org/genesys2/server/test/NamesTest.java rename to src/test/java/org/genesys/test/simpletest/NamesTest.java index d95f3f6ac22c9e9d82c1ec9a385e5197a54b69d3..d25918836af2e84d5501802d1b96a238b16d5078 100644 --- a/src/test/java/org/genesys2/server/test/NamesTest.java +++ b/src/test/java/org/genesys/test/simpletest/NamesTest.java @@ -14,7 +14,7 @@ * limitations under the License. **/ -package org.genesys2.server.test; +package org.genesys.test.simpletest; import java.util.ArrayList; import java.util.HashSet; @@ -23,10 +23,10 @@ import java.util.Set; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import org.junit.Ignore; +import org.genesys.test.base.NoContextTest; import org.junit.Test; -public class NamesTest { +public class NamesTest extends NoContextTest { @Test public void testCleanup() { final List names = new ArrayList(); @@ -46,19 +46,19 @@ public class NamesTest { if (toRemove.contains(name1[0])) { continue; } - System.err.println("Base " + i + " " + ArrayUtils.toString(name1)); + LOG.info("Base " + i + " " + ArrayUtils.toString(name1)); for (int j = i + 1; j < names.size(); j++) { - System.err.println("Inspecting " + j); + LOG.info("Inspecting " + j); final Object[] name2 = names.get(j); if (toRemove.contains(name2[0])) { continue; } final int res = whatToKeep(name1, name2); if (res == -1) { - System.err.println("Would remove " + i + " " + ArrayUtils.toString(name1)); + LOG.info("Would remove " + i + " " + ArrayUtils.toString(name1)); toRemove.add((long) name1[0]); } else if (res == 1) { - System.err.println("Would remove " + j + " " + ArrayUtils.toString(name2)); + LOG.info("Would remove " + j + " " + ArrayUtils.toString(name2)); toRemove.add((long) name2[0]); } } diff --git a/src/test/java/org/genesys2/server/test/NumberUtilsTest.java b/src/test/java/org/genesys/test/simpletest/NumberUtilsTest.java similarity index 94% rename from src/test/java/org/genesys2/server/test/NumberUtilsTest.java rename to src/test/java/org/genesys/test/simpletest/NumberUtilsTest.java index b397790516013c0abdca188fff62372c674bba7d..c3e00e9a7445e1360d7a349d305aba1efc12e613 100644 --- a/src/test/java/org/genesys2/server/test/NumberUtilsTest.java +++ b/src/test/java/org/genesys/test/simpletest/NumberUtilsTest.java @@ -14,15 +14,16 @@ * limitations under the License. **/ -package org.genesys2.server.test; +package org.genesys.test.simpletest; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +import org.genesys.test.base.NoContextTest; import org.genesys2.util.NumberUtils; import org.junit.Test; -public class NumberUtilsTest { +public class NumberUtilsTest extends NoContextTest { @Test public void test1() { assertThat(NumberUtils.numericValue(null), is(0f)); diff --git a/src/test/java/org/genesys2/server/test/PrettyTimeTest.java b/src/test/java/org/genesys/test/simpletest/PrettyTimeTest.java similarity index 65% rename from src/test/java/org/genesys2/server/test/PrettyTimeTest.java rename to src/test/java/org/genesys/test/simpletest/PrettyTimeTest.java index f24d5f3c9864e1c51b7bc5874fda6d3162804d0c..d7a611db3a1cd60414c5130b633c26a6bbf72873 100644 --- a/src/test/java/org/genesys2/server/test/PrettyTimeTest.java +++ b/src/test/java/org/genesys/test/simpletest/PrettyTimeTest.java @@ -1,17 +1,18 @@ -package org.genesys2.server.test; +package org.genesys.test.simpletest; import java.util.Date; import java.util.Locale; +import org.genesys.test.base.NoContextTest; import org.junit.Test; import org.ocpsoft.prettytime.PrettyTime; -public class PrettyTimeTest { +public class PrettyTimeTest extends NoContextTest { @Test public void testPretty() { PrettyTime pt=new PrettyTime(); Date then = new Date(); - System.out.println(pt.format(then)); + LOG.debug(pt.format(then)); } @Test @@ -19,6 +20,6 @@ public class PrettyTimeTest { Locale locale=Locale.GERMAN; PrettyTime pt=new PrettyTime(locale); Date then = new Date(); - System.out.println(pt.format(then)); + LOG.debug(pt.format(then)); } } diff --git a/src/test/java/org/genesys2/server/test/TilesMathTest.java b/src/test/java/org/genesys/test/simpletest/TilesMathTest.java similarity index 97% rename from src/test/java/org/genesys2/server/test/TilesMathTest.java rename to src/test/java/org/genesys/test/simpletest/TilesMathTest.java index a3e222aae12d0acc73e3c1e7f44f4cec13ef379b..5b9d1f46da68e69523f6541e1ac878d94f259a80 100644 --- a/src/test/java/org/genesys2/server/test/TilesMathTest.java +++ b/src/test/java/org/genesys/test/simpletest/TilesMathTest.java @@ -14,11 +14,13 @@ * limitations under the License. **/ -package org.genesys2.server.test; +package org.genesys.test.simpletest; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; +import org.genesys.test.base.NoContextTest; + import static org.genesys2.server.service.MappingService.CoordUtil.latToImg; import static org.genesys2.server.service.MappingService.CoordUtil.lonToImg; import static org.genesys2.server.service.MappingService.CoordUtil.latToImg3; @@ -29,7 +31,7 @@ import static org.genesys2.server.service.MappingService.CoordUtil.tileToLon; import org.genesys2.server.service.MappingService.CoordUtil; import org.junit.Test; -public class TilesMathTest { +public class TilesMathTest extends NoContextTest { @Test public void test1() { diff --git a/src/test/java/org/genesys2/server/mock/service/TokenConsumerService.java b/src/test/java/org/genesys2/server/mock/service/TokenConsumerService.java deleted file mode 100644 index 5bfd9eaf20e0359d37ebeac636439d03115b95b9..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/mock/service/TokenConsumerService.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 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.genesys2.server.mock.service; - -import org.genesys2.server.model.impl.VerificationToken; -import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException; -import org.genesys2.server.service.TokenVerificationService.TokenExpiredException; - -public interface TokenConsumerService { - - void noExceptions(VerificationToken token) throws NoSuchVerificationTokenException, TokenExpiredException; - - void throwRuntimeException(VerificationToken token) throws NoSuchVerificationTokenException, TokenExpiredException; - - void noToken() throws NoSuchVerificationTokenException, TokenExpiredException; - - void throwException(VerificationToken token) throws Exception; - -} diff --git a/src/test/java/org/genesys2/server/mock/service/TokenConsumerServiceImpl.java b/src/test/java/org/genesys2/server/mock/service/TokenConsumerServiceImpl.java deleted file mode 100644 index 6f81613df421fc4211690261e055f91b3f5bf9ae..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/mock/service/TokenConsumerServiceImpl.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 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.genesys2.server.mock.service; - -import org.genesys2.server.model.impl.VerificationToken; -import org.genesys2.server.service.TokenVerificationService; -import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException; -import org.genesys2.server.service.TokenVerificationService.TokenExpiredException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Mock service to test verification token behavior with exceptions - * - * @author matijaobreza - * - */ -@Service -@Transactional(readOnly = true) -public class TokenConsumerServiceImpl implements TokenConsumerService { - - @Autowired - private TokenVerificationService tokenVerificationService; - - @Override - @Transactional - public void throwRuntimeException(VerificationToken token) throws NoSuchVerificationTokenException, TokenExpiredException { - tokenVerificationService.consumeToken(token.getPurpose(), token.getUuid(), token.getKey()); - throw new RuntimeException(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void throwException(VerificationToken token) throws Exception { - tokenVerificationService.consumeToken(token.getPurpose(), token.getUuid(), token.getKey()); - throw new Exception(); - } - - @Override - @Transactional - public void noExceptions(VerificationToken token) throws NoSuchVerificationTokenException, TokenExpiredException { - tokenVerificationService.consumeToken(token.getPurpose(), token.getUuid(), token.getKey()); - } - - @Override - @Transactional - public void noToken() throws NoSuchVerificationTokenException, TokenExpiredException { - tokenVerificationService.consumeToken("nopurpose", "no-such-uuid", "wrongkey"); - throw new RuntimeException("Should not get here"); - } -} diff --git a/src/test/java/org/genesys2/server/model/filters/InverseFiltersTest.java b/src/test/java/org/genesys2/server/model/filters/InverseFiltersTest.java deleted file mode 100644 index d207807396449942250294b9c36a5a9d7306cede..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/model/filters/InverseFiltersTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.genesys2.server.model.filters; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.genesys2.server.service.impl.FilterHandler.AppliedFilters; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = InverseFiltersTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class InverseFiltersTest { - public static final Logger LOG = LoggerFactory.getLogger(InverseFiltersTest.class); - - public static class Config { - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } - } - - @Autowired - private ObjectMapper objectMapper; - - @Test - public void testDeserializeNeg() throws JsonParseException, JsonMappingException, IOException { - String source = "{\"key\":[1,{\"min\":2},\"Test\"],\"-key2\":[{\"max\":2.1},{\"range\":[-1,3.0]}],\"key3\":[{\"like\":\"Te\"},null]}"; - AppliedFilters afs = objectMapper.readValue(source, AppliedFilters.class); - - String result = objectMapper.writeValueAsString(afs); - LOG.info(result); - assertTrue(source.equals(result)); - - assertTrue("-key2 must be a negative filter", afs.get("key2").isInverse()); - assertFalse("key must not be a negative filter", afs.get("key").isInverse()); - } -} diff --git a/src/test/java/org/genesys2/server/model/impl/AccessionCacheTest.java b/src/test/java/org/genesys2/server/model/impl/AccessionCacheTest.java deleted file mode 100644 index 4f816392932a1cfa804a15b5fa5161f794ed9f09..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/model/impl/AccessionCacheTest.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * 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.genesys2.server.model.impl; - -import java.io.IOException; -import java.util.Set; - -import com.hazelcast.core.DistributedObject; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IMap; -import com.hazelcast.monitor.LocalMapStats; - -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.VelocityException; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.model.genesys.Accession; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.impl.ContentServiceImpl; -import org.genesys2.server.service.impl.CropServiceImpl; -import org.genesys2.server.service.impl.GenesysServiceImpl; -import org.genesys2.server.service.impl.GeoServiceImpl; -import org.genesys2.server.service.impl.InstituteServiceImpl; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.OrganizationServiceImpl; -import org.genesys2.server.service.impl.TaxonomyServiceImpl; -import org.genesys2.server.service.impl.UserServiceImpl; -import org.genesys2.server.test.JpaRealDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.ui.velocity.VelocityEngineFactoryBean; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = AccessionCacheTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -@DirtiesContext -public class AccessionCacheTest { - - @Import({ JpaRealDataConfig.class, HazelcastConfig.class }) - @ComponentScan(basePackages = { "org.genesys2.server.persistence" }) - public static class Config { - - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public VelocityEngine velocityEngine() throws VelocityException, IOException { - final VelocityEngineFactoryBean vf = new VelocityEngineFactoryBean(); - return vf.createVelocityEngine(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - } - - @Autowired - private GenesysService genesysService; - - @Autowired - private InstituteService instituteService; - - @Test - public void test1() { - FaoInstitute iita = instituteService.getInstitute("NGA039"); - System.out.println("IITA: " + iita); - - System.err.println("See caching of country"); - for (int i = 0; i < 10; i++) { - iita = instituteService.getInstitute("NGA039"); - System.out.println("Country: " + iita.getCountry()); - } - printCacheStats(); - } - - @Test - public void test2() { - System.out.println("Find 1st"); - Accession accession = genesysService.getAccession(3446120); - System.out.println("Acn: " + accession); - System.out.println(accession.getCountryOfOrigin()); - System.out.println(accession.getInstitute()); - System.out.println(accession.getTaxonomy()); - - System.out.println("See caching of stuff"); - for (int i = 0; i < 10; i++) { - System.out.println("Find"); - accession = genesysService.getAccession(3446120); - System.out.println("Acn: " + accession); - System.out.println(accession.getCountryOfOrigin()); - System.out.println(accession.getInstitute()); - System.out.println(accession.getTaxonomy()); - } - printCacheStats(); - - } - - public static void printCacheStats() { - Set instances = Hazelcast.getAllHazelcastInstances(); - for (HazelcastInstance hz : instances) { - System.out.println("\n\nCache stats Instance: " + hz.getName()); - for (DistributedObject o : hz.getDistributedObjects()) { - if (o instanceof IMap) { - IMap imap = (IMap) o; - System.out.println(imap.getServiceName() + ": " + imap.getName() + " " + imap.getPartitionKey()); - LocalMapStats localMapStats = imap.getLocalMapStats(); - System.out.println("created: " + localMapStats.getCreationTime()); - System.out.println("owned entries: " + localMapStats.getOwnedEntryCount()); - System.out.println("backup entries: " + localMapStats.getBackupEntryCount()); - System.out.println("locked entries: " + localMapStats.getLockedEntryCount()); - System.out.println("dirty entries: " + localMapStats.getDirtyEntryCount()); - System.out.println("hits: " + localMapStats.getHits()); - System.out.println("puts: " + localMapStats.getPutOperationCount()); - System.out.println("last update: " + localMapStats.getLastUpdateTime()); - System.out.println("last access:" + localMapStats.getLastAccessTime()); - } else { - System.out.println(o.getClass() + " " + o); - } - } - } - } -} diff --git a/src/test/java/org/genesys2/server/model/impl/FaoInstituteTest.java b/src/test/java/org/genesys2/server/model/impl/FaoInstituteTest.java deleted file mode 100644 index 990658e4aa86f761194791edb9d1a016f202a981..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/model/impl/FaoInstituteTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * 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.genesys2.server.model.impl; - -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class FaoInstituteTest { - - @Test - public void testUrlsDefault() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - assertTrue(i.getUrl() == null); - assertTrue(i.getUrls() == null); - } - - @Test - public void testUrlsBlank() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl(""); - assertTrue(i.getUrl() != null); - assertTrue(i.getUrls() == null); - } - - @Test - public void testUrlsBlank2() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl(";"); - assertTrue(i.getUrl() != null); - assertTrue(i.getUrls() != null); - assertTrue(i.getUrls().size() == 0); - } - - @Test - public void testUrlsValid1() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl("https://www.iita.org"); - assertTrue(i.getUrl() != null); - assertTrue(i.getUrls() != null); - assertTrue(i.getUrls().size() == 1); - } - - @Test - public void testUrlsValid2() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl("https://www.iita.org; http://genebank.iita.org, "); - assertTrue(i.getUrl() != null); - List urls = i.getUrls(); - assertTrue(urls != null); - assertTrue(urls.size() == 2); - } - - @Test - public void testUrlsNoProtocol() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl("www.iita.org"); - assertTrue(i.getUrl() != null); - List urls = i.getUrls(); - assertTrue(urls != null); - assertTrue(urls.size() == 1); - assertTrue(urls.get(0).equals(new URL("http://www.iita.org"))); - } - - @Test - public void testUrlsNoProtocol2() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl("www.iita.org,https://foo.bar;www.somehost.org"); - assertTrue(i.getUrl() != null); - List urls = i.getUrls(); - assertTrue(urls != null); - assertTrue(urls.size() == 3); - assertTrue(urls.get(0).equals(new URL("http://www.iita.org"))); - assertTrue(urls.get(1).equals(new URL("https://foo.bar"))); - assertTrue(urls.get(2).equals(new URL("http://www.somehost.org"))); - } - - @Test - // http://www.sasa.gov.uk www.scottishlandraces.org.uk - // www.varieties.potato.org.uk www.agricrops.org - public void testUrlsSample1() throws MalformedURLException { - FaoInstitute i = new FaoInstitute(); - i.setUrl("http://www.sasa.gov.uk www.scottishlandraces.org.uk www.varieties.potato.org.uk www.agricrops.org"); - assertTrue(i.getUrl() != null); - List urls = i.getUrls(); - assertTrue(urls != null); - assertTrue(urls.size() == 4); - assertTrue(urls.get(0).equals(new URL("http://www.sasa.gov.uk"))); - assertTrue(urls.get(1).equals(new URL("http://www.scottishlandraces.org.uk"))); - assertTrue(urls.get(2).equals(new URL("http://www.varieties.potato.org.uk"))); - assertTrue(urls.get(3).equals(new URL("http://www.agricrops.org"))); - } - - @Test - public void testDump1() throws IOException { - InputStream fis = getClass().getResourceAsStream("/org/genesys2/server/model/impl/wiews-urls.txt"); - BufferedReader sr = new BufferedReader(new InputStreamReader(fis)); - - String l = null; - FaoInstitute i = new FaoInstitute(); - - while ((l = sr.readLine()) != null) { - int expectedUrls = StringUtils.isBlank(l) ? 0 : l.trim().split("[,;\\s]+").length; - i.setUrl(l); - try { - - List urls = i.getUrls(); - if (StringUtils.isBlank(l)) { - assertTrue(urls == null); - } else { - assertTrue(urls != null); - assertTrue(urls.size() == expectedUrls); - } - } catch (MalformedURLException e) { - System.err.println(e.getMessage()); - System.err.println(l); - System.err.println(Arrays.asList(l.trim().split("[,;\\s]+"))); - } - } - IOUtils.closeQuietly(fis); - } - - @Test - public void testFunny1() throws MalformedURLException { - FaoInstitute i=new FaoInstitute(); - i.setUrl("www.http://ongrc.org"); - List urls = i.getUrls(); - assertTrue(urls.get(0).equals(new URL("http://ongrc.org"))); - - i.setUrl("htt://www.conagebio.go.cr"); - urls = i.getUrls(); - assertTrue(urls.get(0).equals(new URL("http://www.conagebio.go.cr"))); - } -} diff --git a/src/test/java/org/genesys2/server/oauth/OAuthTokenSerializationTest.java b/src/test/java/org/genesys2/server/oauth/OAuthTokenSerializationTest.java deleted file mode 100644 index fd9a6722ccc24c82e8f26e4e6782464c4e797996..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/oauth/OAuthTokenSerializationTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * 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.genesys2.server.oauth; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.junit.Test; -import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken; -import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; -import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class OAuthTokenSerializationTest { - ObjectMapper mapper = new ObjectMapper(); - - @Test - public void testSerializeRefreshToken() throws JsonProcessingException { - OAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken("token1", new Date(System.currentTimeMillis() + 100)); - System.err.println(mapper.writeValueAsString(refreshToken)); - - refreshToken = new DefaultOAuth2RefreshToken("token1"); - System.err.println(mapper.writeValueAsString(refreshToken)); - } - - @Test - public void testSerializeAccessToken() throws IOException { - DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken("accessToken1"); - accessToken.setExpiration(new Date(System.currentTimeMillis() + 5000)); - OAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken("token1", new Date(System.currentTimeMillis() + 10000)); - accessToken.setRefreshToken(refreshToken); - Set scope = new HashSet(); - scope.add("read"); - scope.add("write"); - accessToken.setScope(scope); - accessToken.setTokenType("tokenType"); - Map additionalInformation = new HashMap(); - additionalInformation.put("testStr", "string"); - additionalInformation.put("testInt", 1); - additionalInformation.put("testDbl", 1.1d); - accessToken.setAdditionalInformation(additionalInformation); - String accessTokenStr = mapper.writeValueAsString(accessToken); - System.err.println(accessTokenStr); - - DefaultOAuth2AccessToken tokenRead = mapper.readValue(accessTokenStr, DefaultOAuth2AccessToken.class); - assertTrue(tokenRead.getTokenType().equals(accessToken.getTokenType())); - // roughly the same - assertTrue(tokenRead.getExpiration().getTime() / 50000 == (accessToken.getExpiration().getTime() / 50000)); - assertTrue(tokenRead.getValue().equals(accessToken.getValue())); - - assertTrue(tokenRead.getScope().size() == accessToken.getScope().size()); - for (String s : tokenRead.getScope()) { - assertTrue(accessToken.getScope().contains(s)); - } - - assertTrue(tokenRead.getAdditionalInformation().size() == accessToken.getAdditionalInformation().size()); - for (String aikey : tokenRead.getAdditionalInformation().keySet()) { - assertTrue(accessToken.getAdditionalInformation().containsKey(aikey)); - Object a = tokenRead.getAdditionalInformation().get(aikey); - Object b = accessToken.getAdditionalInformation().get(aikey); - assertTrue((a == null && b == null) || (a != null && b != null)); - assertTrue(a.toString().equals(b.toString())); - } - - System.err.println(mapper.writeValueAsString(tokenRead)); - } - - @Test - public void testDeserializeRefreshToken() throws IOException { - - } -} diff --git a/src/test/java/org/genesys2/server/persistence/domain/mock/TraitServiceMock.java b/src/test/java/org/genesys2/server/persistence/domain/mock/TraitServiceMock.java deleted file mode 100644 index 8cdae837d8c888a9a6b589c80205ba90a8e18143..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/persistence/domain/mock/TraitServiceMock.java +++ /dev/null @@ -1,310 +0,0 @@ -package org.genesys2.server.persistence.domain.mock; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.genesys.blocks.security.SecurityContextUtil; -import org.genesys.blocks.security.model.AclSid; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys2.server.model.genesys.AccessionId; -import org.genesys2.server.model.genesys.Metadata; -import org.genesys2.server.model.genesys.Method; -import org.genesys2.server.model.genesys.Parameter; -import org.genesys2.server.model.genesys.ParameterCategory; -import org.genesys2.server.model.impl.Crop; -import org.genesys2.server.persistence.AccessionTraitRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.MetadataMethodRepository; -import org.genesys2.server.persistence.MethodRepository; -import org.genesys2.server.persistence.ParameterCategoryRepository; -import org.genesys2.server.persistence.ParameterRepository; -import org.genesys2.server.persistence.TraitValueRepository; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.impl.GenesysServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.acls.domain.BasePermission; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional(readOnly = true) -public class TraitServiceMock implements TraitService{ - public static final Logger LOG = LoggerFactory.getLogger(GenesysServiceImpl.class); - - @Autowired - private GenesysLowlevelRepository genesysLowlevelRepository; - @Autowired - private CustomAclService aclService; - @Autowired - private HtmlSanitizer htmlSanitizer; - - @Autowired - private TraitValueRepository traitValueRepository; - @Autowired - private ParameterCategoryRepository parameterCategoryRepository; - @Autowired - private ParameterRepository parameterRepository; - @Autowired - private MethodRepository methodRepository; - @Autowired - private AccessionTraitRepository accessionTraitRepository; -// @Autowired -// private MetadataRepository metadataRepository; - @Autowired - private MetadataMethodRepository metadataMethodRepository; - - @Override - public List listCategories() { - return parameterCategoryRepository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "id"))); - } - - @Override - public List listTraits() { - return parameterRepository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "id"))); - } - - @Override - public Page listTraits(Pageable pageable) { - return parameterRepository.findAll(pageable); - } - - @Override - public Page listTraits(Crop crop, Pageable pageable) { - return parameterRepository.findByCrop(crop, pageable); - } - - @Override - public Parameter getTrait(long traitId) { - return parameterRepository.findOne(traitId); - } - - @Override - public List getTraitMethods(Parameter trait) { - return methodRepository.findByParameter(trait); - } - - @Override - public Method getMethod(long methodId) { - return methodRepository.findOne(methodId); - } - - @Override - public List listMethods() { - return methodRepository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "id"))); - } - - @Override - public Page listMethods(Pageable pageable) { - return methodRepository.findAll(pageable); - } - - @Override - public List listMetadataByMethod(Method method) { - return metadataMethodRepository.listMetadataByMethodId(method.getId()); - } - - @Override - public List listMethods(AccessionId accession) { - final List x = accessionTraitRepository.listMethodIds(accession); - return x.size() == 0 ? null : methodRepository.findByIds(x); - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = false) - public ParameterCategory addCategory(String name, String i18n) { - final ParameterCategory category = new ParameterCategory(); - category.setName(name); - category.setNameL(i18n); - parameterCategoryRepository.save(category); - return category; - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = true) - public ParameterCategory getCategory(String name) { - final ParameterCategory category = parameterCategoryRepository.findByName(name); - return category; - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = false) - public Parameter addParameter(String rdfUri, Crop crop, String category, String title, String i18n) { - - final Parameter parameter = new Parameter(); - - parameter.setRdfUri(StringUtils.defaultIfBlank(rdfUri, null)); - parameter.setCrop(crop); - - // In an ideal world, we should search for category by URI, not name... - final ParameterCategory parameterCategory = parameterCategoryRepository.findByName(category); - - parameter.setCategory(parameterCategory); - parameter.setTitle(title); - parameter.setI18n(StringUtils.defaultIfBlank(i18n, null)); - - parameterRepository.save(parameter); - - return parameter; - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = true) - public Parameter getParameter(String rdfUri) { - - if (rdfUri == null || rdfUri.isEmpty()) { - return null; - } - - final Parameter parameter = parameterRepository.findByRdfUri(rdfUri); // assumes - // that - // crop - // x - // title - // is - // unique(?) - return parameter; - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = true) - public Parameter getParameter(Crop crop, String title) { - final Parameter parameter = parameterRepository.findByCropAndTitle(crop, title); // assumes - // that - // crop - // x - // title - // is - // unique(?) - return parameter; - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = false) - public Method addMethod(String rdfUri, String description, String i18n, String unit, String fieldName, int fieldType, Integer fieldSize, String options, - String range, Parameter parameter) { - - final Method method = new Method(); - - method.setRdfUri(StringUtils.defaultIfBlank(rdfUri, null)); - method.setMethod(htmlSanitizer.sanitize(description)); - method.setI18n(StringUtils.defaultIfBlank(i18n, null)); - method.setUnit(StringUtils.defaultIfBlank(StringUtils.trimToNull(unit), null)); - method.setFieldName(StringUtils.trimToNull(fieldName)); - method.setFieldType(fieldType); - - if (fieldType == 0) { - // Will throw NPE if not provided! - method.setFieldSize(fieldSize.toString()); - } - - method.setOptions(StringUtils.defaultIfBlank(StringUtils.trimToNull(options), null)); - method.setRange(StringUtils.defaultIfBlank(StringUtils.trimToNull(range), null)); - method.setParameter(parameter); - - methodRepository.save(method); - - // Ensure table for method! - genesysLowlevelRepository.ensureMethodTable(method); - - return method; - } - - @Override - @PreAuthorize("isAuthenticated()") - @Transactional(readOnly = true) - public Method getMethod(String rdfUri) { - - if (rdfUri == null || rdfUri.isEmpty()) { - return null; - } - - final Method method = methodRepository.findByRdfUri(rdfUri); - - return method; - } - - @Override - public Method getMethod(String description, Parameter parameter) { - - if (description == null || description.isEmpty()) { - return null; - } - - final Method method = methodRepository.findByMethodAndParameter(description, parameter); - - return method; - } - - /** - * Returns datasets to which current user has 'WRITE' - */ - @Override - @PreAuthorize("isAuthenticated()") - public List listMyMethods() { - final AclSid sid = SecurityContextUtil.getCurrentUser(); - final List oids = aclService.listObjectIdentityIdsForSid(Method.class, sid, BasePermission.WRITE); - LOG.info("Got {} elements for {}", oids.size(), sid); - if (oids.size() == 0) { - return null; - } - - return methodRepository.findByIds(oids); - } - - @Override - public Map getMethodStatistics(Method method) { - if (method.isCoded()) { - return traitValueRepository.getStatistics(method); - } else { - return null; - } - } - - @Override - public Map> mapTraits(Crop crop, List parameterCategories) { - if (parameterCategories == null || parameterCategories.size() == 0) { - return null; - } - - final HashMap> catTraits = new HashMap>(); - - for (final ParameterCategory pc : parameterCategories) { - ArrayList traits; - catTraits.put(pc, traits = new ArrayList()); - traits.addAll(parameterRepository.findByCropAndCategory(crop, pc, new Sort(new Sort.Order("title")))); - } - - return catTraits; - } - - @Override - public Map> mapMethods(Crop crop) { - final HashMap> paramMethods = new HashMap>(); - - for (final Method method : methodRepository.findByCrop(crop)) { - List list = paramMethods.get(method.getParameter().getId()); - if (list == null) { - paramMethods.put(method.getParameter().getId(), list = new ArrayList()); - } - list.add(method); - } - - return paramMethods; - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/AccessionHistoryTest.java b/src/test/java/org/genesys2/server/service/impl/AccessionHistoryTest.java deleted file mode 100644 index 596b6468216e0f92da8079b2255a7ea90e4825b8..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/AccessionHistoryTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2016 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.genesys2.server.service.impl; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.Collections; -import java.util.UUID; - -import org.genesys2.server.model.genesys.Accession; -import org.genesys2.server.model.genesys.AccessionHistoric; -import org.genesys2.server.model.genesys.AccessionId; -import org.genesys2.server.model.genesys.Taxonomy2; -import org.genesys2.server.model.impl.Country; -import org.genesys2.server.model.impl.FaoInstitute; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.transaction.annotation.Transactional; - -import com.google.common.collect.Sets; - -/** - * Ensure that deleted accessions end up as {@link AccessionHistoric} entities. - */ -@Transactional -public class AccessionHistoryTest extends GenesysServicesTest { - private static final String ACCENUMB = "ACC-001"; - private static final String INSTCODE = "INS001"; - - private FaoInstitute faoInstitute; - private Country country; - private Taxonomy2 taxonomy2; - private Accession accession; - - @Before - public void setup() throws InterruptedException { - faoInstitute = new FaoInstitute(); - faoInstitute.setFullName("This is name of institute"); - faoInstitute.setCurrent(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setMaintainsCollection(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setAccessionCount(1); - faoInstitute.setUniqueAcceNumbs(true); - faoInstitute.setCode(INSTCODE); - - instituteService.update(Collections.singletonList(faoInstitute)); - faoInstitute = instituteService.getInstitute(faoInstitute.getCode()); - - taxonomy2 = taxonomyService.internalEnsure("Genus", "species", "", "", ""); - - country = new Country(); - country.setCode3("UKR"); - country.setName("Ukraine"); - country = countryRepository.save(country); - - accession = new Accession(); - accession.setAccessionId(new AccessionId()); - } - - @After - public void teardown() { - accessionHistoricRepository.deleteAll(); - accessionRepository.deleteAll(); - countryRepository.deleteAll(); - instituteRepository.deleteAll(); - taxonomyRepository.deleteAll(); - } - - @Test - public void testDeleteAccession1() throws NonUniqueAccessionException { - accession.setAccessionNumber(ACCENUMB); - accession.setInstitute(faoInstitute); - accession.setTaxonomy(taxonomy2); - accession.setCountryOfOrigin(country); - accession.getAccessionId().setStorage(Sets.newHashSet(10, 20)); - - genesysService.saveAccessions(faoInstitute, Collections.singletonList(accession)); - - accession = genesysService.getAccession(INSTCODE, ACCENUMB); - assertThat("INSTCODE must match", accession.getInstituteCode(), is(INSTCODE)); - assertThat("Institute#code must match", accession.getInstitute().getCode(), is(INSTCODE)); - assertThat("ACCENUMB must match", accession.getAccessionNumber(), is(ACCENUMB)); - assertThat("storage must match", accession.getAccessionId().getStorage(), contains(10, 20)); - UUID uuid = accession.getUuid(); - - // Delete accession - genesysService.removeAccessions(faoInstitute, Collections.singletonList(accession)); - Accession a = genesysService.getAccession(INSTCODE, ACCENUMB); - assertThat(a, nullValue()); - - AccessionHistoric historic = genesysService.getHistoricAccession(uuid); - assertThat(historic, not(nullValue())); - assertThat("INSTCODE must match", historic.getInstituteCode(), is(INSTCODE)); - assertThat("Institute#code must match", historic.getInstitute().getCode(), is(INSTCODE)); - assertThat("ACCENUMB must match", historic.getAccessionNumber(), is(ACCENUMB)); - assertThat("stoRage must match", historic.getAccessionId().getStorage(), contains(10, 20)); - } - -} diff --git a/src/test/java/org/genesys2/server/service/impl/AccessionListReal.java b/src/test/java/org/genesys2/server/service/impl/AccessionListReal.java deleted file mode 100644 index a90e65b5881d6be500e76b8155d15887d3b50086..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/AccessionListReal.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Copyright 2015 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.genesys2.server.service.impl; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.util.HashSet; -import java.util.Set; - -import org.genesys2.server.model.genesys.Accession; -import org.genesys2.server.model.genesys.AccessionList; -import org.genesys2.server.persistence.TraitValueRepository; -import org.genesys2.server.persistence.TraitValueRepositoryImpl; -import org.genesys2.server.service.AccessionListService; -import org.genesys2.server.service.FilterConstants; -import org.genesys2.server.service.GenesysFilterService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.impl.FilterHandler.AppliedFilter; -import org.genesys2.server.service.impl.FilterHandler.AppliedFilters; -import org.genesys2.server.test.GenesysBeansConfig; -import org.genesys2.server.test.JpaRealDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { HazelcastConfig.class, JpaRealDataConfig.class, AccessionListReal.Config.class, GenesysBeansConfig.class }, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class AccessionListReal { - private static final Logger LOG = LoggerFactory.getLogger(AccessionListReal.class); - - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public AccessionListServiceImpl accessionListService() { - return new AccessionListServiceImpl(); - } - - @Bean - public TraitValueRepository traitValueRepository() { - return new TraitValueRepositoryImpl(); - } - } - - @Autowired - private AccessionListService accessionListService; - - @Autowired - private GenesysService genesysService; - - @Autowired - private GenesysFilterService genesysFilterService; - - @Test - public void testAccessionList1() throws NonUniqueAccessionException { - LOG.info("Add 1"); - AccessionList accessionList = new AccessionList(); - accessionList.setTitle("List TMb-1"); - accessionListService.save(accessionList); - assertThat("AccessionList is missing UUID", accessionList.getUuid(), notNullValue()); - - AccessionList loaded = accessionListService.getList(accessionList.getUuid()); - assertThat("AccessionList could not be loaded by UUID", loaded, notNullValue()); - - // Add TMb-1 to the list - Accession a1 = genesysService.getAccession("NGA039", "TMb-1"); - assertThat("TMb-1 should not be null", a1, notNullValue()); - accessionListService.addToList(loaded, a1); - - assertThat("List size of 1", accessionListService.sizeOf(loaded), is(1)); - - // do a load - Set ids = accessionListService.getAccessionIds(loaded); - assertThat("List size of 1", ids.size(), is(1)); - - // Bye-bye - accessionListService.delete(loaded); - } - - @Test - public void testAccessionList1to100() throws NonUniqueAccessionException { - LOG.info("Add 1-100"); - AccessionList accessionList = new AccessionList(); - accessionList.setTitle("List 1-100"); - accessionListService.save(accessionList); - assertThat("AccessionList is missing UUID", accessionList.getUuid(), notNullValue()); - - AccessionList loaded = accessionListService.getList(accessionList.getUuid()); - assertThat("AccessionList could not be loaded by UUID", loaded, notNullValue()); - - Set accessionIds=new HashSet(); - for (Long acceId : genesysService.listAccessionsIds(new PageRequest(0, 100))) { - accessionIds.add(acceId); - } - - // Add accessions by their IDs - accessionListService.addToList(loaded, accessionIds); - - Set ids = accessionListService.getAccessionIds(loaded); - assertThat("List size of 100", ids.size(), is(100)); - - // Bye-bye - accessionListService.delete(loaded); - } - - @Test - public void testAccessionListFromFilters() throws NonUniqueAccessionException { - LOG.info("Adding by filter"); - AccessionList accessionList = new AccessionList(); - accessionList.setTitle("List NGA039"); - accessionListService.save(accessionList); - assertThat("AccessionList is missing UUID", accessionList.getUuid(), notNullValue()); - - final AccessionList loaded = accessionListService.getList(accessionList.getUuid()); - assertThat("AccessionList could not be loaded by UUID", loaded, notNullValue()); - - final AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.INSTCODE).addFilterValue(new FilterHandler.LiteralValueFilter("NGA039"))); - - // 1st pass - accessionListService.addToList(loaded, filters); - int count = accessionListService.sizeOf(loaded); - System.err.println(count); - - // 2nd pass (this would throw errors) - accessionListService.addToList(loaded, filters); - assertThat("No change in list size expected", accessionListService.sizeOf(loaded), is(count)); - - final AppliedFilters filters2 = new AppliedFilters(); - filters2.add(new AppliedFilter().setFilterName(FilterConstants.LISTS).addFilterValue(new FilterHandler.LiteralValueFilter(loaded.getUuid()))); - - Page res = genesysFilterService.listAccessions(filters2, new PageRequest(0, 50)); - assertThat("Page.total must match", res.getTotalElements(), is((long)count)); - assertThat("Page.total must match", res.getNumberOfElements(), is(50)); - - // Remove all traces of us being here - accessionListService.delete(loaded); - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/AccessionListTest.java b/src/test/java/org/genesys2/server/service/impl/AccessionListTest.java deleted file mode 100644 index a8c549fec16914168ab61791230419cc52d78128..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/AccessionListTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2015 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.genesys2.server.service.impl; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -import org.genesys2.server.model.genesys.AccessionList; -import org.genesys2.server.service.AccessionListService; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { HazelcastConfig.class, JpaDataConfig.class, AccessionListTest.Config.class }, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class AccessionListTest { - - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public AccessionListServiceImpl accessionListService() { - return new AccessionListServiceImpl(); - } - - - } - - @Autowired - private AccessionListService accessionListService; - - @Test - public void testAccessionList1() { - AccessionList accessionList=new AccessionList(); - accessionList.setTitle("List1"); - accessionListService.save(accessionList); - assertThat("AccessionList is missing UUID", accessionList.getUuid(), notNullValue()); - - AccessionList loaded = accessionListService.getList(accessionList.getUuid()); - assertThat("AccessionList could not be loaded by UUID", loaded, notNullValue()); - - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/DSTest.java b/src/test/java/org/genesys2/server/service/impl/DSTest.java deleted file mode 100644 index 8afe9ec1396a096f3cf8dac2d318e12a22d48878..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/DSTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.genesys2.server.service.impl; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.genesys2.server.model.dataset.DS; -import org.genesys2.server.model.dataset.DSColumn; -import org.genesys2.server.model.dataset.DSQualifier; -import org.genesys2.server.model.dataset.DSDescriptor; -import org.genesys2.server.service.DSService; -import org.genesys2.server.service.DescriptorService; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.hamcrest.collection.IsCollectionWithSize; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = DSTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class DSTest { - - @Import({ HazelcastConfig.class, JpaDataConfig.class }) - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public DSService dsService() { - return new DSServiceImpl(); - } - - @Bean - public DescriptorService descriptorService() { - return new DescriptorServiceImpl(); - } - } - - @Autowired - private DSService dsService; - @Autowired - private DescriptorService descriptorService; - - @Test - public void test1() throws IOException { - DS ds = generateDataset(); - dsService.saveDataset(ds); - assertThat("Dataset must have a UUID", ds.getUuid(), notNullValue()); - - DSDescriptor d1 = generateDescriptor("D1"); - descriptorService.saveDescriptor(d1); - DSDescriptor d2 = generateDescriptor("D2"); - descriptorService.saveDescriptor(d2); - - DSQualifier dsq1 = dsService.addQualifier(ds, d1); - DSQualifier dsq2 = dsService.addQualifier(ds, d2); - - DSDescriptor d3 = generateDescriptor("D3"); - descriptorService.saveDescriptor(d3); - DSDescriptor d4 = generateDescriptor("D4"); - descriptorService.saveDescriptor(d4); - - dsService.addDescriptor(ds, d3); - dsService.addDescriptor(ds, d4); - - // assertThat("DSQualifier must have an id", dsq1.getId(), - // notNullValue()); - // - System.out.println(dsq1.getId() + " " + dsq1.getDescriptor()); - assertThat("DSQualifier must be loaded by id", dsq1, notNullValue()); - assertThat("DSQualifier must have a Dataset", dsq1.getDataset(), notNullValue()); - assertThat("DSQualifier must have a DSDescriptor", dsq1.getDescriptor(), notNullValue()); - - DS loaded = dsService.loadDatasetByUuid(ds.getUuid()); - assertThat("Dataset must be loaded by UUID", loaded, notNullValue()); - assertThat("Dataset.qualifiers must not be null", loaded.getQualifiers(), notNullValue()); - assertThat("Dataset must have 1 DSQualifier", loaded.getQualifiers(), IsCollectionWithSize.hasSize(2)); - assertThat("Dataset must have 1 DSQualifier value", loaded.getQualifiers().get(0), notNullValue()); - assertThat("Dataset must have 1 DSQualifier with id", loaded.getQualifiers().get(0).getId(), notNullValue()); - - List rows = new ArrayList(); - for (int i = 0; i < 2; i++) { - Object[] row = new Object[4]; - row[0] = new Long(i); - row[1] = new Long(1000 + i); - - row[2] = new Double(2000 + i); - row[3] = new Double(3000 + i); - - rows.add(row); - rows.add(row); - } - dsService.updateRows(loaded, rows); - dsService.updateRows(loaded, rows); - - // - // DSRow dsRow = new DSRow(); - // dsRow.setDataset(ds); - // dsRowRepo.save(dsRow); - // - // DSRowQualifierLong dsrq1 = new DSRowQualifierLong(); - // dsrq1.setDatasetQualifier(dsq1); - // dsrq1.setRow(dsRow); - // dsrq1.setValue(100l + i); - // dsRowQualiRepo.save(dsrq1); - // - // DSRowQualifierLong dsrq2 = new DSRowQualifierLong(); - // dsrq2.setDatasetQualifier(dsq2); - // dsrq2.setRow(dsRow); - // dsrq2.setValue(1000l + i); - // dsRowQualiRepo.save(dsrq2); - // } - // - // for (DSRow dsrX : dsRowRepo.findAll()) { - // assertThat("Must have an id", dsrX.getId(), notNullValue()); - // assertThat("Must have a dataset", dsrX.getDataset(), notNullValue()); - // // assertThat("Must have row qualifiers", dsrX.getRowQualifiers(), - // // notNullValue()); - // } - // - // for (DSRowQualifier dsrqX : dsRowQualiRepo.findAll()) { - // assertThat("Must have an id", dsrqX.getId(), notNullValue()); - // assertThat("Must have a row", dsrqX.getRow(), notNullValue()); - // assertThat("Must have a value!", dsrqX.getValue(), notNullValue()); - // } - - } - - private DSDescriptor generateDescriptor(String code) { - DSDescriptor d = new DSDescriptor(); - d.setCode(code); - return d; - } - - private DS generateDataset() { - DS ds = new DS(); - ds.setColumns(new ArrayList()); - ds.setQualifiers(new ArrayList()); - return ds; - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/EMailServiceTest.java b/src/test/java/org/genesys2/server/service/impl/EMailServiceTest.java deleted file mode 100644 index db8e80bb4c13a6c37d4fc284884cac8190d517a5..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/EMailServiceTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.genesys2.server.service.impl; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class EMailServiceTest { - EMailServiceImpl emailService = new EMailServiceImpl(); - - @Test - public void testToEmailsSplit() { - String[] res = null; - res = emailService.toEmails(""); - assertTrue(res == null); - res = emailService.toEmails("test1"); - assertTrue(res != null); - assertTrue(res.length == 1); - assertTrue("test1".equals(res[0])); - - res = emailService.toEmails("test1,test2"); - assertTrue(res != null); - assertTrue(res.length == 2); - assertTrue("test1".equals(res[0])); - assertTrue("test2".equals(res[1])); - - res = emailService.toEmails("test1;test2"); - assertTrue(res != null); - assertTrue(res.length == 2); - assertTrue("test1".equals(res[0])); - assertTrue("test2".equals(res[1])); - - res = emailService.toEmails("test1 ; test2,test3 "); - assertTrue(res != null); - assertTrue(res.length == 3); - assertTrue("test1".equals(res[0])); - assertTrue("test2".equals(res[1])); - assertTrue("test3".equals(res[2])); - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/ElasticsearchTest.java b/src/test/java/org/genesys2/server/service/impl/ElasticsearchTest.java deleted file mode 100644 index 46b4a3153d36f423dc174cab0b101e22fa35590a..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/ElasticsearchTest.java +++ /dev/null @@ -1,473 +0,0 @@ -/** - * 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.genesys2.server.service.impl; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IQueue; - -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.VelocityException; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.model.elastic.AccessionDetails; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.model.impl.Organization; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.ElasticSearchManagementService; -import org.genesys2.server.service.ElasticService; -import org.genesys2.server.service.FilterConstants; -import org.genesys2.server.service.GenesysFilterService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.impl.FilterHandler.AppliedFilter; -import org.genesys2.server.service.impl.FilterHandler.AppliedFilters; -import org.genesys2.server.service.worker.ElasticUpdater; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.ElasticsearchConfig; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.elasticsearch.core.facet.result.Term; -import org.springframework.data.elasticsearch.core.facet.result.TermResult; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.ui.velocity.VelocityEngineFactoryBean; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ElasticsearchTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("cacher") -@Ignore -public class ElasticsearchTest { - private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchTest.class); - - @Import({ ElasticsearchConfig.class, JpaDataConfig.class, HazelcastConfig.class }) - @ComponentScan(basePackages = { "org.genesys2.server.persistence" }) - public static class Config { - - @Bean - public FilterHandler filterHadler() { - return new FilterHandler(); - } - - @Bean - public ElasticService searchService() { - return new ElasticsearchSearchServiceImpl(); - } - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } - - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public VelocityEngine velocityEngine() throws VelocityException, IOException { - final VelocityEngineFactoryBean vf = new VelocityEngineFactoryBean(); - return vf.createVelocityEngine(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public GenesysFilterService genesysFilterService() { - return new GenesysFilterServiceImpl(); - } - - @Bean - private TraitService traitService() { - return new TraitServiceImpl(); - } - - @Bean - public ElasticSearchManagementService elasticSearchManagementService() { - return new ElasticSearchManagementServiceImpl(); - } - - @Bean - public ElasticUpdater elasticUpdater() { - return new ElasticUpdater(); - } - - @Bean - public ElasticUpdater.ElasticNode elasticNode() { - return null; - } - - @Bean - public IQueue elasticRemoveQueue(HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-remove"); - } - - @Bean - public IQueue elasticUpdateQueue(HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-update"); - } - } - - @Autowired - private ObjectMapper mapper; - - @Autowired - private ElasticService elasticService; - - @Autowired - private OrganizationService organizationService; - - @Test - public void testzz() throws JsonProcessingException, SearchException { - Page a = elasticService.search("+acceNumb='PI 584950' +orgCty.iso3='THA' +taxonomy.genus=Vigna", new PageRequest(0, 10)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testInstituteCode() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.INSTCODE).addFilterValue(new FilterHandler.LiteralValueFilter("NGA039"))); - - LOG.info(mapper.writeValueAsString(filters)); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue("NGA039".equals(aa.getInstitute().getCode())); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testGenus() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.TAXONOMY_GENUS).addFilterValue(new FilterHandler.LiteralValueFilter("Vigna"))); - - LOG.info(mapper.writeValueAsString(filters)); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue("Vigna".equals(aa.getTaxonomy().getGenus())); - LOG.info(mapper.writeValueAsString(aa)); - } - - } - - @Test - public void testGenusAndSpecies() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.TAXONOMY_GENUS).addFilterValue(new FilterHandler.LiteralValueFilter("Vigna"))); - filters.add(new AppliedFilter().setFilterName(FilterConstants.TAXONOMY_SPECIES).addFilterValue(new FilterHandler.LiteralValueFilter("unguiculata"))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue("Vigna".equals(aa.getTaxonomy().getGenus())); - assertTrue("unguiculata".equals(aa.getTaxonomy().getSpecies())); - LOG.info(mapper.writeValueAsString(aa)); - } - - } - - @Test - public void testAcceNumb() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.ACCENUMB).addFilterValue(new FilterHandler.LiteralValueFilter("TVu-7268"))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue("TVu-7268".equals(aa.getAcceNumb())); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testAcceNumbStarts() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.ACCENUMB).addFilterValue(new FilterHandler.StartsWithFilter("ITC05"))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getAcceNumb().startsWith("ITC05")); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testAccenumb() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.ACCENUMB).addFilterValue(new FilterHandler.LiteralValueFilter("VI039981")) - .addFilterValue(new FilterHandler.LiteralValueFilter("VI039982"))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testAliases() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.ACCENUMB).addFilterValue(new FilterHandler.LiteralValueFilter("VI039981")) - .addFilterValue(new FilterHandler.LiteralValueFilter("VI039982"))); - filters.add(new AppliedFilter().setFilterName(FilterConstants.ALIAS).addFilterValue(new FilterHandler.LiteralValueFilter("TOT0956"))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testSampStat() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.SAMPSTAT).addFilterValue(new FilterHandler.LiteralValueFilter(110)) - .addFilterValue(new FilterHandler.LiteralValueFilter(120))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getSampStat() == 110 || aa.getSampStat() == 120); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testStorage() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.STORAGE).addFilterValue(new FilterHandler.LiteralValueFilter(30)) - .addFilterValue(new FilterHandler.LiteralValueFilter(40))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getStorage().contains(40) || aa.getStorage().contains(30)); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testStorageStats() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.STORAGE).addFilterValue(new FilterHandler.LiteralValueFilter(30)) - .addFilterValue(new FilterHandler.LiteralValueFilter(40))); - - LOG.info(filters.toString()); - TermResult termResult = elasticService.termStatistics(filters, FilterConstants.STORAGE, 3); - for (Term t : termResult.getTerms()) { - LOG.info("{} = {}", t.getTerm(), t.getCount()); - } - LOG.info("Other={}", termResult.getOtherCount()); - LOG.info("Missing={}", termResult.getMissingCount()); - LOG.info("Total={}", termResult.getTotalCount()); - } - - @Test - public void testAvailable() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.AVAILABLE).addFilterValue(new FilterHandler.LiteralValueFilter(true)) - .addFilterValue(null)); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total=", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getAvailable() == null || aa.getAvailable() == Boolean.TRUE); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testCollMissId() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.COLLMISSID).addFilterValue( - new FilterHandler.LiteralValueFilter("SDC-CLVNET GERMPLASM COLLECTING PROJECT"))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getColl().getCollMissId().equals("SDC-CLVNET GERMPLASM COLLECTING PROJECT")); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testSgsv() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.SGSV).addFilterValue(new FilterHandler.LiteralValueFilter(true))); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getSgsvDeposits() != null); - LOG.info(mapper.writeValueAsString(aa)); - } - - filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.SGSV).addFilterValue(new FilterHandler.LiteralValueFilter(false))); - - LOG.info(filters.toString()); - a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(aa.getSgsvDeposits() == null); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Test - public void testGeo() throws JsonProcessingException, IOException, SearchException { - // {"sgsv":[],"sampStat":[],"geo.latitude":[{"range":[-20,30]}]} - AppliedFilters filters = mapper - .readValue("{\"sgsv\":[],\"sampStat\":[],\"geo.latitude\":[{\"range\":[-20,30]},{\"max\":-50.1}]}", AppliedFilters.class); - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - // LOG.info(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(aa)); - LOG.info(mapper.writeValueAsString(aa)); - } - } - - @Ignore("We don't have organizations in the hsql db") - @Test - public void testOrganization() throws JsonProcessingException, SearchException { - AppliedFilters filters = new AppliedFilters(); - filters.add(new AppliedFilter().setFilterName(FilterConstants.INSTITUTE_NETWORK).addFilterValue(new FilterHandler.LiteralValueFilter("EURISCO"))); - - Set organizationInst = new HashSet(); - Organization org = organizationService.getOrganization("EURISCO"); - if (org != null) - for (FaoInstitute institue : organizationService.getMembers(org)) { - organizationInst.add(institue.getCode()); - } - - LOG.info(filters.toString()); - Page a = elasticService.filter(filters, new PageRequest(0, 100)); - LOG.info("Size: {} total={}", a.getNumberOfElements(), a.getTotalElements()); - for (AccessionDetails aa : a.getContent()) { - assertTrue(organizationInst.contains(aa.getInstitute().getCode())); - LOG.info(mapper.writeValueAsString(aa)); - } - } - -} diff --git a/src/test/java/org/genesys2/server/service/impl/GenesysServicesTest.java b/src/test/java/org/genesys2/server/service/impl/GenesysServicesTest.java deleted file mode 100644 index e985afbccb5bd775079729c8b028ff13b4ee31b2..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/GenesysServicesTest.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Copyright 2016 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.genesys2.server.service.impl; - -import java.io.File; -import java.util.Set; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IQueue; - -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.velocity.app.VelocityEngine; -import org.elasticsearch.common.collect.Sets; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.security.persistence.AclClassPersistence; -import org.genesys.blocks.security.persistence.AclEntryPersistence; -import org.genesys.blocks.security.persistence.AclObjectIdentityPersistence; -import org.genesys.blocks.security.persistence.AclSidPersistence; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.PasswordPolicy; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys.blocks.security.service.impl.SimplePasswordPolicy; -import org.genesys.filerepository.service.BytesStorageService; -import org.genesys.filerepository.service.ImageGalleryService; -import org.genesys.filerepository.service.RepositoryService; -import org.genesys.filerepository.service.ThumbnailGenerator; -import org.genesys.filerepository.service.impl.FilesystemStorageServiceImpl; -import org.genesys.filerepository.service.impl.ImageGalleryServiceImpl; -import org.genesys.filerepository.service.impl.RepositoryServiceImpl; -import org.genesys.filerepository.service.impl.ThumbnailGenerator1; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.aspect.GenesysImageGalleryAspects; -import org.genesys2.server.persistence.AccessionHistoricRepository; -import org.genesys2.server.persistence.AccessionRepository; -import org.genesys2.server.persistence.ArticleRepository; -import org.genesys2.server.persistence.CountryRepository; -import org.genesys2.server.persistence.CropRepository; -import org.genesys2.server.persistence.CropRuleRepository; -import org.genesys2.server.persistence.FaoInstituteRepository; -import org.genesys2.server.persistence.FaoInstituteSettingRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepositoryCustomImpl; -import org.genesys2.server.persistence.MaterialRequestRepository; -import org.genesys2.server.persistence.MaterialSubRequestRepository; -import org.genesys2.server.persistence.MetadataMethodRepository; -import org.genesys2.server.persistence.MetadataRepository; -import org.genesys2.server.persistence.MethodRepository; -import org.genesys2.server.persistence.OrganizationRepository; -import org.genesys2.server.persistence.ParameterCategoryRepository; -import org.genesys2.server.persistence.ParameterRepository; -import org.genesys2.server.persistence.Taxonomy2Repository; -import org.genesys2.server.persistence.TeamRepository; -import org.genesys2.server.persistence.TraitValueRepository; -import org.genesys2.server.persistence.TraitValueRepositoryImpl; -import org.genesys2.server.persistence.UserRepository; -import org.genesys2.server.persistence.domain.mock.TraitServiceMock; -import org.genesys2.server.persistence.kpi.KPIParameterRepository; -import org.genesys2.server.persistence.kpi.ObservationRepository; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.DatasetService; -import org.genesys2.server.service.EMailService; -import org.genesys2.server.service.EMailVerificationService; -import org.genesys2.server.service.EasySMTA; -import org.genesys2.server.service.ElasticSearchManagementService; -import org.genesys2.server.service.ElasticService; -import org.genesys2.server.service.GenesysFilterService; -import org.genesys2.server.service.GenesysRESTService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoRegionService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteFilesService; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.KPIService; -import org.genesys2.server.service.MappingService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.RequestService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.TeamService; -import org.genesys2.server.service.TokenVerificationService; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.worker.ElasticUpdater; -import org.genesys2.server.service.worker.GeoRegionDataCLDR; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.tests.BaseSpringTest; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.HierarchyMode; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.ContextHierarchy; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextHierarchy(@ContextConfiguration(name = "servicesTest", classes = { GenesysServicesTest.Config.class }, initializers = PropertyPlacholderInitializer.class)) -@EnableAspectJAutoProxy -@ActiveProfiles("dev") -public abstract class GenesysServicesTest extends BaseSpringTest { - - @Configuration - @EnableAspectJAutoProxy - @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL, classMode = DirtiesContext.ClassMode.AFTER_CLASS) - public static class Config { - - @Bean - public GenesysImageGalleryAspects imageGalleryAspects() { - // This thing makes galleries auto-fill with images - return new GenesysImageGalleryAspects(); - } - - @Bean - public InstituteFilesService instituteFilesService() { - return new InstituteFilesServiceImpl(); - } - - @Bean - public RepositoryService repositoryService() { - return new RepositoryServiceImpl(); - } - - @Bean - public ImageGalleryService imageGalleryService() { - return new ImageGalleryServiceImpl(); - } - - @Bean - public ThumbnailGenerator thumbnailGenerator() { - return new ThumbnailGenerator1(); - } - - @Bean - public BytesStorageService bytesStorageService() { - FilesystemStorageServiceImpl fsss = new FilesystemStorageServiceImpl(); - fsss.setRepositoryBaseDirectory(new File("data/repository")); - return fsss; - } - - @Bean - public RequestService requestService() { - return new RequestServiceImpl(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public GeoRegionService geoRegionService() { - return new GeoRegionServiceImpl(); - } - - @Bean - public GeoRegionDataCLDR geoRegionDataCldr() { - return new GeoRegionDataCLDR(); - } - - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public PasswordPolicy passwordPolicy() { - return new SimplePasswordPolicy(); - } - - @Bean - public TeamService teamService() { - return new TeamServiceImpl(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public VelocityEngine velocityEngine() { - return new VelocityEngine(); - } - - @Bean - @Qualifier("genesysLowlevelRepositoryCustomImpl") - public GenesysLowlevelRepository genesysLowlevelRepositoryCustomImpl() { - return new GenesysLowlevelRepositoryCustomImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public EMailVerificationService emailVerificationService() { - return new EMailVerificationServiceImpl(); - } - - @Bean - public TokenVerificationService tokenVerificationService() { - return new TokenVerificationServiceImpl(); - } - - @Bean - public EMailService eMailService() { - return new EMailServiceImpl(); - } - - @Bean - public JavaMailSender mailSender() { - return Mockito.mock(JavaMailSenderImpl.class); - } - - @Bean - public ThreadPoolTaskExecutor threadPoolTaskExecutor() { - return new ThreadPoolTaskExecutor(); - } - - @Bean - public TraitService traitServiceMock() { - return new TraitServiceMock(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean(name = "filesMetadataInfo") - public FilesMetadataInfo filesMetadataInfo(){ - return new FilesMetadataInfo(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public TraitValueRepository traitValueRepository() { - return new TraitValueRepositoryImpl(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public TaxonomyManager taxonomyManager() { - return new TaxonomyManager(); - } - - @Bean - public EasySMTA easySMTAConnector() { - return new EasySMTAMockConnector(); - } - - @Bean - public HttpClientBuilder httpClientBuilder() { - return HttpClientBuilder.create(); - } - - @Bean - public KPIService kpiService() { - return new KPIServiceImpl(); - } - - @Bean - public DatasetService datasetService() { - return new GenesysServiceImpl(); - } - - @Bean - public MappingService mappingService() { - return new MappingServiceImpl(); - } - - @Bean - public GenesysFilterService genesysFilterService() { - return new GenesysFilterServiceImpl(); - } - - @Bean - public GenesysRESTService genesysRESTService() { - return new GenesysRESTServiceImpl(); - } - - @Bean - public ElasticService elasticService() { - return new ElasticsearchSearchServiceImpl(); - } - - @Bean - public FilterHandler filterHandler() { - return new FilterHandler(); - } - - @Bean - public Jackson2ObjectMapperFactoryBean objectMapper() { - final Jackson2ObjectMapperFactoryBean mapperFactoryBean = new Jackson2ObjectMapperFactoryBean(); - mapperFactoryBean.setFeaturesToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - return mapperFactoryBean; - } - - @Bean - public ElasticSearchManagementService elasticSearchManagementService() { - return new ElasticSearchManagementServiceImpl(); - } - - @Bean - public ElasticUpdater elasticUpdater() { - return new ElasticUpdater(); - } - - @Bean - public ElasticUpdater.ElasticNode elasticNode() { - return null; - } - - @Bean - public IQueue elasticRemoveQueue(HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-remove"); - } - - @Bean - public IQueue elasticUpdateQueue(HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-update"); - } - - @Bean - public static Set supportedLocales() { - final Set supportedLocales = Sets.newHashSet("en", "es", "de", "fr", "fa", "ar", "ru", "zh", "pt"); - return supportedLocales; - } - } - - @Autowired - protected AccessionHistoricRepository accessionHistoricRepository; - - @Autowired - protected CropRuleRepository cropRuleRepository; - - @Autowired - protected TaxonomyService taxonomyService; - - @Autowired - protected Taxonomy2Repository taxonomy2Repository; - - @Autowired - protected MetadataMethodRepository metadataMethodRepository; - - @Autowired - protected MetadataRepository metadataRepository; - - @Autowired - protected DatasetService datasetService; - - @Autowired - protected ObservationRepository observationRepository; - - @Autowired - protected KPIParameterRepository kpiParameterRepository; - - @Autowired - protected KPIService kpiService; - - @Autowired - protected EasySMTA easySMTAConnector; - - @Autowired - protected JavaMailSender mailSender; - - @Autowired - protected AccessionRepository accessionRepository; - - @Autowired - protected GeoService geoService; - - @Autowired - protected CountryRepository countryRepository; - - @Autowired - protected FaoInstituteRepository instituteRepository; - - @Autowired - protected Taxonomy2Repository taxonomyRepository; - - @Autowired - protected FaoInstituteSettingRepository instituteSettingRepository; - - @Autowired - protected MethodRepository methodRepository; - - @Autowired - protected @Qualifier("traitServiceMock") TraitService traitService; - - @Autowired - protected ArticleRepository articleRepository; - - @Autowired - protected ContentService contentService; - - @Autowired - protected JavaMailSender javaMailSender; - - @Autowired - protected UserService userService; - - @Autowired - protected UserRepository userPersistence; - - @Autowired - protected InstituteService instituteService; - - @Autowired - protected TeamRepository teamRepository; - - @Autowired - protected CustomAclService aclService; - - @Autowired - protected AclSidPersistence aclSidPersistence; - - @Autowired - protected AclEntryPersistence aclEntryPersistence; - - @Autowired - protected AclObjectIdentityPersistence aclObjectIdentityPersistence; - - @Autowired - protected AclClassPersistence aclClassPersistence; - - @Autowired - protected TeamService teamService; - - @Autowired - protected GenesysService genesysService; - - @Autowired - protected CropService cropService; - - @Autowired - protected CropRepository cropRepository; - - @Autowired - protected ParameterRepository parameterRepository; - - @Autowired - protected ParameterCategoryRepository parameterCategoryRepository; - - @Autowired - protected OrganizationService organizationService; - - @Autowired - protected OrganizationRepository organizationRepository; - - @Autowired - protected RequestService requestService; - - @Autowired - protected MaterialRequestRepository materialRequestRepository; - - @Autowired - protected MaterialSubRequestRepository materialSubRequestRepository; -} diff --git a/src/test/java/org/genesys2/server/service/impl/KPIEntitiesTest.java b/src/test/java/org/genesys2/server/service/impl/KPIEntitiesTest.java deleted file mode 100644 index cb9bb43d8adea96a7b36ffa683b3710e3519789d..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/KPIEntitiesTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/** - * 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.genesys2.server.service.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; -import org.genesys2.server.model.kpi.BooleanDimension; -import org.genesys2.server.model.kpi.Dimension; -import org.genesys2.server.model.kpi.DimensionKey; -import org.genesys2.server.model.kpi.Execution; -import org.genesys2.server.model.kpi.ExecutionDimension; -import org.genesys2.server.model.kpi.ExecutionRun; -import org.genesys2.server.model.kpi.JpaDimension; -import org.genesys2.server.model.kpi.KPIParameter; -import org.genesys2.server.model.kpi.NumericListDimension; -import org.genesys2.server.model.kpi.Observation; -import org.genesys2.server.model.kpi.StringListDimension; -import org.genesys2.server.persistence.kpi.DimensionKeyRepository; -import org.genesys2.server.service.KPIService; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = KPIEntitiesTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class KPIEntitiesTest { - private static Logger LOG = LoggerFactory.getLogger(KPIEntitiesTest.class); - - @Import({ HazelcastConfig.class, JpaDataConfig.class }) - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public KPIService kpiService() { - return new KPIServiceImpl(); - } - } - - @Autowired - private KPIService kpiService; - @Autowired - private DimensionKeyRepository dimensionKeyRepository; - - @Test - public void persistStringListDimension() { - StringListDimension dimInstCode = new StringListDimension(); - dimInstCode.setTitle("Holding institute code"); - dimInstCode.setName("instCode"); - Set list = new HashSet(); - list.add("NGA039"); - list.add("PHL001"); - list.add("MEX002"); - list.add("SYR002"); - dimInstCode.setValues(list); - LOG.debug(String.valueOf(dimInstCode.getValues())); - Dimension savedDim = kpiService.save(dimInstCode); - assertTrue(savedDim == dimInstCode); - assertTrue(savedDim.getId() != null); - - Dimension loaded = kpiService.getDimension(savedDim.getId()); - assertTrue(loaded != savedDim); - assertTrue(StringUtils.equals(loaded.getName(), dimInstCode.getName())); - assertTrue(StringUtils.equals(loaded.getTitle(), dimInstCode.getTitle())); - assertTrue(loaded instanceof StringListDimension); - LOG.debug(String.valueOf(loaded.getValues())); - assertTrue(loaded.getValues().containsAll(list)); - assertTrue(list.containsAll(loaded.getValues())); - } - - @Test - public void persistNumericListDimension() { - NumericListDimension dimNum = new NumericListDimension(); - dimNum.setTitle("Biological status of sample"); - dimNum.setName("sampStat"); - dimNum.setClazz(Long.class); - Set list = new HashSet(); - list.add(1l); - list.add(2l); - list.add(3l); - list.add(4l); - dimNum.setValues(list); - LOG.debug(String.valueOf(dimNum.getValues())); - Dimension savedDim = kpiService.save(dimNum); - assertTrue(savedDim == dimNum); - assertTrue(savedDim.getId() != null); - - Dimension loaded = kpiService.getDimension(savedDim.getId()); - assertTrue(loaded != savedDim); - assertTrue(StringUtils.equals(loaded.getName(), dimNum.getName())); - assertTrue(StringUtils.equals(loaded.getTitle(), dimNum.getTitle())); - assertTrue(loaded instanceof NumericListDimension); - LOG.debug(String.valueOf(loaded.getValues())); - NumericListDimension nl = (NumericListDimension) loaded; - LOG.debug(String.valueOf(nl.getClazz())); - assertTrue(nl.getClazz() == Long.class); - assertTrue(loaded.getValues().containsAll(list)); - assertTrue(list.containsAll(loaded.getValues())); - } - - @Test - public void persistBooleanListDimension() { - BooleanDimension dim = new BooleanDimension(); - dim.setTitle("Yes/No dimension"); - dim.setName("boolean"); - assertTrue(dim.hasFalse()); - assertTrue(dim.hasTrue()); - LOG.debug(String.valueOf(dim.getValues())); - - dim.useFalse(false); - assertFalse(dim.hasFalse()); - assertTrue(dim.hasTrue()); - dim.useTrue(false); - assertFalse(dim.hasFalse()); - assertFalse(dim.hasTrue()); - dim.setMode(3); - assertTrue(dim.hasTrue()); - assertTrue(dim.hasFalse()); - - Dimension savedDim = kpiService.save(dim); - assertTrue(savedDim == dim); - assertTrue(savedDim.getId() != null); - - // For comparison - Set list = new HashSet(); - list.add(true); - list.add(false); - - Dimension loaded = kpiService.getDimension(savedDim.getId()); - assertTrue(loaded != savedDim); - assertTrue(StringUtils.equals(loaded.getName(), dim.getName())); - assertTrue(StringUtils.equals(loaded.getTitle(), dim.getTitle())); - assertTrue(loaded instanceof BooleanDimension); - LOG.debug(String.valueOf(loaded.getValues())); - assertTrue(loaded.getValues().containsAll(list)); - assertTrue(list.containsAll(loaded.getValues())); - } - - @Test - public void persistJpaDimension() { - JpaDimension dimJpa = new JpaDimension(); - dimJpa.setTitle("Example JPA Entity#field dimension"); - dimJpa.setName("jpadimension"); - dimJpa.setEntity("Dimension"); - dimJpa.setField("name"); - dimJpa.setCondition("version > -1"); - - Dimension savedDim = kpiService.save(dimJpa); - assertTrue(savedDim == dimJpa); - assertTrue(savedDim.getId() != null); - - Dimension loaded = kpiService.getDimension(savedDim.getId()); - assertTrue(loaded != savedDim); - assertTrue(StringUtils.equals(loaded.getName(), dimJpa.getName())); - assertTrue(StringUtils.equals(loaded.getTitle(), dimJpa.getTitle())); - assertTrue(loaded instanceof JpaDimension); - JpaDimension loadedJpa = (JpaDimension) loaded; - assertTrue(StringUtils.equals(loadedJpa.getEntity(), dimJpa.getEntity())); - assertTrue(StringUtils.equals(loadedJpa.getField(), dimJpa.getField())); - - try { - loadedJpa.getValues(); - fail("JpaDimension#getValues() must throw RuntimeException"); - } catch (RuntimeException e) { - } - - Set values = kpiService.getValues(loadedJpa); - LOG.info(String.valueOf(values)); - assertTrue(values.contains("jpadimension")); - } - - @Test - public void persistParameter() { - KPIParameter parameter = new KPIParameter(); - parameter.setTitle("KPI Dimensions"); - parameter.setDescription("Total number of KPI Dimensions defined"); - parameter.setName("dimension.count." + System.currentTimeMillis()); - parameter.setEntity("Dimension"); - - KPIParameter persisted = kpiService.save(parameter); - assertTrue(persisted.getId() != null); - - KPIParameter loaded = kpiService.getParameter(parameter.getName()); - assertTrue(loaded != null); - assertTrue(loaded != parameter); - assertTrue(StringUtils.equals(loaded.getName(), parameter.getName())); - assertTrue(StringUtils.equals(loaded.getTitle(), parameter.getTitle())); - assertTrue(StringUtils.equals(loaded.getEntity(), parameter.getEntity())); - assertTrue(StringUtils.equals(loaded.getDescription(), parameter.getDescription())); - - KPIParameter parameter2 = new KPIParameter(); - parameter2.setTitle("KPI Dimensions 2"); - parameter2.setDescription("Total number of KPI Dimensions defined "); - parameter2.setName("dimension.count"); - try { - kpiService.save(parameter2); - fail("KPIService should not allow duplicate parameter names!"); - } catch (DataIntegrityViolationException e) { - // All good! - } - - // drop it - kpiService.delete(loaded); - } - - @Test - public void persistExecution() { - KPIParameter parameter = new KPIParameter(); - parameter.setTitle("KPI Dimensions"); - parameter.setDescription("Total number of KPI Dimensions defined"); - parameter.setName("dimension.count"); - parameter.setEntity("Dimension"); - kpiService.save(parameter); - - NumericListDimension dimVersion = new NumericListDimension(); - dimVersion.setClazz(Long.class); - dimVersion.setName("version"); - dimVersion.setTitle("Version numbers"); - Set list = new HashSet(); - list.add(0l); - list.add(1l); - list.add(2l); - dimVersion.setValues(list); - for (Number n : dimVersion.getValues()) { - assertTrue(n instanceof Long); - } - kpiService.save(dimVersion); - - Execution execution = new Execution(); - execution.setName("foobar"); - execution.setParameter(parameter); - execution.addDimension(dimVersion, null, "version"); - - String paQuery = execution.query(); - LOG.info("Query = {}", paQuery); - - kpiService.save(execution); - - Execution execution2 = new Execution(); - execution2.setName("versionexec"); - execution2.setParameter(parameter); - execution2.addDimension(dimVersion, null, "version"); - kpiService.save(execution2); - - Execution loaded = kpiService.getExecution(execution.getId()); - for (ExecutionDimension d : loaded.getExecutionDimensions()) { - LOG.debug("ED = {}", d); - } - assertEquals(loaded.getParameter().getId(), parameter.getId()); - assertTrue(loaded.getExecutionDimensions().size() == execution.getExecutionDimensions().size()); - - List observations = kpiService.execute(execution); - for (Observation obs : observations) { - LOG.info(String.valueOf(obs)); - } - - List observations2 = kpiService.execute(execution); - for (Observation obs : observations2) { - LOG.info(String.valueOf(obs)); - } - - kpiService.save(execution, observations); - kpiService.save(execution2, observations2); - - // Let's check DimensionKey - List dks = dimensionKeyRepository.findAll(); - for (DimensionKey dk : dks) { - LOG.info("DK={}", dk); - } - - // drop it - LOG.info("DELETING!!!!"); - ExecutionRun executionRun = kpiService.findLastExecutionRun(execution); - kpiService.deleteObservations(executionRun); - kpiService.delete(execution); - - // Let's check DimensionKey again - dks = dimensionKeyRepository.findAll(); - for (DimensionKey dk : dks) { - LOG.info("DK={}", dk); - } - - ExecutionRun executionRun2 = kpiService.findLastExecutionRun(execution2); - kpiService.deleteObservations(executionRun2); - kpiService.delete(execution2); - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/KPIServiceTest.java b/src/test/java/org/genesys2/server/service/impl/KPIServiceTest.java deleted file mode 100644 index ea91345f4a1c52a2c17b3ab920c64c26c20820be..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/KPIServiceTest.java +++ /dev/null @@ -1,255 +0,0 @@ -/** - * 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.genesys2.server.service.impl; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.genesys2.server.model.kpi.BooleanDimension; -import org.genesys2.server.model.kpi.Dimension; -import org.genesys2.server.model.kpi.DimensionKey; -import org.genesys2.server.model.kpi.Execution; -import org.genesys2.server.model.kpi.KPIParameter; -import org.genesys2.server.model.kpi.NumericListDimension; -import org.genesys2.server.model.kpi.Observation; -import org.genesys2.server.model.kpi.StringListDimension; -import org.genesys2.server.service.KPIService; -import org.genesys2.server.test.JpaRealDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = KPIServiceTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class KPIServiceTest { - private static Logger LOG = LoggerFactory.getLogger(KPIService.class); - - @Import({ HazelcastConfig.class, JpaRealDataConfig.class }) - @ComponentScan(basePackages = { "org.genesys2.server.persistence" }) - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public KPIService kpiService() { - return new KPIServiceImpl(); - } - } - - @Autowired - private KPIService kpiService; - - @Test - public void testzz() { - LOG.info("Test 1"); - - Object res = null; - res = kpiService - .getSingleResult( - "select count(distinct _base) from Accession _base inner join _base.institute _ped1 where (10 member of _base.stoRage) and ( _ped1.code = ?1 )", - "HUN003"); - printRes(res); - } - - @Test - public void test1() { - LOG.info("Test 1"); - - Object res = null; - res = kpiService.getSingleResult("select count(a) from Accession a where a.mlsStatus=?1", true); - printRes(res); - - res = kpiService.getSingleResult("select count(a) from Accession a inner join a.institute i where a.mlsStatus=?1 and i.code=?2", true, "NGA039"); - printRes(res); - - List instlist = new ArrayList(); - instlist.add("NGA039"); - instlist.add("PHL001"); - res = kpiService.getSingleResult("select count(a) from Accession a inner join a.institute i where a.mlsStatus=?1 and i.code in ( ?2 )", true, instlist); - printRes(res); - - res = kpiService.getSingleResult("select count(a) from Accession a where ?1 in elements(a.stoRage)", 10); - printRes(res); - List storagelist = new ArrayList(); - storagelist.add(10); - storagelist.add(11); - storagelist.add(30); - res = kpiService.getSingleResult("select count(distinct a) from Accession a inner join a.stoRage st where st in ( ?1 )", storagelist); - printRes(res); - - res = kpiService.getSingleResult( - "select count(distinct a) from Accession a inner join a.institute _ped1 where ( _ped1.code = ?1 ) and ( a.sampleStatus = ?2 )", "NGA039", 110); - printRes(res); - - res = kpiService - .getSingleResult( - "select count(distinct a) from Accession a inner join a.institute _ped1 inner join a.taxonomy.cropTaxonomies _ped3 where ( _ped1.code = ?1 ) and ( a.sampleStatus = ?2 ) and ( _ped3.crop.shortName = ?3 )", - "NGA039", 110, "banana"); - printRes(res); - } - - private void printRes(Object res) { - if (res != null) - LOG.info("Result={} {}", res, res.getClass()); - else - LOG.info("Result is null"); - } - - @Test - public void test2() { - StringListDimension dimInstCode = new StringListDimension(); - dimInstCode.setTitle("Holding institute code"); - dimInstCode.setName("instCode"); - Set instlist = new HashSet(); - instlist.add("NGA039"); - instlist.add("PHL001"); - instlist.add("MEX002"); - instlist.add("SYR002"); - dimInstCode.setValues(instlist); - - NumericListDimension dimSampStat = new NumericListDimension(); - dimSampStat.setTitle("Biological status of accession"); - dimSampStat.setName("sampleStatus"); - Set samplist = new HashSet(); - samplist.add(100); - samplist.add(110); - samplist.add(120); - dimSampStat.setValues(samplist); - - StringListDimension dimCrop = new StringListDimension(); - dimCrop.setTitle("Crop name"); - dimCrop.setName("crop"); - Set croplist = new HashSet(); - croplist.add("banana"); - croplist.add("wheat"); - croplist.add("maize"); - croplist.add("rice"); - dimCrop.setValues(croplist); - - KPIParameter accessionCount = new KPIParameter(); - accessionCount.setName("accession.count"); - accessionCount.setEntity("Accession"); - - Execution paramExec = new Execution(); - paramExec.setName("foobar"); - paramExec.setParameter(accessionCount); - paramExec.addDimension(dimInstCode, "institute", "code"); - paramExec.addDimension(dimSampStat, null, "sampleStatus"); - paramExec.addDimension(dimCrop, "taxonomy.cropTaxonomies", "crop.shortName"); - - String paQuery = paramExec.query(); - LOG.info("Query = {}", paQuery); - - execute(paQuery, paramExec, 0, new ArrayList()); - } - - @Test - public void testAccessionsInMLS() { - StringListDimension dimInstCode = new StringListDimension(); - dimInstCode.setTitle("Holding institute code"); - dimInstCode.setName("instCode"); - Set instlist = new HashSet(); - instlist.add("NGA039"); - instlist.add("PHL001"); - instlist.add("AUT007"); - instlist.add("MEX002"); - instlist.add("SYR002"); - dimInstCode.setValues(instlist); - - BooleanDimension dimBoolean = new BooleanDimension(); - dimBoolean.setTitle("Yes/No values"); - dimBoolean.setName("bool"); - - KPIParameter accessionsInMls = new KPIParameter(); - accessionsInMls.setName("accession.mls"); - accessionsInMls.setEntity("Accession"); - - Execution paramExec = new Execution(); - paramExec.setParameter(accessionsInMls); - paramExec.addDimension(dimInstCode, "institute", "code"); - paramExec.addDimension(dimBoolean, null, "mlsStatus"); - - String paQuery = paramExec.query(); - LOG.info("Query = {}", paQuery); - - execute(paQuery, paramExec, 0, new ArrayList()); - } - - private void execute(String paQuery, Execution paramExec, int depth, List params) { - Dimension dim = paramExec.getDimension(depth); - if (dim == null) { - // execute - LOG.info("Executing: {} params={}", paQuery, params); - if (kpiService != null) { - Object res = kpiService.getSingleResult(paQuery, params.toArray()); - printRes(res, paramExec, params.toArray()); - } - } else { - // Recurse - for (Object val : dim.getValues()) { - params.add(val); - execute(paQuery, paramExec, depth + 1, params); - params.remove(depth); - } - } - } - - private void printRes(Object res, Execution paramExec, Object[] array) { - LOG.info("Reporting result\n\n"); - KPIParameter kPIParameter = paramExec.getParameter(); - if (res != null) - LOG.info("{}={} {}", kPIParameter.getName(), res, res.getClass()); - else { - LOG.warn("{} has no result (null)", kPIParameter.getName()); - return; - } - - Observation observation = new Observation(); - observation.setValue((Long) res); - for (int i = 0; i < array.length; i++) { - DimensionKey dk = new DimensionKey(); - dk.setName(paramExec.getDimension(i).getName()); - dk.setValue(array[i].toString()); - LOG.info("\t\t {}", dk); - - observation.getDimensions().add(dk); - } - LOG.info("OBSERVATION: {}", observation); - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/WorldClimUpdaterDummyTest.java b/src/test/java/org/genesys2/server/service/impl/WorldClimUpdaterDummyTest.java deleted file mode 100644 index 668239eef5733c78501ed965faa56c57ccaca509..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/WorldClimUpdaterDummyTest.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.genesys2.server.service.impl; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.CoreMatchers.*; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.apache.http.impl.client.HttpClientBuilder; -import org.genesys.worldclim.grid.generic.GenericGridFile; -import org.genesys.worldclim.grid.generic.GenericGridZipFile; -import org.genesys.worldclim.grid.generic.Header; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepositoryCustomImpl; -import org.genesys2.server.service.worker.WorldClimUpdater; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WorldClimUpdaterDummyTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class WorldClimUpdaterDummyTest { - - @Import({ HazelcastConfig.class, JpaDataConfig.class }) - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public WorldClimUpdater worldClimUpdater() { - return new WorldClimUpdater(); - } - - @Bean - public GenesysLowlevelRepository genesysLowlevel() { - return new GenesysLowlevelRepositoryCustomImpl(); - } - } - - @Autowired - private WorldClimUpdater worldClimUpdater; - - @Value("${download.files.dir}") - private String downloadDir; - - @Test - public void testDownloadAlt() throws IOException { - File tempArchive = worldClimUpdater.download("alt_2-5m_bil.zip"); - File destination = new File(downloadDir, "worldclim-alt-temp"); - assertThat("Destination folder must not exist", destination.exists(), is(Boolean.FALSE)); - destination.mkdirs(); - assertThat("Destination folder must exist", destination.exists(), is(Boolean.TRUE)); - assertThat("Destination folder must be a directory", destination.isDirectory(), is(Boolean.TRUE)); - - try { - List files = GenericGridZipFile.unzip(tempArchive, destination); - for (File file : files) { - System.out.println("Unzipped " + file.getAbsolutePath()); - file.delete(); - } - } finally { - tempArchive.delete(); - destination.delete(); - } - } - - @Test - public void testDownloadAltKeep() throws IOException { - File destination = new File(downloadDir, "worldclim-data"); - destination.mkdirs(); - assertThat("Destination folder must exist", destination.exists(), is(Boolean.TRUE)); - assertThat("Destination folder must be a directory", destination.isDirectory(), is(Boolean.TRUE)); - - String[] altFiles = destination.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.startsWith("alt") && (name.endsWith(".bil") || name.endsWith(".hdr")); - } - }); - - if (altFiles == null || altFiles.length == 0) { - System.out.println("Must download"); - List files = worldClimUpdater.downloadAndExtract(destination, "alt_2-5m_bil.zip"); - for (File file : files) { - System.out.println("Unzipped " + file.getAbsolutePath()); - } - } else { - System.out.println("Files are there"); - } - - GenericGridFile ggf = new GenericGridFile(destination, "alt"); - Header header = ggf.readHeader(); - - int varSize = header.getBits() / 8; - ByteBuffer byteBuffer = header.createByteBuffer(); - FileChannel dataChannel = null; - try { - dataChannel = ggf.getDataFileStream().getChannel(); - - for (int i = header.getColumns() - 1; i >= 0; i--) { - dataChannel.read(byteBuffer, i * varSize); - assertThat("Value will be read!", byteBuffer.getShort(0), notNullValue()); - } - } finally { - IOUtils.closeQuietly(dataChannel); - } - } - - @Test - public void testUpdateAltitude() throws IOException { - File destination = new File(downloadDir, "worldclim-data"); - destination.mkdirs(); - assertThat("Destination folder must exist", destination.exists(), is(Boolean.TRUE)); - assertThat("Destination folder must be a directory", destination.isDirectory(), is(Boolean.TRUE)); - - String[] altFiles = destination.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.startsWith("alt") && (name.endsWith(".bil") || name.endsWith(".hdr")); - } - }); - - if (altFiles == null || altFiles.length == 0) { - System.out.println("Must download"); - List files = worldClimUpdater.downloadAndExtract(destination, "alt_2-5m_bil.zip"); - for (File file : files) { - System.out.println("Unzipped " + file.getAbsolutePath()); - } - } else { - System.out.println("Files are there"); - } - - GenericGridFile ggf = new GenericGridFile(destination, "alt"); - Header header = ggf.readHeader(); - - short nullValue = (short) header.getNoDataValue(); - MappedByteBuffer x = ggf.mapDataBuffer(); - for (int i = 0; i < header.getColumns(); i++) { - System.out.println(x.getShort(i * 2)); - assertThat("Value will be read!", x.getShort(i * 2), notNullValue()); - assertThat("Value will be -9999", x.getShort(i * 2), is(nullValue)); - } - } -} diff --git a/src/test/java/org/genesys2/server/service/impl/WorldClimUpdaterTest.java b/src/test/java/org/genesys2/server/service/impl/WorldClimUpdaterTest.java deleted file mode 100644 index 152ca5f4aa4a0f9152eac28a342a002079507508..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/impl/WorldClimUpdaterTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.genesys2.server.service.impl; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.spring.cache.HazelcastCacheManager; - -import org.genesys2.server.model.dataset.DS; -import org.genesys2.server.model.dataset.DSColumn; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepositoryCustomImpl; -import org.genesys2.server.service.DSService; -import org.genesys2.server.service.DescriptorService; -import org.genesys2.server.service.worker.WorldClimUpdater; -import org.genesys2.server.test.JpaRealDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.HazelcastConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WorldClimUpdaterTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@ActiveProfiles("dev") -@Ignore -public class WorldClimUpdaterTest { - - @Import({ HazelcastConfig.class, JpaRealDataConfig.class }) - public static class Config { - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public WorldClimUpdater worldClimUpdater() { - return new WorldClimUpdater(); - } - - @Bean - public DSService dsService() { - return new DSServiceImpl(); - } - - @Bean - public DescriptorService descriptorService() { - return new DescriptorServiceImpl(); - } - - @Bean - public GenesysLowlevelRepository genesysLowlevel() { - return new GenesysLowlevelRepositoryCustomImpl(); - } - - } - - @Autowired - private WorldClimUpdater worldClimUpdater; - - @Autowired - private DSService dsService; - - @Test - public void testUpdateAlt() throws IOException { - worldClimUpdater.update("alt"); - - for (int i = 1; i <= 12; i++) { - worldClimUpdater.update("tmin" + i); - worldClimUpdater.update("tmax" + i); - worldClimUpdater.update("tmean" + i); - worldClimUpdater.update("prec" + i); - } - - for (int i = 1; i <= 19; i++) { - worldClimUpdater.update("bio" + i); - } - } - - @Test - public void deleteDataset() { - DS ds = dsService.loadDatasetByUuid(WorldClimUpdater.WORLDCLIM_DATASET); - if (ds != null) { - for (DSColumn dsd : ds.getColumns()) { - dsService.deleteDescriptor(dsd); - } - dsService.deleteRows(ds); - dsService.deleteDataset(ds); - } - } - - @Test - public void testDownload() throws IOException { - DS ds = dsService.loadDatasetByUuid(WorldClimUpdater.WORLDCLIM_DATASET); - File file = new File("worldclim " + System.currentTimeMillis() + ".xls"); - BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); - dsService.download(ds, fos); - fos.flush(); - fos.close(); - // file.delete(); - } - - @Test - public void testDownloadDesc() throws IOException { - DS ds = dsService.loadDatasetByUuid(WorldClimUpdater.WORLDCLIM_DATASET); - List dsds = new ArrayList(); - for (DSColumn dsd : ds.getColumns()) { - if (dsd.getDescriptor().getCode().startsWith("tmin")) { - dsds.add(dsd); - } - } - System.out.println("Downloading tmin data: " + dsds.size()); - - File file = new File("worldclim " + System.currentTimeMillis() + ".xls"); - BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); - dsService.download(ds, dsds, fos); - fos.flush(); - fos.close(); - // file.delete(); - } -} diff --git a/src/test/java/org/genesys2/server/service/worker/AccessionCounterTest.java b/src/test/java/org/genesys2/server/service/worker/AccessionCounterTest.java deleted file mode 100644 index 0c05a3269056becea17425057316e6a200c4e1d7..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/worker/AccessionCounterTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.genesys2.server.service.worker; - -import org.apache.commons.lang3.RandomUtils; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.SchedulerConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@Ignore -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = AccessionCounterTest.Config.class, initializers = PropertyPlacholderInitializer.class) -public class AccessionCounterTest { -// private static final Logger LOG = LoggerFactory.getLogger(AccessionCounterTest.class); - - @Import(SchedulerConfig.class) - public static class Config { - @Bean - public AccessionCounter accessionCounter() { - return new AccessionCounter(); - } - } - - @Autowired - private AccessionCounter accessionCounter; - - @Test - public void test1() throws InterruptedException { - FaoInstitute inst = new FaoInstitute(); - inst.setCode("bbb001"); - FaoInstitute inst2 = new FaoInstitute(); - inst2.setCode("AAA001"); - for (int i=0; i<10; i++) { - if (RandomUtils.nextBoolean()) { - accessionCounter.recountInstitute(inst); - } else { - accessionCounter.recountInstitute(inst2); - } - Thread.sleep(RandomUtils.nextLong(2000, 5000)); - } - Thread.sleep(11000); - } -} diff --git a/src/test/java/org/genesys2/server/service/worker/HazelcastDistributedExecutorTest.java b/src/test/java/org/genesys2/server/service/worker/HazelcastDistributedExecutorTest.java deleted file mode 100644 index 741c196689467ed50efd4be04dc3661ea1adf649..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/worker/HazelcastDistributedExecutorTest.java +++ /dev/null @@ -1,320 +0,0 @@ -package org.genesys2.server.service.worker; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.RejectedExecutionException; - -import javax.annotation.Resource; - -import org.apache.commons.lang.math.RandomUtils; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.HierarchyMode; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.hazelcast.config.Config; -import com.hazelcast.config.ExecutorConfig; -import com.hazelcast.config.GroupConfig; -import com.hazelcast.config.JoinConfig; -import com.hazelcast.config.NetworkConfig; -import com.hazelcast.config.QueueConfig; -import com.hazelcast.config.TcpIpConfig; -import com.hazelcast.core.Cluster; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.HazelcastInstanceNotActiveException; -import com.hazelcast.core.IExecutorService; -import com.hazelcast.core.IMap; -import com.hazelcast.core.IQueue; -import com.hazelcast.core.ManagedContext; -import com.hazelcast.core.Member; -import com.hazelcast.spring.cache.HazelcastCacheManager; -import com.hazelcast.spring.context.SpringAware; -import com.hazelcast.spring.context.SpringManagedContext; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = HazelcastDistributedExecutorTest.TestConfig.class, initializers = PropertyPlacholderInitializer.class) -@Ignore -@DirtiesContext(hierarchyMode = HierarchyMode.EXHAUSTIVE, classMode = DirtiesContext.ClassMode.AFTER_CLASS) -public class HazelcastDistributedExecutorTest { - - private static final Logger LOG = LoggerFactory.getLogger(HazelcastDistributedExecutorTest.class); - - @EnableAspectJAutoProxy - @Import({}) - // @ComponentScan(basePackages = {}) - public static class TestConfig { - @Value("${hazelcast.port}") - int hazelPort; - @Value("${hazelcast.instanceName}-testexec") - private String instanceName; - @Value("${hazelcast.password}") - private String password; - @Value("${hazelcast.name}-testexec") - private String name; - - @Bean - public ManagedContext managedContext() { - return new SpringManagedContext(); - } - - @Bean - public HazelcastInstance hazelcast(ManagedContext managedContext) { - Config cfg = new Config(); - cfg.setManagedContext(managedContext); - cfg.setInstanceName(instanceName); - - GroupConfig groupConfig = cfg.getGroupConfig(); - groupConfig.setName(name); - groupConfig.setPassword(password); - - cfg.setProperty("hazelcast.merge.first.run.delay.seconds", "5"); - cfg.setProperty("hazelcast.merge.next.run.delay.seconds", "5"); - cfg.setProperty("hazelcast.logging.type", "log4j"); - cfg.setProperty("hazelcast.icmp.enabled", "true"); - - NetworkConfig network = cfg.getNetworkConfig(); - network.setPort(hazelPort); - network.setPortAutoIncrement(false); - - JoinConfig join = network.getJoin(); - join.getMulticastConfig().setEnabled(false); - TcpIpConfig tcpIpConfig = join.getTcpIpConfig(); - tcpIpConfig.setEnabled(true); - tcpIpConfig.setConnectionTimeoutSeconds(20); - - // MapConfig mapconfig=new MapConfig(); - - ExecutorConfig execConfig = new ExecutorConfig(); - execConfig.setName("hazel-exec"); - execConfig.setPoolSize(4); - execConfig.setQueueCapacity(2); - execConfig.setStatisticsEnabled(true); - cfg.addExecutorConfig(execConfig); - - QueueConfig queueConfig = new QueueConfig(); - queueConfig.setName("elasticsearchQueue"); - queueConfig.setMaxSize(500); - cfg.addQueueConfig(queueConfig); - - HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg); - return instance; - } - - @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance hazelcastInstance) { - HazelcastCacheManager cm = new HazelcastCacheManager(hazelcastInstance); - return cm; - } - - @Bean - public IMap tileserverMap(HazelcastInstance hazelcast) { - IMap x = hazelcast.getMap("tileserver"); - return x; - } - - @Bean - public IExecutorService distributedExecutor(HazelcastInstance hazelcast) { - IExecutorService executorService = hazelcast.getExecutorService("hazel-exec"); - return executorService; - } - - @Bean - public IQueue elasticsearchQueue(HazelcastInstance hazelcast) { - IQueue elasticsearchQueue = hazelcast.getQueue("elasticsearchQueue"); - return elasticsearchQueue; - } - - @Bean - public ListenerFoo listenerFoo() { - return new ListenerFoo("Foo1"); - } - - @Bean - public ListenerFoo listenerFoo2() { - return new ListenerFoo("Foo2"); - } - - } - - @Autowired - HazelcastInstance hazelcast; - - @Autowired - HazelcastCacheManager cacheManager; - - @Resource - IMap tileserverMap; - - @Resource - transient IQueue elasticsearchQueue; - - @Resource - IExecutorService executorService; - - // @Autowired - // ListenerFoo listenerFoo; - - @Test - public void test1() { - LOG.info("Name: {}", hazelcast.getName()); - Cluster cluster = hazelcast.getCluster(); - for (Member member : cluster.getMembers()) { - LOG.info("Cluster member: {} local={}", member, member.localMember()); - } - IMap map = hazelcast.getMap("default"); - LOG.info("Map: {}", map); - IMap tsm = hazelcast.getMap("tileserver"); - LOG.info("Map: {}", tsm); - tsm.put("Test1", "Test1"); - LOG.info("Same? {}", (tsm == tileserverMap)); - System.err.println(tileserverMap.get("Test1")); - } - - @Test - public void testExe() throws InterruptedException, ExecutionException { - tileserverMap.put("Test1", "Test1"); - for (int i = 0; i < 500; i++) { - elasticsearchQueue.add((long) i); - } - - Set> set = new HashSet>(); - for (int i = 0; i < 10; i++) { - try { - Future task = executorService.submit(new Foobar("exec" + i)); - set.add(task); - LOG.info("Submitted task {}", i); - } catch (RejectedExecutionException e) { - LOG.error(e.getMessage()); - } - } - - Thread.sleep(5000); - } - - @Test - public void testExe2() throws InterruptedException, ExecutionException { - for (int i = 0; i < 200; i++) { - if (!elasticsearchQueue.offer((long) i)) { - // Queue full? - Thread.sleep(10); - } - } - Thread.sleep(1000); - // for (int i = 0; i < 300; i++) { - // elasticsearchQueue.add((long) i); - // } - // Thread.sleep(1000); - // for (int i = 0; i < 300; i++) { - // elasticsearchQueue.add((long) i); - // } - } - - @Test - public void testExe3() throws InterruptedException, ExecutionException { - - } - - @SpringAware - static class Foobar implements Callable, Serializable { - /** - * - */ - private static final long serialVersionUID = 8635615920157309873L; - @Resource - transient IMap tileserverMap; - @Resource - transient IQueue elasticsearchQueue; - transient String myName; - - public Foobar(String name) { - myName = name; - } - - @Override - public String call() throws Exception { - System.err.println("setmyname" + myName); - System.err.println("mapserver= " + tileserverMap); - Long item = null; - do { - item = elasticsearchQueue.poll(); - if (item == null) - break; - System.err.println(myName + " item: " + item); - Thread.sleep(10 + RandomUtils.nextInt(10)); - } while (item != null); - Thread.sleep(100 + RandomUtils.nextInt(100)); - return (String) tileserverMap.get("Test1"); - } - } - - static class ListenerFoo implements Runnable, InitializingBean, DisposableBean { - @Resource - transient IQueue elasticsearchQueue; - - private Thread worker; - private boolean running; - - private String name; - - public ListenerFoo(String string) { - this.name = string; - } - - @Override - public void run() { - while (running) { - try { - Long item = elasticsearchQueue.poll(); - - try { - if (item != null) { - LOG.debug(name + " Item: " + item); - Thread.sleep(RandomUtils.nextInt(10)); - } else { - // Thread.sleep(100 + RandomUtils.nextInt(100)); - } - } catch (InterruptedException e) { - } - } catch (HazelcastInstanceNotActiveException e) { - LOG.debug("Hazelcast not active."); - try { - Thread.sleep(100); - } catch (InterruptedException e1) { - } - } - } - } - - @Override - public void afterPropertiesSet() throws Exception { - this.running = true; - this.worker = new Thread(this, "hazel-worker-" + name); - this.worker.start(); - } - - @Override - public void destroy() throws Exception { - this.running = false; - this.worker.interrupt(); - } - - } -} diff --git a/src/test/java/org/genesys2/server/service/worker/SGSVDumpTest.java b/src/test/java/org/genesys2/server/service/worker/SGSVDumpTest.java deleted file mode 100644 index d4ae636b340d3ffe933d8696d6badca120c86204..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/worker/SGSVDumpTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 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.genesys2.server.service.worker; - -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.genesys2.server.model.genesys.SvalbardDeposit; -import org.junit.Ignore; -import org.junit.Test; - -/** - * SGSV data: - * - *
    - *
  • INSTCODE, ACCENUMB are not unique in SGSV. See USA996 accession PI89009 or COL003:G10276
  • - *
- * - * @author mobreza - * - */ -@Ignore -public class SGSVDumpTest { - - @Test - public void download() { - // Set instCodeAcceNumb = new HashSet<>(); - SGSVUpdate updater = new SGSVUpdate() { - - @Override - void workIt(List bulk) { - LOG.trace("Queueing job size={}", bulk.size()); - final List accns = readSvalbardDeposits(bulk); - for (SvalbardDeposit entry : accns) { - if (StringUtils.isBlank(entry.getAcceNumb())) { - LOG.warn("No ACCENUMB for entry={}", entry); - } - // String key = entry.instCode + ":" + entry.acceNumb + ":" + entry.genus; - // if (instCodeAcceNumb.contains(key)) { - // LOG.warn("Duplicate entry for " + key + " entry=" + entry); - // } - // instCodeAcceNumb.add(key); - } - } - }; - updater.updateSGSV(); - } - -} diff --git a/src/test/java/org/genesys2/server/service/worker/SGSVUpdateTest.java b/src/test/java/org/genesys2/server/service/worker/SGSVUpdateTest.java deleted file mode 100644 index 7aeee3c540e495ea636b51c4c011a94d7331e968..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/service/worker/SGSVUpdateTest.java +++ /dev/null @@ -1,352 +0,0 @@ -/** - * 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.genesys2.server.service.worker; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.VelocityException; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.model.genesys.Accession; -import org.genesys2.server.model.genesys.SvalbardDeposit; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.persistence.SvalbardRepository; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.impl.ContentServiceImpl; -import org.genesys2.server.service.impl.GenesysServiceImpl; -import org.genesys2.server.service.impl.GeoServiceImpl; -import org.genesys2.server.service.impl.InstituteServiceImpl; -import org.genesys2.server.service.impl.NonUniqueAccessionException; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.OrganizationServiceImpl; -import org.genesys2.server.service.impl.TaxonomyManager; -import org.genesys2.server.service.impl.TaxonomyServiceImpl; -import org.genesys2.server.service.impl.UserServiceImpl; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.hsqldb.lib.StringInputStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -import org.springframework.core.task.TaskExecutor; -import org.springframework.data.domain.PageRequest; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.ui.velocity.VelocityEngineFactoryBean; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SGSVUpdateTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@Ignore -public class SGSVUpdateTest { - - private static final Logger LOG = LoggerFactory.getLogger(SGSVUpdateTest.class); - - @Import(JpaDataConfig.class) - @ComponentScan(basePackages = { "org.genesys2.server.persistence" }) - public static class Config { - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public VelocityEngine velocityEngine() throws VelocityException, IOException { - final VelocityEngineFactoryBean vf = new VelocityEngineFactoryBean(); - return vf.createVelocityEngine(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public SGSVUpdate sgsvUpdate() { - return new SGSVUpdate(); - } - - @Bean - public TaskExecutor taskExecutor() { - return new ThreadPoolTaskExecutor(); - } - - } - - @Autowired - private SGSVUpdate sgsvUpdate; - - @Autowired - private InstituteService instituteService; - - @Autowired - private GenesysService genesysService; - - @Autowired - private SvalbardRepository svalbardRepository; - - @Autowired - private TaxonomyService taxonomyService; - - @Autowired - private TaskExecutor taskExecutor; - - @Autowired - private TaxonomyManager taxonomyManager; - - @Before - public void setup() { - LOG.info("Setting up"); - final Collection institutes = new ArrayList(); - for (final String instCode : new String[] { "INS001", "INS002" }) { - final FaoInstitute institute = new FaoInstitute(); - institute.setFullName(instCode + " institute"); - institute.setCode(instCode); - institute.setUniqueAcceNumbs(true); - institutes.add(institute); - } - instituteService.update(institutes); - } - - @After - public void afterEachTest() { - LOG.info("Deleting institutes"); - instituteService.delete("INS001"); - instituteService.delete("INS002"); - assertTrue(instituteService.list(new PageRequest(0, 1)).getNumber() == 0); - } - - private void makeAccession(String instCode, String acceNumb, String genus, String species) { - final FaoInstitute institute = instituteService.getInstitute(instCode); - final List accessions = new ArrayList(); - - final Accession a = new Accession(); - a.setInstitute(institute); - a.setAccessionNumber(acceNumb); - a.setTaxonomy(taxonomyManager.ensureTaxonomy2(genus, species, null, null, null)); - - accessions.add(a); - genesysService.saveAccessions(institute, accessions); - } - - private void deleteAccession(String instCode, String doi, String acceNumb, String genus, String species) throws NonUniqueAccessionException { - final FaoInstitute institute = instituteService.getInstitute(instCode); - final List accessions = new ArrayList(); - - accessions.add(genesysService.getAccession(instCode, doi, acceNumb, genus)); - - genesysService.removeAccessions(institute, accessions); - } - - @Test - public void testBlankInput() { - try { - final InputStream str = new StringInputStream(""); - sgsvUpdate.importSGSVStream(str); - } catch (final Throwable e) { - fail("Exception not expected"); - } - } - - @Test - public void testTooFewHeaders() { - try { - final InputStream str = new StringInputStream("a\tb\tc"); - sgsvUpdate.importSGSVStream(str); - } catch (final Throwable e) { - fail("Exception not expected"); - } - } - -// @Test -// public void testImportNoSuchAccession() { -// try { -// final List accns = new ArrayList<>(); -// final SvalbardDeposit entry = new SvalbardDeposit(); -// entry.setinstCode = "INS002"; -// entry.acceNumb = "NONE1"; -// entry.genus = "Genus"; -// entry.boxNo = "Box1"; -// entry.quantity = 1.0f; -// accns.add(entry); -// -// sgsvUpdate.updateSvalbards(accns); -// -// } catch (final Throwable e) { -// fail("Exception not expected"); -// } -// } - -// @Test -// public void testImportSGSV() throws NonUniqueAccessionException { -// makeAccession("INS001", "TEST0", "Genus", "sp."); -// makeAccession("INS001", "TEST1", "Genus", "sp."); -// try { -// final List accns = new ArrayList(); -// final SvalbardDeposit entry = new SvalbardDeposit(); -// entry.acceNumb = "TEST1"; -// entry.genus = "Genus"; -// accns.add(entry); -// -// sgsvUpdate.updateSvalbards(accns); -// -// } catch (final Throwable e) { -// LOG.error(e, e); -// fail("Exception not expected"); -// } -// -// assertTrue(svalbardRepository.findAll().size() > 0); -// -// deleteAccession("INS001", "TEST0", "Genus", "sp."); -// deleteAccession("INS001", "TEST1", "Genus", "sp."); -// } - - private String[] toEntry(String instCode, String acceNumb, String genus, String species, float quantity) { - return new String[] { "a", instCode, "c", "d", acceNumb, "f", "g", Float.toString(quantity), "i", "j", "k", "l", "m", "n", "o", "p", genus, species, - "s", "t", "u", "v", "w", "x", "y", "z", "a", "27" }; - } - - void assertEntry(SvalbardDeposit e) { - assertTrue(e != null); - assertTrue(e.getGenus().equals("Genus")); - assertTrue(e.getQuantity() == 1.0f); - } - - @Test - public void testWorkIt() throws NonUniqueAccessionException { - makeAccession("INS001", "TEST0", "Genus", "sp."); - makeAccession("INS001", "TEST1", "Genus", "sp."); - - try { - final List bulk = new ArrayList(); - bulk.add(toEntry("INS001", "TEST0", "Genus", "sp.", 1.0f)); - bulk.add(toEntry("INS001", "TEST1", "Genus", "sp.", 1.0f)); - bulk.add(toEntry("INS001", "TEST2", "Genus", "sp.", 1.0f)); - bulk.add(toEntry("INS001", "TEST3", "Genus", "sp.", 1.0f)); - sgsvUpdate.workIt(bulk); - assertTrue(bulk.size() == 0); - bulk.add(toEntry("INS001", "TEST0", "Genus", "sp.", 1.0f)); - bulk.add(toEntry("INS001", "TEST1", "Genus", "sp.", 1.0f)); - sgsvUpdate.workIt(bulk); - assertTrue(bulk.size() == 0); - bulk.add(toEntry("INS001", "TEST2", "Genus", "sp.", 1.0f)); - bulk.add(toEntry("INS001", "TEST3", "Genus", "sp.", 1.0f)); - sgsvUpdate.workIt(bulk); - assertTrue(bulk.size() == 0); - sgsvUpdate.workIt(bulk); - - } catch (final Throwable e) { - LOG.error(e.getMessage(), e); - fail("Exception not expected"); - } - - final ThreadPoolTaskExecutor tpte = (ThreadPoolTaskExecutor) taskExecutor; - - while (tpte.getActiveCount() > 0) { - try { - LOG.info("Waiting for workers to finish. Active={}", tpte.getActiveCount()); - Thread.sleep(100); - } catch (final InterruptedException e) { - } - } - - assertTrue(svalbardRepository.findAll().size() == 2); - - deleteAccession("INS001", null, "TEST0", "Genus", "sp."); - deleteAccession("INS001", null, "TEST1", "Genus", "sp."); - - assertTrue(svalbardRepository.findAll().size() == 0); - } -} diff --git a/src/test/java/org/genesys2/server/test/EasySMTATest.java b/src/test/java/org/genesys2/server/test/EasySMTATest.java deleted file mode 100644 index a66725602d14b00c7de548d39e3d7c66018544ba..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/EasySMTATest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.genesys2.server.service.EasySMTA; -import org.genesys2.server.service.EasySMTA.EasySMTAUserData; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class EasySMTATest { - - @Test - public void testSelf() throws JsonParseException, JsonMappingException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final EasySMTAUserData pid1 = new EasySMTAUserData(); - pid1.setPid("pid"); - final String content = mapper.writeValueAsString(pid1); - final EasySMTAUserData pidData = mapper.readValue(content, EasySMTA.EasySMTAUserData.class); - assertTrue(pidData != null); - } - - @Test - public void testJSONRead() { - final String content = "{\"pid\":\"000000\",\"type\":\"in\",\"legalStatus\":\"cg\",\"name\":\"Matija\",\"surname\":\"Obreza\",\"email\":\"matija.obreza@croptrust.org\",\"address\":\"Platz der Vereinten Nationen 7\\r\\n53113 Bonn\",\"country\":\"DEU\",\"countryName\":\"Germany\",\"telephone\":\"\",\"fax\":\"\",\"orgName\":\"\",\"aoName\":\"\",\"aoSurname\":\"\",\"aoEmail\":\"\",\"orgAddress\":\"\",\"orgCountry\":\"\",\"orgCountryName\":\"\",\"aoTelephone\":\"\",\"aoFax\":\"\",\"shipAddrFlag\":\"s\",\"shipAddress\":\"\",\"shipCountry\":\"AFG\",\"shipTelephone\":\"\"}"; - final ObjectMapper mapper = new ObjectMapper(); - try { - final EasySMTAUserData pidData = mapper.readValue(content, EasySMTA.EasySMTAUserData.class); - assertTrue(pidData != null); - } catch (final IOException e) { - fail(e.getMessage()); - } - } - - @Test - public void testJSONReadMissing() { - final String content = "{\"pid\":\"000000\",\"firstName\":\"Matija\",\"lastName\":\"Obreza\",\"email\":\"matija.obreza@croptrust.org\",\"address\":\"Platz der Vereinten Nationen 7\\r\\n53113 Bonn\",\"country\":\"DEU\",\"countryName\":\"Germany\",\"telephone\":\"\",\"fax\":\"\",\"orgName\":\"\",\"aoName\":\"\",\"aoSurname\":\"\",\"aoEmail\":\"\",\"orgAddress\":\"\",\"orgCountry\":\"\",\"orgCountryName\":\"\",\"aoTelephone\":\"\",\"aoFax\":\"\",\"shipAddrFlag\":\"s\",\"shipAddress\":\"\",\"shipCountry\":\"AFG\",\"shipTelephone\":\"\"}"; - final ObjectMapper mapper = new ObjectMapper(); - try { - final EasySMTAUserData pidData = mapper.readValue(content, EasySMTA.EasySMTAUserData.class); - assertTrue(pidData != null); - } catch (final IOException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test(expected = JsonMappingException.class) - public void testJSONSurnameLastname() throws JsonParseException, JsonMappingException, IOException { - final String content = "{\"pid\":\"000000\",\"firstName\":\"Matija\",\"lastName\":\"Obreza\",\"surname\":\"Obreza\",\"email\":\"matija.obreza@croptrust.org\",\"address\":\"Platz der Vereinten Nationen 7\\r\\n53113 Bonn\",\"country\":\"DEU\",\"countryName\":\"Germany\",\"telephone\":\"\",\"fax\":\"\",\"orgName\":\"\",\"aoName\":\"\",\"aoSurname\":\"\",\"aoEmail\":\"\",\"orgAddress\":\"\",\"orgCountry\":\"\",\"orgCountryName\":\"\",\"aoTelephone\":\"\",\"aoFax\":\"\",\"shipAddrFlag\":\"s\",\"shipAddress\":\"\",\"shipCountry\":\"AFG\",\"shipTelephone\":\"\"}"; - final ObjectMapper mapper = new ObjectMapper(); - final EasySMTAUserData pidData = mapper.readValue(content, EasySMTA.EasySMTAUserData.class); - assertTrue(pidData != null); - } - - @Test - public void testJSONNull() throws JsonParseException, JsonMappingException, IOException { - final String content = "null"; - final ObjectMapper mapper = new ObjectMapper(); - final EasySMTAUserData pidData = mapper.readValue(content, EasySMTA.EasySMTAUserData.class); - assertTrue(pidData == null); - } -} diff --git a/src/test/java/org/genesys2/server/test/GRINTaxonomyTest.java b/src/test/java/org/genesys2/server/test/GRINTaxonomyTest.java deleted file mode 100644 index f4935ff583b4bed482c050c0200fad83833436af..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/GRINTaxonomyTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * 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.genesys2.server.test; - -import java.io.File; - -import org.jamel.dbf.processor.DbfProcessor; -import org.jamel.dbf.processor.DbfRowProcessor; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Value; - -/** - * Test DBF reader of GRIN Taxonomy data from http://www.ars-grin.gov/misc/tax/ - * - * @author matijaobreza - */ -@Ignore -public class GRINTaxonomyTest { - - @Value("${download.files.dir}") - private final String filesDir = "./data"; - - // @Test - public void dbInfoTest() { - final String dbfInfo = DbfProcessor.readDbfInfo(new File("genusno.dbf")); - System.out.println(dbfInfo); - } - - /** - * Common names - */ - // @Test - public void testCommon() { - final File dbf = new File("common.dbf"); - final String dbfInfo = DbfProcessor.readDbfInfo(dbf); - System.out.println(dbfInfo); - - DbfProcessor.processDbf(dbf, new DbfRowProcessor() { - @Override - public void processRow(Object[] row) { - System.out.print(new String((byte[]) row[0]).trim()); - System.out.print(", "); - System.out.print(((Number) row[1]).longValue()); - System.out.print(", "); - System.out.print(new String((byte[]) row[2]).trim()); - System.out.println(); - } - }); - } - - @Test - public void testSpecies() { - final File dbf = new File(filesDir, "species 2.dbf"); - final String dbfInfo = DbfProcessor.readDbfInfo(dbf); - System.out.println(dbfInfo); - - DbfProcessor.processDbf(dbf, new DbfRowProcessor() { - @Override - public void processRow(Object[] row) { - // if (! "Zea".equals(new String((byte[]) row[3]).trim())) { - // return; - // } - // if ("".equals(new String((byte[]) row[4]).trim()) || - // "".equals(new String((byte[]) row[8]).trim()) ) { - // return; - // } - System.out.print(((Number) row[0]).longValue()); - System.out.print(", "); - System.out.print(((Number) row[1]).longValue()); - System.out.print(", "); - System.out.print(new String((byte[]) row[3]).trim()); - System.out.print(", 4="); - System.out.print(new String((byte[]) row[4]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[5]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[6]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[7]).trim()); - System.out.print(", SUB >> "); - System.out.print(new String((byte[]) row[8]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[9]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[10]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[11]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[12]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[13]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[14]).trim()); - System.out.print(", "); - - System.out.print(new String((byte[]) row[15]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[16]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[17]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[18]).trim()); - System.out.print(", "); - - System.out.print(new String((byte[]) row[20]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[21]).trim()); - System.out.print(", "); - - System.out.print(row[24]); - System.out.print(", "); - System.out.print(row[25]); - System.out.println(); - } - }); - } - - // @Test - public void testGenusno() { - final File dbf = new File("genusno.dbf"); - final String dbfInfo = DbfProcessor.readDbfInfo(dbf); - System.out.println(dbfInfo); - - DbfProcessor.processDbf(dbf, new DbfRowProcessor() { - @Override - public void processRow(Object[] row) { - System.out.print(new String((byte[]) row[0]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[1]).trim()); - System.out.print(", "); - System.out.print(((Number) row[2]).longValue()); - System.out.print(", "); - System.out.print(((Number) row[3]).longValue()); - System.out.print(", "); - System.out.print(new String((byte[]) row[4]).trim()); - System.out.println(); - } - }); - } - - // @Test - public void testTaxonno() { - final File dbf = new File("taxonno.dbf"); - final String dbfInfo = DbfProcessor.readDbfInfo(dbf); - System.out.println(dbfInfo); - - DbfProcessor.processDbf(dbf, new DbfRowProcessor() { - @Override - public void processRow(Object[] row) { - System.out.print(new String((byte[]) row[0]).trim()); - System.out.print(", "); - System.out.print(new String((byte[]) row[1]).trim()); - System.out.print(", "); - System.out.print(((Number) row[2]).longValue()); - System.out.print(", "); - System.out.print(((Number) row[3]).longValue()); - System.out.println(); - } - }); - } -} diff --git a/src/test/java/org/genesys2/server/test/GenesysBeansConfig.java b/src/test/java/org/genesys2/server/test/GenesysBeansConfig.java deleted file mode 100644 index 946196fb0f5e5eacca2e0bc4d4f9c15bffdf4fde..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/GenesysBeansConfig.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * 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.genesys2.server.test; - -import java.io.IOException; -import java.util.Properties; - -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.VelocityException; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepositoryCustomImpl; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.GenesysFilterService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.audit.SpringSecurityAuditorAware; -import org.genesys2.server.service.impl.ContentServiceImpl; -import org.genesys2.server.service.impl.CropServiceImpl; -import org.genesys2.server.service.impl.GenesysFilterServiceImpl; -import org.genesys2.server.service.impl.GenesysServiceImpl; -import org.genesys2.server.service.impl.GeoServiceImpl; -import org.genesys2.server.service.impl.InstituteServiceImpl; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.OrganizationServiceImpl; -import org.genesys2.server.service.impl.TaxonomyServiceImpl; -import org.genesys2.server.service.impl.TraitServiceImpl; -import org.genesys2.server.service.impl.UserServiceImpl; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.domain.AuditorAware; -import org.springframework.ui.velocity.VelocityEngineFactoryBean; - -@Configuration -public class GenesysBeansConfig { - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public AuditorAware auditorAware() { - return new SpringSecurityAuditorAware(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean - public GenesysFilterService genesysFilterService() { - return new GenesysFilterServiceImpl(); - } - - @Bean - public TraitService traitService() { - return new TraitServiceImpl(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public GenesysLowlevelRepository genesysLowlevelRepository() { - return new GenesysLowlevelRepositoryCustomImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public VelocityEngine velocityEngine() throws VelocityException, IOException { - final VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean(); - velocityEngineFactoryBean.setVelocityProperties(velocityProperties()); - velocityEngineFactoryBean.afterPropertiesSet(); - VelocityEngine engine = velocityEngineFactoryBean.getObject(); - if (engine == null) { - throw new RuntimeException("Velocity engine could not be created"); - } - return engine; - } - - private Properties velocityProperties() { - final Properties properties = new Properties(); - properties.setProperty("resource.loader", "class"); - properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - properties.setProperty("velocimacro.permissions.allow.inline.local.scope", "false"); - properties.setProperty("runtime.log.logsystem.log4j.logger", "velocity"); - properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogChute"); - return properties; - } - -} diff --git a/src/test/java/org/genesys2/server/test/HtmlSanitizerTest.java b/src/test/java/org/genesys2/server/test/HtmlSanitizerTest.java deleted file mode 100644 index 2e8dde5e7dcff3f014f04e88d1357ae691e375d5..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/HtmlSanitizerTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = HtmlSanitizerTest.Config.class, initializers = PropertyPlacholderInitializer.class) -public class HtmlSanitizerTest { - - @EnableAspectJAutoProxy - @Import({}) - // @ComponentScan(basePackages = {}) - public static class Config { - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - } - - @Autowired - private HtmlSanitizer htmlSanitizer; - - @Test - public void test1() { - assertNotNull(htmlSanitizer); - - assertNull(htmlSanitizer.sanitize(null)); - assertEquals("", htmlSanitizer.sanitize("")); - assertEquals("genesys 1 2 3", htmlSanitizer.sanitize("genesys 1 2 3")); - assertEquals("

genesys 1 2 3

", htmlSanitizer.sanitize("

genesys 1 2 3

")); - assertEquals("

genesys 1 2 3

", htmlSanitizer.sanitize("

genesys 1 2 3

")); - assertEquals("

genesys 1
2 3

", htmlSanitizer.sanitize("

genesys 1
2 3

")); - assertEquals("

genesys 1 2 3

", htmlSanitizer.sanitize("

genesys 1 2 3

")); - assertEquals("

genesys 1

genesys 1

", htmlSanitizer.sanitize("

genesys 1

genesys 1

")); - - assertEquals( - "GENESYS is the result of collaboration between Bioversity International", - htmlSanitizer - .sanitize("GENESYS is the result of collaboration between Bioversity International")); - } -} diff --git a/src/test/java/org/genesys2/server/test/JpaDataConfig.java b/src/test/java/org/genesys2/server/test/JpaDataConfig.java deleted file mode 100644 index 9ebf4fb77268e5efe9bdda049fbef37dd73c6a39..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/JpaDataConfig.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * 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.genesys2.server.test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Properties; -import java.util.UUID; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.genesys.blocks.model.EntityId; -import org.genesys.blocks.model.IdUUID; -import org.genesys2.server.service.audit.SpringSecurityAuditorAware; -import org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper; -import org.hibernate.EmptyInterceptor; -import org.hibernate.jpa.HibernatePersistenceProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.support.PersistenceExceptionTranslator; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.hibernate4.HibernateExceptionTranslator; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@PropertySource("classpath:/spring/spring.properties") -@EnableJpaRepositories(basePackages = { "org.genesys.blocks.persistence", "org.genesys.blocks.security.persistence", "org.genesys.blocks.oauth.persistence", - "org.genesys.blocks.auditlog.persistence", "org.genesys2.server.persistence", "org.genesys2.server.persistence.acl", - "org.genesys.filerepository.persistence", "org.genesys.catalog.persistence" }, entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager", repositoryImplementationPostfix = "CustomImpl") -@EnableTransactionManagement -public class JpaDataConfig { - @Autowired - private Environment env; - - @Bean(name = "dataSource") - public DataSource dataSource() throws Exception { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - - dataSource.setDriverClassName(env.getProperty("db.driverClassName")); - dataSource.setUrl(env.getProperty("db.url")); - dataSource.setUsername(env.getProperty("db.username")); - dataSource.setPassword(env.getProperty("db.password")); - - return dataSource; - } - - @Bean - public JdbcTemplate jdbcTemplate(DataSource dataSource) { - return new JdbcTemplate(dataSource); - } - - @Bean(name = "entityManagerFactory") - public LocalContainerEntityManagerFactoryBean entityManagerFactory(HazelcastCacheRegionFactoryWrapper wrp) throws Exception { - final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean(); - - bean.setDataSource(dataSource()); - bean.setPersistenceUnitName("spring-jpa"); - bean.setPackagesToScan("org.genesys.blocks.model", "org.genesys.blocks.auditlog.model", "org.genesys.blocks.security.model", - "org.genesys.blocks.oauth.model", "org.genesys2.server.model", "org.genesys.filerepository.model", "org.genesys.catalog.model"); - bean.setPersistenceProvider(new HibernatePersistenceProvider()); - - final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); - jpaVendorAdapter.setShowSql(env.getProperty("db.showSql", Boolean.TYPE, true)); - jpaVendorAdapter.setGenerateDdl(env.getProperty("db.hbm2ddl", Boolean.TYPE, true)); - - Properties jpaProperties = jpaProperties(); - for (Object key : jpaProperties.keySet()) { - System.err.println("JPA: " + key + " = " + jpaProperties.get(key)); - } - jpaProperties.put("hibernate.ejb.interceptor", new EmptyInterceptor() { - private final Logger LOG = LoggerFactory.getLogger("org.genesys.blocks.auditlog.Interceptor"); - - @Override - public Boolean isTransient(final Object entity) { - if (entity instanceof IdUUID) { - UUID uuid = ((IdUUID) entity).getUuid(); - if (uuid == null) - return true; - } - if (entity instanceof EntityId) { - Long id = ((EntityId) entity).getId(); - if (id == null || id < 0) - return true; - } - try { - return tryMethod(entity, "getVersion"); - } catch (final NoSuchMethodException e) { - try { - return tryMethod(entity, "getId"); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e1) { - throw new RuntimeException(e.getMessage() + " on " + entity.getClass() + " e=" + entity, e); - } - } catch (final Throwable e) { - throw new RuntimeException(e.getMessage() + " on " + entity.getClass() + " e=" + entity, e); - } - } - - public Boolean tryMethod(final Object entity, final String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { - final Method getter = entity.getClass().getMethod(methodName); - if (getter != null) { - final Object result = getter.invoke(entity); - if (result == null) { - LOG.trace("{} is transient, has {} == null", entity, methodName); - return true; - } else if (result instanceof Number) { - final Number r = (Number) result; - if (r.longValue() < 0) { - LOG.trace("{} is transient, has {} = {} < 0", entity, methodName, result); - return true; - } else { - // LOG.trace(entity + " is not transient, has " + methodName + " = " + result + " >= 0"); - return false; - } - } else { - // LOG.trace(entity + " is not transient, has " + methodName + " = " + result); - return false; - } - } else { - LOG.trace("No version method."); - throw new RuntimeException("No version method"); - } - } - }); - bean.setJpaProperties(jpaProperties); - - bean.setJpaVendorAdapter(jpaVendorAdapter); - - return bean; - } - - @Bean(name = "transactionManager") - public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) throws Exception { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setDataSource(dataSource()); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslator hibernateExceptionTranslator() { - return new HibernateExceptionTranslator(); - } - - private Properties jpaProperties() throws Exception { - Properties jpaProp = new Properties(); - jpaProp.load(getClass().getResourceAsStream("/spring/hibernate.properties")); - return jpaProp; - } - - @Bean - public SpringSecurityAuditorAware auditorAware() { - return new SpringSecurityAuditorAware(); - } -} diff --git a/src/test/java/org/genesys2/server/test/JpaNoCacheDataConfig.java b/src/test/java/org/genesys2/server/test/JpaNoCacheDataConfig.java deleted file mode 100644 index 3a397e00065d20d65e90a32e4afbfb3ce671c703..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/JpaNoCacheDataConfig.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * 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.genesys2.server.test; - -import java.util.ArrayList; -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.hibernate.jpa.HibernatePersistenceProvider; -import org.junit.Ignore; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.support.PersistenceExceptionTranslator; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.hibernate4.HibernateExceptionTranslator; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.test.context.transaction.TransactionConfiguration; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@PropertySource("classpath:/spring/spring.properties") -@EnableJpaRepositories(basePackages = { "org.genesys2.server.persistence.acl", "org.genesys2.server.persistence" }, repositoryImplementationPostfix = "CustomImpl", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager") -@EnableTransactionManagement -@TransactionConfiguration(defaultRollback = false, transactionManager = "transactionManager") -public class JpaNoCacheDataConfig { - @Autowired - private Environment env; - - @Bean(name = "dataSource") - public DataSource dataSource() throws Exception { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - - dataSource.setDriverClassName(env.getProperty("db.driverClassName")); - dataSource.setUrl(env.getProperty("db.url")); - dataSource.setUsername(env.getProperty("db.username")); - dataSource.setPassword(env.getProperty("db.password")); - - return dataSource; - } - - @Bean - public JdbcTemplate jdbcTemplate(DataSource dataSource) { - return new JdbcTemplate(dataSource); - } - - @Bean(name = "entityManagerFactory") - public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception { - final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean(); - - bean.setDataSource(dataSource()); - bean.setPersistenceUnitName("spring-jpa"); - bean.setPackagesToScan("org.genesys2.server.model"); - bean.setPersistenceProvider(new HibernatePersistenceProvider()); - - final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); - jpaVendorAdapter.setShowSql(env.getProperty("db.showSql", Boolean.TYPE, true)); - jpaVendorAdapter.setGenerateDdl(env.getProperty("db.hbm2ddl", Boolean.TYPE, true)); - Properties jpaProperties = jpaProperties(); - for (Object key : jpaProperties.keySet()) { - System.err.println("JPA: " + key + " = " + jpaProperties.get(key)); - } - bean.setJpaProperties(jpaProperties); - - bean.setJpaVendorAdapter(jpaVendorAdapter); - - return bean; - } - - @Bean(name = "transactionManager") - public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) throws Exception { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setDataSource(dataSource()); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslator hibernateExceptionTranslator() { - return new HibernateExceptionTranslator(); - } - - private Properties jpaProperties() throws Exception { - Properties jpaProp = new Properties(); - jpaProp.load(getClass().getResourceAsStream("/spring/hibernate.properties")); - - for (Object key : new ArrayList(jpaProp.keySet())) { - if (((String) key).startsWith("hibernate.cache.") || ("javax.persistence.sharedCache.mode".equals(key))) { - System.err.println("Removing: " + key); - jpaProp.remove(key); - } - } - - jpaProp.setProperty("hibernate.cache.use_second_level_cache", "false"); - - return jpaProp; - } -} diff --git a/src/test/java/org/genesys2/server/test/JpaRealDataConfig.java b/src/test/java/org/genesys2/server/test/JpaRealDataConfig.java deleted file mode 100644 index 7ea1583e33c53cc41944fe3422134866753c78ed..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/JpaRealDataConfig.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * 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.genesys2.server.test; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; - -import org.apache.tomcat.jdbc.pool.DataSource; -import org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper; -import org.hibernate.jpa.HibernatePersistenceProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.support.PersistenceExceptionTranslator; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.orm.hibernate4.HibernateExceptionTranslator; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.test.context.transaction.TransactionConfiguration; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@PropertySource("classpath:/spring/spring-database.properties") -@EnableJpaRepositories(basePackages = { "org.genesys2.server.persistence.acl", "org.genesys2.server.persistence", "org.genesys2.server.persistence.dataset" }, repositoryImplementationPostfix = "CustomImpl", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager") -@EnableTransactionManagement -@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager") -public class JpaRealDataConfig { - @Autowired - private Environment env; - - @Bean(name = "dataSource", destroyMethod = "close") - public DataSource dataSource() throws Exception { - final DataSource dataSource = new DataSource(); - - dataSource.setDriverClassName(env.getProperty("db.driverClassName")); - dataSource.setUrl(env.getProperty("db.url")); - dataSource.setUsername(env.getProperty("db.username")); - dataSource.setPassword(env.getProperty("db.password")); - dataSource.setValidationQuery("SELECT 1"); - dataSource.setTestWhileIdle(true); - dataSource.setTestOnBorrow(true); - dataSource.setTestOnConnect(true); - dataSource.setValidationInterval(60); - dataSource.setMinIdle(3); - dataSource.setMaxActive(10); - dataSource.setMaxIdle(5); - dataSource.setInitialSize(5); - - return dataSource; - } - - @Bean - public JdbcTemplate jdbcTemplate(DataSource dataSource) { - return new JdbcTemplate(dataSource); - } - - @Bean(name = "entityManagerFactory") - public LocalContainerEntityManagerFactoryBean entityManagerFactory(HazelcastCacheRegionFactoryWrapper wrp) throws Exception { - final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean(); - - bean.setDataSource(dataSource()); - bean.setPersistenceUnitName("spring-jpa"); - bean.setPackagesToScan("org.genesys2.server.model"); - bean.setPersistenceProvider(new HibernatePersistenceProvider()); - - final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); - jpaVendorAdapter.setShowSql(env.getProperty("db.showSql", Boolean.TYPE, true)); - jpaVendorAdapter.setGenerateDdl(env.getProperty("db.hbm2ddl", Boolean.TYPE, true)); - Properties jpaProperties = jpaProperties(); - // for (Object key : jpaProperties.keySet()) { - // System.err.println("JPA: " + key + " = " + jpaProperties.get(key)); - // } - bean.setJpaProperties(jpaProperties); - - bean.setJpaVendorAdapter(jpaVendorAdapter); - - return bean; - } - - @Bean - public PersistenceExceptionTranslator hibernateExceptionTranslator() { - return new HibernateExceptionTranslator(); - } - - @Bean(name = "transactionManager") - public JpaTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) throws Exception { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setDataSource(dataSource()); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - @Bean(name = "jpaProperties") - public Properties jpaProperties() throws Exception { - Properties jpaProp = new Properties(); - jpaProp.load(getClass().getResourceAsStream("/spring/hibernate-mysql.properties")); - return jpaProp; - } -} diff --git a/src/test/java/org/genesys2/server/test/LicensesTest.java b/src/test/java/org/genesys2/server/test/LicensesTest.java deleted file mode 100644 index 236e25b5e28cd88f871d10b43fb1849c359fe173..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/LicensesTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 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.genesys2.server.test; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.IOUtils; -import org.junit.Test; - -public class LicensesTest { - - @Test - public void test3rdPartyRead() throws IOException { - try (InputStream is = getClass().getClassLoader().getResourceAsStream("THIRD-PARTY.txt")) { - String thirdParty = IOUtils.toString(is, Charset.forName("UTF8")); - assertThat("THIRD-PARTY.txt could not be read", thirdParty, not(nullValue())); - - Pattern licenseInfo = Pattern.compile("^ {5}\\(((?:\\([^\\)]+\\)|[^\\)])+)\\) (\\(.+\\) )*(.+) \\((.+):(.+):(.+) \\- (.+)\\)$", Pattern.MULTILINE); - Matcher m = licenseInfo.matcher(thirdParty); - while (m.find()) { - String license = m.group(1); - String license2 = m.group(2); - String project = m.group(3); - String groupId = m.group(4); - String artifactId = m.group(5); - String version = m.group(6); - String url = m.group(7); - System.err.println(project + " url=" + url + " license=" + license + " art=" + artifactId + "@" + version); - } - } - } - -} diff --git a/src/test/java/org/genesys2/server/test/MaterialRequestTest.java b/src/test/java/org/genesys2/server/test/MaterialRequestTest.java deleted file mode 100644 index f16cd149b6bf424c4dd62ac605cdc3c118d409e2..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/MaterialRequestTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import javax.mail.internet.MimeMessage; - -import org.apache.commons.lang.math.RandomUtils; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.VelocityException; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys2.server.listener.sample.CreateContentListener; -import org.genesys2.server.model.genesys.MaterialRequest; -import org.genesys2.server.persistence.MaterialRequestRepository; -import org.genesys2.server.security.AsAdminInvoker; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.EMailService; -import org.genesys2.server.service.EasySMTA; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.RequestService; -import org.genesys2.server.service.RequestService.RequestException; -import org.genesys2.server.service.RequestService.RequestInfo; -import org.genesys2.server.service.TokenVerificationService; -import org.genesys2.server.service.impl.ContentServiceImpl; -import org.genesys2.server.service.impl.EMailServiceImpl; -import org.genesys2.server.service.impl.EasySMTAMockConnector; -import org.genesys2.server.service.impl.InstituteServiceImpl; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.RequestServiceImpl; -import org.genesys2.server.service.impl.TokenVerificationServiceImpl; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.mail.MailException; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.ui.velocity.VelocityEngineFactoryBean; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MaterialRequestTest.Config.class, JpaDataConfig.class, GenesysBeansConfig.class}, initializers = PropertyPlacholderInitializer.class) -@Ignore -public class MaterialRequestTest { - - public static class Config { - - @Bean - public TokenVerificationService tokenVerificationService() { - return new TokenVerificationServiceImpl(); - } - - @Bean - public EasySMTA easySmta() { - return new EasySMTAMockConnector(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public RequestService requestService() { - return new RequestServiceImpl(); - } - - @Bean - public EMailService emailService() { - return new EMailServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public VelocityEngine velocityEngine() throws VelocityException, IOException { - final VelocityEngineFactoryBean vf = new VelocityEngineFactoryBean(); - return vf.createVelocityEngine(); - } - - @Bean - public ThreadPoolTaskExecutor taskExecutor() { - return new ThreadPoolTaskExecutor(); - } - - @Bean - public JavaMailSender javaMailSender() { - final JavaMailSender jms = new JavaMailSenderImpl() { - @Override - protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException { - System.err.println("Faking sending email..."); - } - }; - return jms; - } - - @Bean - public AsAdminInvoker asAdminInvoker() { - return new AsAdminInvoker(); - } - - @Bean - public CreateContentListener createContentListener() { - return new CreateContentListener(); - } - } - - @Autowired - private RequestService requestService; - - @Autowired - private InstituteService instituteService; - - @Autowired - private GenesysService genesysService; - - @Autowired - private MaterialRequestRepository requestRepository; - - // Initialize bean to create default contents - @Autowired - private CreateContentListener createContentListener; - - @Ignore("We don't have accession data") - @Test - public void testCreateRequest() { - final RequestInfo requestInfo = new RequestInfo(); - final Set accessionIds = generateAccessionIds(); - - MaterialRequest request = null; - - try { - request = requestService.initiateRequest(requestInfo, accessionIds); - } catch (final RequestException e) { - fail(e.getMessage()); - } - - System.err.println(request); - assertTrue(request.getId() != null); - assertTrue(request.getUuid() != null); - assertTrue(request.getBody() != null); - assertTrue(request.getPid().equals("pid1")); - assertTrue(request.getEmail().equals("email@localhost")); - - final MaterialRequest loaded = requestService.get(request.getUuid()); - assertTrue("Could not load request", loaded != null); - assertTrue("Got something else back", loaded.getId().equals(request.getId())); - } - - Set generateAccessionIds() { - final Set accessionIds = new HashSet(); - for (long i = 2 + RandomUtils.nextInt(20); i >= 0; i--) { - accessionIds.add(i); - } - return accessionIds; - } - - @Test(expected = DataIntegrityViolationException.class) - public void expectDataIntegrityViolationOnDoubleUuid() { - final MaterialRequest mr = new MaterialRequest(); - mr.setPid("pid2"); - mr.setEmail("email@localhost"); - - requestRepository.save(mr); - assertTrue(mr.getId() != null); - assertTrue(mr.getUuid() != null); - - final MaterialRequest mr2 = new MaterialRequest(); - mr2.setUuid(mr.getUuid()); - requestRepository.save(mr2); - } - - @Test(expected = RequestException.class) - public void testEmail() throws RequestException { - final RequestInfo requestInfo = new RequestInfo(); - final Set accessionIds = generateAccessionIds(); - - requestService.initiateRequest(requestInfo, accessionIds); - } - - @Test - public void loadNonExistent() { - final MaterialRequest loaded = requestService.get("non-existent-uuid"); - assertTrue("Should be null", loaded == null); - } -} diff --git a/src/test/java/org/genesys2/server/test/PropertyPlacholderInitializer.java b/src/test/java/org/genesys2/server/test/PropertyPlacholderInitializer.java deleted file mode 100644 index 8c4a2c6fcd3fc86e49986fb079e82ea805dd868e..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/PropertyPlacholderInitializer.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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.genesys2.server.test; - -import org.springframework.beans.factory.config.PlaceholderConfigurerSupport; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -/** - * Initializing class for using "context:property-placeholder" within @Configuration classes - */ -public class PropertyPlacholderInitializer implements ApplicationContextInitializer { - - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - final PlaceholderConfigurerSupport postProcessor = new PropertySourcesPlaceholderConfigurer(); - postProcessor.setIgnoreResourceNotFound(true); - postProcessor.setFileEncoding("utf-8"); - - postProcessor.setLocations(new Resource[] { new ClassPathResource("application.properties"), new ClassPathResource("spring/spring.properties"), - // Include genesys.properties - new ClassPathResource("genesys.properties") }); - applicationContext.addBeanFactoryPostProcessor(postProcessor); - } -} diff --git a/src/test/java/org/genesys2/server/test/RestTest.java b/src/test/java/org/genesys2/server/test/RestTest.java deleted file mode 100644 index 12c8a3eb018faaf309d51a48d73b2da4375fdc31..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/RestTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - -import org.junit.Before; -import org.junit.Ignore; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@WebAppConfiguration -@ContextConfiguration(locations = { "classpath:spring/spring-common.xml",// ignore - // security - "classpath:spring/spring-db.xml", "classpath:spring/spring-servlet.xml", "classpath:spring/spring-security-test.xml" }) -@ActiveProfiles("test") -@Ignore -public abstract class RestTest { - - @Autowired - protected WebApplicationContext wac; - - @Autowired - protected ObjectMapper objectMapper; - - protected MockMvc mockMvc; - - @Before - public void setup() { - mockMvc = webAppContextSetup(this.wac).build(); - } - -} diff --git a/src/test/java/org/genesys2/server/test/TaxonomyEnsureTest.java b/src/test/java/org/genesys2/server/test/TaxonomyEnsureTest.java deleted file mode 100644 index e2cb75792724a5aae335b6a3a469b29608940dad..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/TaxonomyEnsureTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.apache.commons.lang3.StringUtils; -import org.genesys2.server.model.genesys.Taxonomy2; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.impl.CropServiceImpl; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.TaxonomyManager; -import org.genesys2.server.service.impl.TaxonomyServiceImpl; -import org.genesys2.spring.config.CacheConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@ActiveProfiles("dev") -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TaxonomyEnsureTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@Ignore -public class TaxonomyEnsureTest { - - @Import({ JpaNoCacheDataConfig.class, CacheConfig.class }) - public static class Config { - - @Bean - public TaxonomyManager taxonomyManager() { - return new TaxonomyManager(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - } - - // use it without @Scheduled - @Autowired - private TaxonomyService taxonomyService; - - @Autowired - private TaxonomyManager taxonomyManager; - - @Test - public void testSubstr() { - final String genus = "Aaaa"; - final String species = "bbbb"; - final String taxonName = "Aaaa bbbb fb."; - final String x = genus + ' ' + species; - - assertTrue(taxonName.startsWith(x)); - - if (taxonName.startsWith(x)) { - final String subtaxa = taxonName.substring(x.length()).trim(); - assertTrue(StringUtils.isNotBlank(subtaxa)); - assertTrue("fb.".equals(subtaxa)); - } - } - - @Test - public void testEnsure1() { - try { - final Taxonomy2 tax = taxonomyManager.ensureTaxonomy2("Aaaaa", "bbbb", null, "alfalfa", null); - assertTrue("id missing", tax.getId() != null); - assertTrue("taxGenus should not be null", tax.getTaxGenus() != null); - assertTrue("taxSpecies should not be null", tax.getTaxSpecies() != null); - assertFalse("taxGenus should not be this", tax.getTaxGenus().equals(tax.getId())); - assertFalse("taxSpecies should not be this", tax.getTaxSpecies().equals(tax.getId())); - assertFalse("taxSpecies should not match taxGenus", tax.getTaxSpecies().equals(tax.getTaxGenus())); - - final Taxonomy2 taxGenus = taxonomyService.get(tax.getTaxGenus()); - assertTrue("taxGenus should have species=sp. and not " + taxGenus.getSpecies(), taxGenus.getSpecies().equals("sp.")); - - final Taxonomy2 taxSpecies = taxonomyService.get(tax.getTaxSpecies()); - assertTrue("taxSpecies should have species=bbbb and not " + taxSpecies.getSpecies(), taxSpecies.getSpecies().equals(tax.getSpecies())); - - } catch (final Exception e) { - fail("This should not have any exceptions!"); - } - } - - @Test - public void testNullSpecies() { - try { - final Taxonomy2 tax = taxonomyManager.ensureTaxonomy2("Aaaaa", null, null, null, null); - assertTrue("id missing", tax.getId() != null); - assertTrue("taxGenus should not be null", tax.getTaxGenus() != null); - assertTrue("taxSpecies should not be null", tax.getTaxSpecies() != null); - assertTrue("taxGenus must be this", tax.getTaxGenus().equals(tax.getId())); - assertTrue("taxSpecies must be this", tax.getTaxSpecies().equals(tax.getId())); - assertTrue("taxSpecies should match taxGenus", tax.getTaxSpecies().equals(tax.getTaxGenus())); - } catch (final Exception e) { - fail("This should not have any exceptions!"); - } - } - - @Test - public void testSpSpecies() { - try { - final Taxonomy2 tax = taxonomyManager.ensureTaxonomy2("Aaaaa", "sp.", null, null, null); - assertTrue("id missing", tax.getId() != null); - assertTrue("species must be sp.", tax.getSpecies().equals("sp.")); - assertTrue("taxGenus should not be null", tax.getTaxGenus() != null); - assertTrue("taxSpecies should not be null", tax.getTaxSpecies() != null); - assertTrue("taxGenus must be this", tax.getTaxGenus().equals(tax.getId())); - assertTrue("taxSpecies must be this", tax.getTaxSpecies().equals(tax.getId())); - assertTrue("taxSpecies should match taxGenus", tax.getTaxSpecies().equals(tax.getTaxGenus())); - } catch (final Exception e) { - fail("This should not have any exceptions!"); - } - } - - @Test - public void testSpecies() { - try { - final Taxonomy2 tax = taxonomyManager.ensureTaxonomy2("Aaaaa", "species", null, null, null); - assertTrue("id missing", tax.getId() != null); - assertTrue("species must be species", tax.getSpecies().equals("species")); - assertTrue("taxGenus should not be null", tax.getTaxGenus() != null); - assertTrue("taxSpecies should not be null", tax.getTaxSpecies() != null); - assertFalse("taxGenus must not be this", tax.getTaxGenus().equals(tax.getId())); - assertTrue("taxSpecies must be this", tax.getTaxSpecies().equals(tax.getId())); - assertFalse("taxSpecies should not match taxGenus", tax.getTaxSpecies().equals(tax.getTaxGenus())); - } catch (final Exception e) { - fail("This should not have any exceptions!"); - } - } - - @Test - public void testFullTaxonomy() { - try { - final Taxonomy2 tax = taxonomyManager.ensureTaxonomy2("Aaaaa", "species", "spauthor", "subtaxa", "subtauthor"); - System.out.println(tax); - assertTrue("id missing", tax.getId() != null); - assertTrue("species must be sp.", tax.getSpecies().equals("species")); - assertTrue("taxGenus should not be null", tax.getTaxGenus() != null); - assertTrue("taxSpecies should not be null", tax.getTaxSpecies() != null); - assertFalse("taxGenus must not be this", tax.getTaxGenus().equals(tax.getId())); - assertFalse("taxSpecies must not be this", tax.getTaxSpecies().equals(tax.getId())); - assertFalse("taxSpecies should not match taxGenus", tax.getTaxSpecies().equals(tax.getTaxGenus())); - - final Taxonomy2 taxGenus = taxonomyService.get(tax.getTaxGenus()); - System.out.println(taxGenus); - - final Taxonomy2 taxSpecies = taxonomyService.get(tax.getTaxSpecies()); - System.out.println(taxSpecies); - - } catch (final Exception e) { - fail("This should not have any exceptions!"); - } - } -} diff --git a/src/test/java/org/genesys2/server/test/TokenVerificationServiceTest.java b/src/test/java/org/genesys2/server/test/TokenVerificationServiceTest.java deleted file mode 100644 index 918eb268449c79eab6ee47dd6508064984d90d1e..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/TokenVerificationServiceTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.genesys2.server.mock.service.TokenConsumerService; -import org.genesys2.server.mock.service.TokenConsumerServiceImpl; -import org.genesys2.server.model.impl.VerificationToken; -import org.genesys2.server.persistence.VerificationTokenRepository; -import org.genesys2.server.service.TokenVerificationService; -import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException; -import org.genesys2.server.service.TokenVerificationService.TokenExpiredException; -import org.genesys2.server.service.impl.TokenVerificationServiceImpl; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.Calendar; - -/** - * Tests for {@link TokenVerificationServiceImpl} - * - * @author matijaobreza - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TokenVerificationServiceTest.Config.class, initializers = PropertyPlacholderInitializer.class) -@Ignore -public class TokenVerificationServiceTest { - - @ComponentScan(basePackages = { "org.genesys2.server.persistence" }) - public static class Config extends JpaDataConfig { - - @Bean - public TokenVerificationService tokenVerificationService() { - return new TokenVerificationServiceImpl(); - } - - @Bean - public TokenConsumerService tokenConsumerService() { - return new TokenConsumerServiceImpl(); - } - - } - - @Autowired - private VerificationTokenRepository tokenRepository; - - @Autowired - private TokenVerificationService tokenVerificationService; - - @Autowired - private TokenConsumerService tokenConsumerService; - - @Test(expected = NoSuchVerificationTokenException.class) - public void consumeException() throws NoSuchVerificationTokenException, TokenExpiredException { - tokenVerificationService.consumeToken("purpose1", "no-such-uuid", "wrongkey"); - } - - @Test(expected = NoSuchVerificationTokenException.class) - public void testGenerateAndFail() throws NoSuchVerificationTokenException, TokenExpiredException { - final VerificationToken t = tokenVerificationService.generateToken("purpose1", null); - assertTrue("ID should be assigned", t.getId() != null); - assertTrue("UUID should be assigned", t.getUuid() != null); - assertTrue("Data should be null", t.getData() == null); - - tokenVerificationService.consumeToken("purpose1", t.getUuid(), "wrongkey"); - } - - @Test - public void testGenerateAndConsume() { - final VerificationToken t = tokenVerificationService.generateToken("purpose1", null); - assertTrue("ID should be assigned", t.getId() != null); - assertTrue("UUID should be assigned", t.getUuid() != null); - assertTrue("Data should be null", t.getData() == null); - - try { - tokenVerificationService.consumeToken("purpose1", t.getUuid(), "wrongkey"); - fail("Exception not thrown"); - } catch (final NoSuchVerificationTokenException | TokenExpiredException e) { - - } - - try { - final VerificationToken ct = tokenVerificationService.consumeToken("purpose1", t.getUuid(), t.getKey()); - assertTrue("Token not consumed", ct != null); - } catch (final NoSuchVerificationTokenException e) { - fail("Token not found"); - } catch (final TokenExpiredException e) { - fail("Token has expired"); - } - - try { - tokenVerificationService.consumeToken("purpose1", t.getUuid(), t.getKey()); - fail("Token still found"); - } catch (final NoSuchVerificationTokenException | TokenExpiredException e) { - - } - } - - @Test(expected = NoSuchVerificationTokenException.class) - public void cancelException() throws NoSuchVerificationTokenException { - tokenVerificationService.cancel("no-such-uuid"); - fail("Token should not be found"); - } - - @Test - public void testGenerateAndCancel() { - final VerificationToken t = tokenVerificationService.generateToken("purpose1", null); - assertTrue("ID should be assigned", t.getId() != null); - assertTrue("UUID should be assigned", t.getUuid() != null); - assertTrue("Data should be null", t.getData() == null); - - try { - tokenVerificationService.cancel(t.getUuid()); - } catch (final NoSuchVerificationTokenException e) { - fail("Token not canceled"); - } - - try { - tokenVerificationService.cancel(t.getUuid()); - fail("Exception expected!"); - } catch (final NoSuchVerificationTokenException e) { - - } - } - - @Test - public void consumeTokenNoExceptions() { - final VerificationToken t = tokenVerificationService.generateToken("purpose1", null); - assertTrue("Token not created", t != null); - - try { - tokenConsumerService.noExceptions(t); - } catch (final NoSuchVerificationTokenException e) { - fail("Token not found"); - } catch (TokenExpiredException e) { - fail("Token has expired"); - } - - try { - tokenVerificationService.consumeToken(t.getPurpose(), t.getUuid(), t.getKey()); - fail("Token should not be available"); - } catch (final NoSuchVerificationTokenException | TokenExpiredException e) { - } - } - - @Test - public void testTokenAfterRuntime() { - final VerificationToken t = tokenVerificationService.generateToken("purpose1", null); - assertTrue("Token not created", t != null); - try { - tokenConsumerService.throwRuntimeException(t); - fail("RuntimeException expected"); - } catch (final NoSuchVerificationTokenException e) { - fail("Token not found"); - } catch (TokenExpiredException e) { - fail("Token has expired"); - } catch (final RuntimeException e) { - // ok - } - - try { - tokenVerificationService.consumeToken(t.getPurpose(), t.getUuid(), t.getKey()); - } catch (final NoSuchVerificationTokenException | TokenExpiredException e) { - fail("Token should still be available"); - } - } - - @Test - public void testTokenException() { - final VerificationToken t = tokenVerificationService.generateToken("purpose1", null); - assertTrue("Token not created", t != null); - try { - tokenConsumerService.throwException(t); - fail("Exception expected"); - } catch (final Exception e) { - // ok - } - - try { - tokenVerificationService.consumeToken(t.getPurpose(), t.getUuid(), t.getKey()); - } catch (final NoSuchVerificationTokenException | TokenExpiredException e) { - fail("Token should still be available"); - } - } - - @Test - public void noConsume() { - try { - tokenConsumerService.noToken(); - fail("Token should not be found"); - } catch (final NoSuchVerificationTokenException | TokenExpiredException e) { - - } - } - - @Test(expected = TokenExpiredException.class) - public void verificationTokenExpiredTest() throws TokenExpiredException, NoSuchVerificationTokenException { - VerificationToken token = tokenVerificationService.generateToken("purpose1", null); - assertTrue("ID should be assigned", token.getId() != null); - assertTrue("UUID should be assigned", token.getUuid() != null); - assertTrue("Data should be null", token.getData() == null); - - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.HOUR_OF_DAY, -1); - token.setValidUntil(calendar.getTime()); - token = tokenRepository.save(token); - - tokenVerificationService.consumeToken(token.getPurpose(), token.getUuid(), token.getKey()); - } -} diff --git a/src/test/java/org/genesys2/server/test/UrlrewriteTest.java b/src/test/java/org/genesys2/server/test/UrlrewriteTest.java deleted file mode 100644 index a241cd753835255cc2719e14cf885e1994828514..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/server/test/UrlrewriteTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 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.genesys2.server.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Test; - -public class UrlrewriteTest { - - @Test - public void testOnlyLang() { - Pattern p = Pattern.compile("^/([^?]+)\\?lang=([a-z]{2})$"); - Matcher m; - m = p.matcher("/hello.world"); - assertFalse(m.matches()); - m = p.matcher("/some/url?lang=de"); - assertTrue(m.matches()); - System.err.println(m.group(1)); - assertTrue("some/url".equals(m.group(1))); - assertTrue("de".equals(m.group(2))); - } - - @Test - public void test1() { - Pattern p = Pattern.compile("^/([^?]+)(?:\\?(.*)&|\\?)lang=([a-z]{2})(.*)$"); - Matcher m; - m = p.matcher("/some/url?lang=de&foo=bar&1=2"); - assertTrue(m.matches()); - System.err.println(m.group(1)); - assertTrue("some/url".equals(m.group(1))); - assertTrue(m.group(2) == null || "".equals(m.group(2))); - assertTrue("de".equals(m.group(3))); - assertTrue("&foo=bar&1=2".equals(m.group(4))); - - m = p.matcher("/some/url?demo=1,2,3&lang=de&foo=bar&1=2"); - assertTrue(m.matches()); - System.err.println(m.group(1)); - assertTrue("some/url".equals(m.group(1))); - assertTrue("demo=1,2,3".equals(m.group(2))); - assertTrue("de".equals(m.group(3))); - assertTrue("&foo=bar&1=2".equals(m.group(4))); - - m = p.matcher("/some/url?demo=1,2,3&foo=bar&1=2&lang=de"); - assertTrue(m.matches()); - System.err.println(m.group(1)); - assertTrue("some/url".equals(m.group(1))); - assertTrue("demo=1,2,3&foo=bar&1=2".equals(m.group(2))); - assertTrue("de".equals(m.group(3))); - assertTrue(m.group(4)==null || "".equals(m.group(4))); - - } -} diff --git a/src/test/java/org/genesys2/tests/BaseSpringTest.java b/src/test/java/org/genesys2/tests/BaseSpringTest.java deleted file mode 100644 index 0a1be2a23d7ac25a42ee22f8f834483935735ab5..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/BaseSpringTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.genesys2.tests; - -import org.genesys.blocks.security.component.AclAssignerAspect; -import org.genesys2.server.test.JpaDataConfig; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.spring.config.ElasticsearchConfig; -import org.genesys2.spring.config.HazelcastConfig; -import org.genesys2.spring.config.CacheConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; - -@Configuration -@TestPropertySource({ "classpath:application.properties", "classpath:spring/spring.properties" }) -@ActiveProfiles("dev") -@ContextConfiguration(name = "root", classes = { JpaDataConfig.class, HazelcastConfig.class, ElasticsearchConfig.class, CacheConfig.class }, initializers = PropertyPlacholderInitializer.class) -public abstract class BaseSpringTest { - - @Bean - public AclAssignerAspect aclAssignerAspect() { - return new AclAssignerAspect(); - } -} \ No newline at end of file diff --git a/src/test/java/org/genesys2/tests/resttests/AbstractRestTest.java b/src/test/java/org/genesys2/tests/resttests/AbstractRestTest.java deleted file mode 100644 index ebb636fb3ac41c7a91e15fa734174f3e2399391c..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/AbstractRestTest.java +++ /dev/null @@ -1,726 +0,0 @@ -/* - * Copyright 2016 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.genesys2.tests.resttests; - -import java.io.File; -import java.util.Set; - -import org.apache.velocity.app.VelocityEngine; -import org.elasticsearch.common.collect.Sets; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.oauth.persistence.AccessTokenRepository; -import org.genesys.blocks.oauth.persistence.OAuthClientRepository; -import org.genesys.blocks.oauth.persistence.RefreshTokenRepository; -import org.genesys.blocks.oauth.service.OAuthClientDetailsService; -import org.genesys.blocks.oauth.service.OAuthServiceImpl; -import org.genesys.blocks.security.persistence.AclClassPersistence; -import org.genesys.blocks.security.persistence.AclEntryPersistence; -import org.genesys.blocks.security.persistence.AclObjectIdentityPersistence; -import org.genesys.blocks.security.persistence.AclSidPersistence; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.PasswordPolicy; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys.blocks.security.service.impl.SimplePasswordPolicy; -import org.genesys.catalog.service.ShortFilterService; -import org.genesys.catalog.service.impl.ShortFilterServiceImpl; -import org.genesys.filerepository.persistence.RepositoryFilePersistence; -import org.genesys.filerepository.service.BytesStorageService; -import org.genesys.filerepository.service.ImageGalleryService; -import org.genesys.filerepository.service.RepositoryService; -import org.genesys.filerepository.service.ThumbnailGenerator; -import org.genesys.filerepository.service.impl.FilesystemStorageServiceImpl; -import org.genesys.filerepository.service.impl.ImageGalleryServiceImpl; -import org.genesys.filerepository.service.impl.RepositoryServiceImpl; -import org.genesys.filerepository.service.impl.ThumbnailGenerator1; -import org.genesys.glis.v1.api.GenesysApi; -import org.genesys2.brapi.service.impl.BrAPIServiceImpl; -import org.genesys2.server.api.admin.v0.CacheController; -import org.genesys2.server.api.admin.v0.KPIController; -import org.genesys2.server.api.v0.AccessionController; -import org.genesys2.server.api.v0.CropsController; -import org.genesys2.server.api.v0.DatasetController; -import org.genesys2.server.api.v0.InstituteGalleriesController; -import org.genesys2.server.api.v0.LookupController; -import org.genesys2.server.api.v0.MeController; -import org.genesys2.server.api.v0.OrganizationController; -import org.genesys2.server.api.v0.PermissionController; -import org.genesys2.server.api.v0.RequestsController; -import org.genesys2.server.api.v0.TraitsController; -import org.genesys2.server.api.v0.UsersController; -import org.genesys2.server.api.v1.SubsetController; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.aspect.GenesysImageGalleryAspects; -import org.genesys2.server.mvc.admin.OAuthManagementController; -import org.genesys2.server.persistence.AccessionHistoricRepository; -import org.genesys2.server.persistence.AccessionRepository; -import org.genesys2.server.persistence.ArticleRepository; -import org.genesys2.server.persistence.CountryRepository; -import org.genesys2.server.persistence.CropRepository; -import org.genesys2.server.persistence.CropRuleRepository; -import org.genesys2.server.persistence.FaoInstituteRepository; -import org.genesys2.server.persistence.FaoInstituteSettingRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepositoryCustomImpl; -import org.genesys2.server.persistence.MaterialRequestRepository; -import org.genesys2.server.persistence.MaterialSubRequestRepository; -import org.genesys2.server.persistence.MetadataMethodRepository; -import org.genesys2.server.persistence.MetadataRepository; -import org.genesys2.server.persistence.MethodRepository; -import org.genesys2.server.persistence.OrganizationRepository; -import org.genesys2.server.persistence.ParameterCategoryRepository; -import org.genesys2.server.persistence.ParameterRepository; -import org.genesys2.server.persistence.Taxonomy2Repository; -import org.genesys2.server.persistence.TeamRepository; -import org.genesys2.server.persistence.TraitValueRepository; -import org.genesys2.server.persistence.TraitValueRepositoryImpl; -import org.genesys2.server.persistence.UserRepository; -import org.genesys2.server.persistence.domain.mock.TraitServiceMock; -import org.genesys2.server.persistence.kpi.KPIParameterRepository; -import org.genesys2.server.persistence.kpi.ObservationRepository; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.DatasetService; -import org.genesys2.server.service.EMailService; -import org.genesys2.server.service.EMailVerificationService; -import org.genesys2.server.service.EasySMTA; -import org.genesys2.server.service.ElasticSearchManagementService; -import org.genesys2.server.service.ElasticService; -import org.genesys2.server.service.GenesysFilterService; -import org.genesys2.server.service.GenesysRESTService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoRegionService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteFilesService; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.KPIService; -import org.genesys2.server.service.MappingService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.RequestService; -import org.genesys2.server.service.SubsetService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.TeamService; -import org.genesys2.server.service.TokenVerificationService; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.impl.ContentServiceImpl; -import org.genesys2.server.service.impl.CropServiceImpl; -import org.genesys2.server.service.impl.EMailServiceImpl; -import org.genesys2.server.service.impl.EMailVerificationServiceImpl; -import org.genesys2.server.service.impl.EasySMTAMockConnector; -import org.genesys2.server.service.impl.ElasticSearchManagementServiceImpl; -import org.genesys2.server.service.impl.ElasticsearchSearchServiceImpl; -import org.genesys2.server.service.impl.FilterHandler; -import org.genesys2.server.service.impl.GenesysFilterServiceImpl; -import org.genesys2.server.service.impl.GenesysRESTServiceImpl; -import org.genesys2.server.service.impl.GenesysServiceImpl; -import org.genesys2.server.service.impl.GeoRegionServiceImpl; -import org.genesys2.server.service.impl.GeoServiceImpl; -import org.genesys2.server.service.impl.InstituteFilesServiceImpl; -import org.genesys2.server.service.impl.InstituteServiceImpl; -import org.genesys2.server.service.impl.KPIServiceImpl; -import org.genesys2.server.service.impl.MappingServiceImpl; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.OrganizationServiceImpl; -import org.genesys2.server.service.impl.RequestServiceImpl; -import org.genesys2.server.service.impl.SubsetServiceImpl; -import org.genesys2.server.service.impl.TaxonomyManager; -import org.genesys2.server.service.impl.TaxonomyServiceImpl; -import org.genesys2.server.service.impl.TeamServiceImpl; -import org.genesys2.server.service.impl.TokenVerificationServiceImpl; -import org.genesys2.server.service.impl.UserServiceImpl; -import org.genesys2.server.service.worker.AccessionCounter; -import org.genesys2.server.service.worker.AccessionUploader; -import org.genesys2.server.service.worker.ElasticUpdater; -import org.genesys2.server.service.worker.GeoRegionDataCLDR; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.tests.BaseSpringTest; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.HierarchyMode; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.ContextHierarchy; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IQueue; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextHierarchy(@ContextConfiguration(name = "this", classes = { AbstractRestTest.Config.class }, initializers = PropertyPlacholderInitializer.class)) -@EnableAspectJAutoProxy -@ActiveProfiles("dev") -@WebAppConfiguration -public abstract class AbstractRestTest extends BaseSpringTest { - - @Configuration - @EnableWebMvc - @EnableAspectJAutoProxy - @ComponentScan(basePackages = { "org.genesys2.server.brapi" }) - @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL, classMode = DirtiesContext.ClassMode.AFTER_CLASS) - public static class Config { - - @Bean - public SubsetService subsetService() { - return new SubsetServiceImpl(); - } - - @Bean - public GenesysImageGalleryAspects imageGalleryAspects() { - // This thing makes galleries auto-fill with images - return new GenesysImageGalleryAspects(); - } - - @Bean - public InstituteGalleriesController instGalleriesController() { - return new InstituteGalleriesController(); - } - - @Bean - public InstituteFilesService instituteFilesService() { - return new InstituteFilesServiceImpl(); - } - - @Bean - public RepositoryService repositoryService() { - return new RepositoryServiceImpl(); - } - - @Bean - public ImageGalleryService imageGalleryService() { - return new ImageGalleryServiceImpl(); - } - - @Bean - public ThumbnailGenerator thumbnailGenerator() { - return new ThumbnailGenerator1(); - } - - @Bean - public BytesStorageService bytesStorageService() { - FilesystemStorageServiceImpl fsss = new FilesystemStorageServiceImpl(); - fsss.setRepositoryBaseDirectory(new File("data/repository")); - return fsss; - } - - @Bean - public ShortFilterService shortFilterService() { - return new ShortFilterServiceImpl(); - } - - @Bean - public SubsetController subsetController() { - return new SubsetController(); - } - - @Bean - public RequestsController requestsController() { - return new RequestsController(); - } - - @Bean - public RequestService requestService() { - return new RequestServiceImpl(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public MeController meController() { - return new MeController(); - } - - @Bean - public CacheManager cacheManager() { - return new NoOpCacheManager(); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public PasswordPolicy passwordPolicy() { - return new SimplePasswordPolicy(); - } - - @Bean - public TeamService teamService() { - return new TeamServiceImpl(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public VelocityEngine velocityEngine() { - return new VelocityEngine(); - } - - @Bean - @Qualifier("genesysLowlevelRepositoryCustomImpl") - public GenesysLowlevelRepository genesysLowlevelRepositoryCustomImpl() { - return new GenesysLowlevelRepositoryCustomImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public UsersController restUsersController() { - return new UsersController(); - } - - @Bean - public OAuthServiceImpl oauthService() { - return new OAuthServiceImpl(); - } - - @Bean - public EMailVerificationService emailVerificationService() { - return new EMailVerificationServiceImpl(); - } - - @Bean - public TokenVerificationService tokenVerificationService() { - return new TokenVerificationServiceImpl(); - } - - @Bean - public EMailService eMailService() { - return new EMailServiceImpl(); - } - - @Bean - public JavaMailSender mailSender() { - return Mockito.mock(JavaMailSenderImpl.class); - } - - @Bean - public ThreadPoolTaskExecutor threadPoolTaskExecutor() { - return new ThreadPoolTaskExecutor(); - } - - @Bean - public TraitsController traitsController() { - return new TraitsController(); - } - - @Bean - public TraitService traitServiceMock() { - return new TraitServiceMock(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public TraitValueRepository traitValueRepository() { - return new TraitValueRepositoryImpl(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public LookupController lookupController() { - return new LookupController(); - } - - @Bean - public PermissionController permissionController() { - return new PermissionController(); - } - - @Bean - public OrganizationController organizationController() { - return new OrganizationController(); - } - - @Bean - public GenesysApi glisGenesysApi() { - return new GenesysApi(); - } - - @Bean - public TaxonomyManager taxonomyManager() { - return new TaxonomyManager(); - } - - @Bean - public EasySMTA easySMTAConnector() { - return new EasySMTAMockConnector(); - } - - @Bean - public OAuthManagementController oAuthManagementController() { - return new OAuthManagementController(); - } - - @Bean - public KPIController kpiController() { - return new KPIController(); - } - - @Bean - public KPIService kpiService() { - return new KPIServiceImpl(); - } - - @Bean - public DatasetController datasetController() { - return new DatasetController(); - } - - @Bean - public DatasetService datasetService() { - return new GenesysServiceImpl(); - } - - @Bean - public CropsController cropsController() { - return new CropsController(); - } - - @Bean - public CacheController cacheController() { - return new CacheController(); - } - - @Bean - public MappingService mappingService() { - return new MappingServiceImpl(); - } - - @Bean - public GenesysFilterService genesysFilterService() { - return new GenesysFilterServiceImpl(); - } - - @Bean - public AccessionUploader uploader() { - return new AccessionUploader(); - } - - @Bean - public AccessionCounter accessionCounter() { - return new AccessionCounter(); - } - - @Bean - public AccessionController accessionController() { - return new AccessionController(); - } - - @Bean - public GenesysRESTService genesysRESTService() { - return new GenesysRESTServiceImpl(); - } - - @Bean - public ElasticService elasticService() { - return new ElasticsearchSearchServiceImpl(); - } - - @Bean - public FilterHandler filterHandler() { - return new FilterHandler(); - } - - @Bean - public Jackson2ObjectMapperFactoryBean objectMapper() { - final Jackson2ObjectMapperFactoryBean mapperFactoryBean = new Jackson2ObjectMapperFactoryBean(); - mapperFactoryBean.setFeaturesToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - return mapperFactoryBean; - } - - @Bean - public ElasticSearchManagementService elasticSearchManagementService() { - return new ElasticSearchManagementServiceImpl(); - } - - @Bean - public ElasticUpdater elasticUpdater() { - return new ElasticUpdater(); - } - - @Bean - public ElasticUpdater.ElasticNode elasticNode() { - return null; - } - - @Bean - public IQueue elasticRemoveQueue(HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-remove"); - } - - @Bean - public IQueue elasticUpdateQueue(HazelcastInstance hazelcast) { - return hazelcast.getQueue("es-update"); - } - - @Bean - public BrAPIServiceImpl brapiService() { - return new BrAPIServiceImpl(); - } - - @Bean - public GeoRegionService geoRegionService() { - return new GeoRegionServiceImpl(); - } - - @Bean - public GeoRegionDataCLDR geoRegionDataCldr() { - return new GeoRegionDataCLDR(); - } - - @Bean - public static Set supportedLocales() { - final Set supportedLocales = Sets.newHashSet("en", "es", "de", "fr", "fa", "ar", "ru", "zh", "pt"); - return supportedLocales; - } - } - - @Autowired - protected AccessionHistoricRepository accessionHistoricRepository; - - @Autowired - protected CropRuleRepository cropRuleRepository; - - @Autowired - protected TaxonomyService taxonomyService; - - @Autowired - protected Taxonomy2Repository taxonomy2Repository; - - @Autowired - protected MetadataMethodRepository metadataMethodRepository; - - @Autowired - protected MetadataRepository metadataRepository; - - @Autowired - protected DatasetService datasetService; - - @Autowired - protected ObservationRepository observationRepository; - - @Autowired - protected KPIParameterRepository kpiParameterRepository; - - @Autowired - protected KPIService kpiService; - // @Autowired protected - // OAuthManagementController oAuthManagementController; - - @Autowired - protected AccessTokenRepository accessTokenPersistence; - - @Autowired - protected RefreshTokenRepository refreshTokenPersistence; - - @Autowired - protected OAuthClientRepository clientDetailsPersistence; - - @Autowired - protected OAuthClientDetailsService clientDetailsService; - - @Autowired - protected TokenStore tokenStore; - - @Autowired - protected EasySMTA easySMTAConnector; - - @Autowired - protected JavaMailSender mailSender; - - @Autowired - protected AccessionRepository accessionRepository; - - @Autowired - protected PermissionController permissionController; - - @Autowired - protected GeoService geoService; - - @Autowired - protected CountryRepository countryRepository; - - @Autowired - protected FaoInstituteRepository instituteRepository; - - @Autowired - protected FaoInstituteSettingRepository instituteSettingRepository; - - @Autowired - protected MethodRepository methodRepository; - - @Autowired - protected LookupController lookupController; - - @Autowired - protected TraitsController traitsController; - - @Autowired - protected @Qualifier("traitServiceMock") TraitService traitService; - - @Autowired - protected ArticleRepository articleRepository; - - @Autowired - protected ContentService contentService; - - @Autowired - protected JavaMailSender javaMailSender; - - @Autowired - protected UsersController restUsersController; - - @Autowired - protected UserService userService; - - @Autowired - protected MeController meController; - - @Autowired - protected UserRepository userPersistence; - - @Autowired - protected InstituteService instituteService; - - @Autowired - protected TeamRepository teamRepository; - - @Autowired - protected CustomAclService aclService; - - @Autowired - protected AclSidPersistence aclSidPersistence; - - @Autowired - protected AclEntryPersistence aclEntryPersistence; - - @Autowired - protected AclObjectIdentityPersistence aclObjectIdentityPersistence; - - @Autowired - protected AclClassPersistence aclClassPersistence; - - @Autowired - protected TeamService teamService; - - @Autowired - protected GenesysService genesysService; - - @Autowired - protected CropService cropService; - - @Autowired - protected CropRepository cropRepository; - - @Autowired - protected ParameterRepository parameterRepository; - - @Autowired - protected ParameterCategoryRepository parameterCategoryRepository; - - @Autowired - protected OrganizationService organizationService; - - @Autowired - protected OrganizationRepository organizationRepository; - - @Autowired - protected RequestService requestService; - - @Autowired - protected MaterialRequestRepository materialRequestRepository; - - @Autowired - protected MaterialSubRequestRepository materialSubRequestRepository; - - @Autowired - protected RepositoryFilePersistence repositoryFileRepository; -} diff --git a/src/test/java/org/genesys2/tests/resttests/KPIControllerTest.java b/src/test/java/org/genesys2/tests/resttests/KPIControllerTest.java deleted file mode 100644 index 345a90575c83124396531ef55005e525f67a477a..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/KPIControllerTest.java +++ /dev/null @@ -1,351 +0,0 @@ -package org.genesys2.tests.resttests; - -import static org.hamcrest.Matchers.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.genesys2.server.api.model.ExecutionJson; -import org.genesys2.server.model.kpi.BooleanDimension; -import org.genesys2.server.model.kpi.Dimension; -import org.genesys2.server.model.kpi.DimensionKey; -import org.genesys2.server.model.kpi.Execution; -import org.genesys2.server.model.kpi.ExecutionRun; -import org.genesys2.server.model.kpi.KPIParameter; -import org.genesys2.server.model.kpi.Observation; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -// FIXME tearDown() method not using @Transactional -@Ignore -public class KPIControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(KPIControllerTest.class); - - @Autowired - private WebApplicationContext webApplicationContext; - - MockMvc mockMvc; - - private KPIParameter kpiParameter; - private Dimension dimension; - private Execution execution; - private Observation observation; - private ExecutionRun executionRun; - private DimensionKey dimensionKey; - - @Before - public void setUp() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - - dimension = new BooleanDimension(); - dimension.setVersion(1); - dimension.setTitle("DimensionTitle"); - dimension.setName("DimensionName"); - - dimensionKey = new DimensionKey(); - dimensionKey.setName("NameDimKey"); - dimensionKey.setValue("ValueDimKey"); - - kpiParameter = new KPIParameter(); - kpiParameter.setName("KPIParamName"); - kpiParameter.setTitle("KPIParamTitle"); - kpiParameter.setEntity(KPIParameter.class.getName()); - kpiParameter.setVersion(1); - kpiParameter.setDescription("DescriptionKPI"); - - kpiService.save(kpiParameter); - kpiService.save(dimension); - - execution = new Execution(); - execution.setName("ExecutionName"); - execution.setVersion(1); - execution.setParameter(kpiParameter); - - executionRun = new ExecutionRun(); - - executionRun.setExecution(execution); - executionRun.setTimestamp(new Date()); - - observation = new Observation(); - observation.setExecutionRun(executionRun); - observation.setValue(1); - - Set dimensionKeys = new HashSet<>(); - dimensionKeys.add(dimensionKey); - - observation.setDimensions(dimensionKeys); - - kpiService.save(execution); - List observationList = new ArrayList<>(); - observationList.add(observation); - kpiService.save(execution, observationList); - } - - @After - public void tearDown() { - observationRepository.deleteAll(); - for (int i = kpiService.listExecutions().size() - 1; i >= 0; i--) { - kpiService.delete(kpiService.listExecutions().get(i)); - } - kpiParameterRepository.deleteAll(); - } - - @Test - public void listParametersTest() throws Exception { - LOG.info("Start test-method listParametersTest"); - - mockMvc.perform(get("/api/v0/kpi/parameter/list") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.KPIParamName", is("KPIParamTitle\nDescriptionKPI"))); - - LOG.info("Test listParametersTest passed"); - } - - @Test - public void getParameterTest() throws Exception { - LOG.info("Start test-method getParameterTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/kpi/parameter/{name}", "KPIParamName") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(kpiParameter))); - - LOG.info("Test getParameterTest passed"); - } - - @Test - public void deleteParameterTest() throws Exception { - LOG.info("Start test-method deleteParameterTest"); - - observationRepository.deleteAll(); - for (int i = kpiService.listExecutions().size() - 1; i >= 0; i--) { - kpiService.delete(kpiService.listExecutions().get(i)); - } - - mockMvc.perform(delete("/api/v0/kpi/parameter/{name}", "KPIParamName") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(nullValue()))) - .andExpect(jsonPath("$.name", is("KPIParamName"))) - .andExpect(jsonPath("$.title", is("KPIParamTitle"))) - .andExpect(jsonPath("$.entity", is(KPIParameter.class.getName()))) - .andExpect(jsonPath("$.description", is("DescriptionKPI"))); - - LOG.info("Test deleteParameterTest passed"); - } - - @Test - public void createParameterTest() throws Exception { - LOG.info("Start test-method createParameterTest"); - - tearDown(); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(post("/api/v0/kpi/parameter") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(kpiParameter))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(notNullValue()))) - .andExpect(jsonPath("$.name", is("KPIParamName"))) - .andExpect(jsonPath("$.title", is("KPIParamTitle"))) - .andExpect(jsonPath("$.entity", is(KPIParameter.class.getName()))) - .andExpect(jsonPath("$.description", is("DescriptionKPI"))); - - LOG.info("Test createParameterTest passed"); - } - - @Test - public void listDimensionsTest() throws Exception { - LOG.info("Start test-method listDimensionsTest"); - - mockMvc.perform(get("/api/v0/kpi/dimension/list") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$." + dimension.getId(), is(dimension.getName() + " " + dimension.getTitle()))); - - LOG.info("Test listDimensionsTest passed"); - } - - @Test - public void getDimensionTest() throws Exception { - LOG.info("Start test-method getDimensionTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/kpi/dimension/{id}", dimension.getId()) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(dimension))); - - LOG.info("Test getDimensionTest passed"); - } - - @Test - public void deleteDimensionTest() throws Exception { - LOG.info("Start test-method deleteDimensionTest"); - - mockMvc.perform(delete("/api/v0/kpi/dimension/{id}", dimension.getId()) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(nullValue()))) - .andExpect(jsonPath("$.name", is("DimensionName"))) - .andExpect(jsonPath("$.title", is("DimensionTitle"))); - - LOG.info("Test deleteDimensionTest passed"); - } - - @Test - public void updateBooleanDimensionTest() throws Exception { - LOG.info("Start test-method updateBooleanDimensionTest"); - - tearDown(); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(post("/api/v0/kpi/dimension") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(dimension))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(dimension.getId().intValue()))) - .andExpect(jsonPath("$.name", is("DimensionName"))) - .andExpect(jsonPath("$.title", is("DimensionTitle"))); - - LOG.info("Test updateBooleanDimensionTest passed"); - } - - @Test - public void listExecutionTest() throws Exception { - LOG.info("Start test-method listExecutionTest"); - - mockMvc.perform(get("/api/v0/kpi/execution/list") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$." + execution.getName(), is(execution.getTitle()))); - - LOG.info("Test listExecutionTest passed"); - } - - @Test - public void getExecutionTest() throws Exception { - LOG.info("Start test-method getExecutionTest"); - - mockMvc.perform(get("/api/v0/kpi/execution/{executionName}", execution.getName()) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(execution.getId().intValue()))) - .andExpect(jsonPath("$.name", is(execution.getName()))) - .andExpect(jsonPath("$.version", is((int) execution.getVersion()))) - .andExpect(jsonPath("$.parameter", is(execution.getParameter().getName()))) - .andExpect(jsonPath("$.title", isEmptyOrNullString())) - .andExpect(jsonPath("$.dimensions", hasSize(0))); - - LOG.info("Test getExecutionTest passed"); - } - - @Test - public void deleteExecutionTest() throws Exception { - LOG.info("Start test-method deleteExecutionTest"); - observationRepository.deleteAll(); - mockMvc.perform(delete("/api/v0/kpi/execution/{executionName}", execution.getName()) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(nullValue()))) - .andExpect(jsonPath("$.name", is(execution.getName()))) - .andExpect(jsonPath("$.version", is((int) execution.getVersion()))) - .andExpect(jsonPath("$.parameter", is(execution.getParameter().getName()))) - .andExpect(jsonPath("$.title", is(execution.getTitle()))); - - LOG.info("Test deleteExecutionTest passed"); - } - - @Test - public void listObservationsTest() throws Exception { - LOG.info("Start test-method listObservationsTest"); - - mockMvc.perform(post("/api/v0/kpi/observation/{executionName}/", execution.getName()) - .contentType(MediaType.APPLICATION_JSON) - .param("page", "1")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(1))) - .andExpect(jsonPath("$[0].id", is(notNullValue()))) - .andExpect(jsonPath("$[0].value", is(1.0))) - .andExpect(jsonPath("$[0].dimensions", hasSize(1))) - .andExpect(jsonPath("$[0].dimensionCount", is(1))); - - LOG.info("Test listObservationsTest passed"); - } - - @Test - public void executeTest() throws Exception { - LOG.info("Start test-method executeTest"); - - mockMvc.perform(post("/api/v0/kpi/execution/{executionName}/execute", execution.getName()) - .contentType(MediaType.APPLICATION_JSON) - .param("page", "1")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(1))) - .andExpect(jsonPath("$[0].id", is(notNullValue()))) - .andExpect(jsonPath("$[0].value", is(1.0))) - .andExpect(jsonPath("$[0].dimensions", hasSize(0))) - .andExpect(jsonPath("$[0].dimensionCount", is(0))); - - LOG.info("Test executeTest passed"); - } - - @Test - public void updateExecutionTest() throws Exception { - LOG.info("Start test-method updateExecutionTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - ExecutionJson executionJson = ExecutionJson.from(execution); - - mockMvc.perform(post("/api/v0/kpi/execution") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(executionJson))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id", is(notNullValue()))) - .andExpect(jsonPath("$.name", is("ExecutionName"))) - .andExpect(jsonPath("$.version", is(1))) - .andExpect(jsonPath("$.parameter", is("KPIParamName"))) - .andExpect(jsonPath("$.title", is(nullValue()))) - .andExpect(jsonPath("$.dimensions", hasSize(0))); - - LOG.info("Test updateExecutionTest passed"); - } -} diff --git a/src/test/java/org/genesys2/tests/resttests/OrganizationControllerTest.java b/src/test/java/org/genesys2/tests/resttests/OrganizationControllerTest.java deleted file mode 100644 index 97b6521255ca75ad2aa1fbada28047b31fc6cffd..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/OrganizationControllerTest.java +++ /dev/null @@ -1,254 +0,0 @@ -package org.genesys2.tests.resttests; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.genesys2.server.api.v0.OrganizationController; -import org.genesys2.server.model.impl.Article; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.model.impl.Organization; -import org.genesys2.server.service.CRMException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageRequest; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.context.WebApplicationContext; - -public class OrganizationControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(OrganizationControllerTest.class); - - @Autowired - private WebApplicationContext webApplicationContext; - - MockMvc mockMvc; - - private Organization organization; - private Article article; - private FaoInstitute faoInstitute; - private List institutes = new ArrayList<>(); - - @Before - public void setUp() throws CRMException { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - - organization = organizationService.create("slugOrganization", "TitleOrganization"); - - faoInstitute = new FaoInstitute(); - faoInstitute.setFullName("This is name of institute"); - faoInstitute.setCurrent(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setMaintainsCollection(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setAccessionCount(1); - faoInstitute.setUniqueAcceNumbs(true); - faoInstitute.setCode("Code"); - - institutes.add(faoInstitute); - instituteService.update(institutes); - - organization.setMembers(institutes); - - article = contentService.updateArticle(organization, "blurp", organization.getTitle(), "Body", null, Locale.ENGLISH); - } - - @After - public void tearDown() { - - organizationRepository.deleteAll(); - articleRepository.deleteAll(); - instituteRepository.deleteAll(); - } - - @Test - public void listOrganizationsTest() throws Exception { - LOG.info("Start test-method listOrganizationsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/org") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .param("page", "1")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(organizationService.list(new PageRequest(0, 10)).getContent()))); - - LOG.info("Test listOrganizationsTest is passed"); - } - - @Test - public void updateOrganizationTest() throws Exception { - LOG.info("Start test-method updateOrganizationTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - organization.setTitle("newTitle"); - - mockMvc.perform(post("/api/v0/org") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(organization))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(organization))); - - LOG.info("Test updateOrganizationTest is passed"); - } - - @Test - public void getOrganizationTest() throws Exception { - LOG.info("Start test-method getOrganizationTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/org/{shortName}", organization.getSlug()) - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) - .andExpect(content().string(objectMapper.writeValueAsString(organization))); - - LOG.info("Test getOrganizationTest is passed"); - } - - @Test - public void getBlurpTest() throws Exception { - LOG.info("Start test-method getBlurpTest"); - - mockMvc.perform(get("/api/v0/org/{shortName}/blurp/{language}", organization.getSlug(), article.getLang()) - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) - .andExpect(content().string(article.getBody())); - - LOG.info("Test getBlurpTest is passed"); - } - - @Test - public void updateBlurpTest() throws Exception { - LOG.info("Start test-method updateBlurpTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - OrganizationController.OrganizationBlurpJson organizationBlurpJson = new OrganizationController.OrganizationBlurpJson(); - organizationBlurpJson.blurp = "newBlurp"; - organizationBlurpJson.locale = "en"; - - mockMvc.perform(put("/api/v0/org/{shortName}/blurp", organization.getSlug()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(organizationBlurpJson))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(organizationService.updateAbout(organization, organizationBlurpJson.blurp, organizationBlurpJson.summary, organizationBlurpJson.getLocale())))); - - LOG.info("test updateBlurpTest is passed"); - } - - @Test - public void deleteOrganizationTest() throws Exception { - LOG.info("Start test-method deleteOrganizationTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - organization.setId(null); - - mockMvc.perform(delete("/api/v0/org/{shortName}", organization.getSlug()) - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(organization))); - - LOG.info("test deleteOrganizationTest is passed"); - } - - @Test - public void getOrganizationMembersTest() throws Exception { - LOG.info("Start test-method getOrganizationMembersTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/org/{shortName}/institutes", organization.getSlug()) - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(organizationService.getMembers(organizationService.getOrganization(organization.getSlug()))))); - - LOG.info("test getOrganizationMembersTest is passed"); - } - - @Test - @Transactional - public void addOrganizationInstitutesTest() throws Exception { - LOG.info("Start test-method addOrganizationInstitutesTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - List instituteList = new ArrayList<>(); - - FaoInstitute secondFaoInstitute = new FaoInstitute(); - secondFaoInstitute.setFullName("This is name of second institute"); - secondFaoInstitute.setCurrent(true); - secondFaoInstitute.setPgrActivity(true); - secondFaoInstitute.setMaintainsCollection(true); - secondFaoInstitute.setPgrActivity(true); - secondFaoInstitute.setAccessionCount(1); - secondFaoInstitute.setUniqueAcceNumbs(true); - secondFaoInstitute.setCode("SecondCode"); - - List faoInstituteList = new ArrayList<>(); - faoInstituteList.add(secondFaoInstitute); - instituteService.update(faoInstituteList); - - instituteList.add(faoInstitute.getCode()); - instituteList.add(secondFaoInstitute.getCode()); - - mockMvc.perform(post("/api/v0/org/{slug}/add-institutes", organization.getSlug()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(instituteList))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(true))); - - LOG.info("test addOrganizationInstitutesTest is passed"); - } - - @Test - @Transactional - public void setOrganizationInstitutesTest() throws Exception { - LOG.info("Start test-method setOrganizationInstitutesTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - List instituteList = new ArrayList<>(); - - FaoInstitute thirdFaoInstitute = new FaoInstitute(); - thirdFaoInstitute.setFullName("This is name of second institute"); - thirdFaoInstitute.setCurrent(true); - thirdFaoInstitute.setPgrActivity(true); - thirdFaoInstitute.setMaintainsCollection(true); - thirdFaoInstitute.setPgrActivity(true); - thirdFaoInstitute.setAccessionCount(1); - thirdFaoInstitute.setUniqueAcceNumbs(true); - thirdFaoInstitute.setCode("SecondCode"); - - List faoInstituteList = new ArrayList<>(); - faoInstituteList.add(thirdFaoInstitute); - instituteService.update(faoInstituteList); - - instituteList.add(faoInstitute.getCode()); - instituteList.add(thirdFaoInstitute.getCode()); - - mockMvc.perform(post("/api/v0/org/{slug}/set-institutes", organization.getSlug()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(instituteList))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().string(objectMapper.writeValueAsString(true))); - - LOG.info("test setOrganizationInstitutesTest is passed"); - } -} diff --git a/src/test/java/org/genesys2/tests/resttests/RequestsControllerTest.java b/src/test/java/org/genesys2/tests/resttests/RequestsControllerTest.java deleted file mode 100644 index 3cae79f52ee8465c720b03697f8588d099728f5a..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/RequestsControllerTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.genesys2.tests.resttests; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.genesys.blocks.security.UserException; -import org.genesys2.server.model.genesys.MaterialRequest; -import org.genesys2.server.model.genesys.MaterialSubRequest; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.service.CRMException; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.RequestService; -import org.genesys2.server.service.impl.EasySMTAException; -import org.genesys2.server.service.impl.RequestServiceImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.context.WebApplicationContext; - -@Transactional -@Ignore -public class RequestsControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(RequestsControllerTest.class); - - @Autowired - private WebApplicationContext webApplicationContext; - - MockMvc mockMvc; - - private MaterialRequest materialRequest; - private MaterialSubRequest materialSubRequest; - - private FaoInstitute faoInstitute; - private List institutes = new ArrayList<>(); - - @Before - public void setUp() throws UserException, JsonProcessingException, EasySMTAException, CRMException { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - - contentService.createGlobalArticle(ContentService.SMTP_MATERIAL_CONFIRM_NO_PID, contentService.getDefaultLocale(), "Missing PID", "Body", null, true); - - contentService.createGlobalArticle(ContentService.SMTP_MATERIAL_REQUEST, contentService.getDefaultLocale(), "Material request", "Body", null, true); - - ObjectMapper objectMapper = new ObjectMapper(); - - Set accessionsId = new HashSet<>(); - accessionsId.add(1L); - - RequestService.RequestInfo requestInfo = new RequestService.RequestInfo(); - requestInfo.setEmail("salexandrbasov@gmail.com"); - requestInfo.setNotes("notes"); - requestInfo.setPreacceptSMTA(false); - requestInfo.setPurposeType(1); - - RequestServiceImpl.RequestBody requestBody = new RequestServiceImpl.RequestBody(); - requestBody.pid = easySMTAConnector.getUserData("salexandrbasov@gmail.com"); - requestBody.requestInfo = requestInfo; - requestBody.accessionIds = accessionsId; - - materialRequest = new MaterialRequest(); - materialRequest.setEmail("salexandrbasov@gmail.com"); - materialRequest.setVersion(1); - materialRequest.setBody(objectMapper.writeValueAsString(requestBody)); - materialRequestRepository.save(materialRequest); - - materialSubRequest = new MaterialSubRequest(); - materialSubRequest.setBody(objectMapper.writeValueAsString(requestBody)); - materialSubRequest.setInstCode("Code"); - materialSubRequest.setVersion(2); - materialSubRequest.setSourceRequest(materialRequest); - - materialSubRequestRepository.save(materialSubRequest); - - faoInstitute = new FaoInstitute(); - faoInstitute.setFullName("This is name of institute"); - faoInstitute.setCurrent(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setMaintainsCollection(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setAccessionCount(1); - faoInstitute.setUniqueAcceNumbs(true); - faoInstitute.setCode("Code"); - - institutes.add(faoInstitute); - instituteService.update(institutes); - - } - - @After - public void teerDown() { - materialSubRequestRepository.deleteAll(); - materialRequestRepository.deleteAll(); - articleRepository.deleteAll(); - } - - @Test - public void listRequestsTest() throws Exception { - LOG.info("Start test-method listRequestsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/requests").contentType(MediaType.APPLICATION_JSON).param("page", "0")).andExpect(status().isOk()).andExpect(content().contentType( - MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(requestService.list(new PageRequest(0, 10, new Sort(Sort.Direction.DESC, - "createdDate")))))); - - LOG.info("Test listRequestsTest passed"); - } - - @Test - public void getRequestTest() throws Exception { - LOG.info("Start test-method getRequestTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - MaterialRequest materialRequestForTest = requestService.list(new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "createdDate"))).getContent().get(0); - - mockMvc.perform(get("/api/v0/requests/r/{uuid}", materialRequestForTest.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content() - .contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(materialRequestForTest))); - - LOG.info("Test getRequestTest passed"); - } - - @Test - public void reconfirmRequestTest() throws Exception { - LOG.info("Start test-method reconfirmRequestTest"); - - MaterialRequest materialRequestForTest = requestService.list(new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "createdDate"))).getContent().get(0); - - mockMvc.perform(post("/api/v0/requests/r/{uuid}/reconfirm", materialRequestForTest.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect( - content().contentType(MediaType.APPLICATION_JSON)); - - LOG.info("Test reconfirmRequestTest passed"); - } - - @Test - public void validateRequestTest() throws Exception { - LOG.info("Start test-method validateRequestTest"); - - MaterialRequest materialRequestForTest = requestService.list(new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "createdDate"))).getContent().get(0); - materialRequestForTest.setSubRequests(materialSubRequestRepository.findAll()); - mockMvc.perform(post("/api/v0/requests/r/{uuid}/validate", materialRequestForTest.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect( - content().contentType(MediaType.APPLICATION_JSON)); - - LOG.info("Test validateRequestTest passed"); - } - - @Test - public void updatePidTest() throws Exception { - LOG.info("Start test-method updatePidTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - MaterialRequest materialRequestForTest = requestService.list(new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "createdDate"))).getContent().get(0); - materialRequestForTest.setSubRequests(materialSubRequestRepository.findAll()); - mockMvc.perform(post("/api/v0/requests/r/{uuid}/update-pid", materialRequestForTest.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect( - content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(requestService.recheckPid(materialRequestForTest)))); - - LOG.info("Test updatePidTest passed"); - } - - @Test - public void listInstituteRequestsTest() throws Exception { - LOG.info("Start test-method listInstituteRequestsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/requests/{instCode}", materialSubRequest.getInstCode()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content() - .contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(requestService.list(faoInstitute, new PageRequest(0, 10, new Sort( - Sort.Direction.DESC, "createdDate")))))); - - LOG.info("Test listInstituteRequestsTest passed"); - } - - @Test - public void getInstituteRequestTest() throws Exception { - LOG.info("Start test-method getInstituteRequestTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - mockMvc.perform(get("/api/v0/requests/{instCode}/r/{uuid}", materialSubRequest.getInstCode(), materialSubRequest.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect( - status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(requestService.get(faoInstitute, - materialSubRequest.getUuid())))); - - LOG.info("Test getInstituteRequestTest passed"); - } - -} diff --git a/src/test/java/org/genesys2/tests/resttests/TraitsControllerTest.java b/src/test/java/org/genesys2/tests/resttests/TraitsControllerTest.java deleted file mode 100644 index b10c2ca0d2b9afe39b984760de2b39f97f48c116..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/TraitsControllerTest.java +++ /dev/null @@ -1,259 +0,0 @@ -package org.genesys2.tests.resttests; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.List; - -import org.genesys.blocks.security.UserException; -import org.genesys.blocks.security.model.BasicUser.AccountType; -import org.genesys.blocks.security.serialization.Permissions; -import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException; -import org.genesys2.server.api.OAuth2Cleanup; -import org.genesys2.server.api.v0.TraitsController; -import org.genesys2.server.model.UserRole; -import org.genesys2.server.model.genesys.Method; -import org.genesys2.server.model.genesys.Parameter; -import org.genesys2.server.model.impl.Crop; -import org.genesys2.server.model.impl.User; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageRequest; -import org.springframework.http.MediaType; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Ignore -public class TraitsControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(TraitsControllerTest.class); - - @Autowired - private WebApplicationContext webApplicationContext; - - private MockMvc mockMvc; - - private Parameter parameter; - private Crop crop; - private Method method; - private User user; - - @Before - public void setUp() throws JsonProcessingException, UserException, PasswordPolicyException { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - - user = userService.createUser("salexandrbasov@gmail.com", "SYS_ADMIN", "Alexandr19011990", AccountType.LOCAL); - - ObjectMapper objectMapper = new ObjectMapper(); - - crop = cropService.addCrop("shortName", "Name", "description", "en"); - - traitService.addCategory("nameOfParameterCategory", objectMapper.writeValueAsString("en")); - - parameter = traitService.addParameter("rdfUri", crop, "nameOfParameterCategory", "titleOfParameter", objectMapper.writeValueAsString("en")); - - method = traitService.addMethod("rdfUriMethod", "descriptionMethod", objectMapper.writeValueAsString("en"), "unitForMethod", "fieldName", 1, 2, "options", "range", parameter); - - Permissions permission=new Permissions().grantNone(); - permission.create=true; - permission.manage=true; - - aclService.setPermissions(method, user, permission); - - List authorities = new ArrayList<>(); - GrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(UserRole.ADMINISTRATOR.getName()); - authorities.add(simpleGrantedAuthority); - - UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, user, authorities); - - SecurityContextHolder.getContext().setAuthentication(authToken); - - } - - @After - public void tearDown() { - methodRepository.deleteAll(); - parameterRepository.deleteAll(); - parameterCategoryRepository.deleteAll(); - cropRepository.deleteAll(); - userPersistence.deleteAll(); - aclObjectIdentityPersistence.deleteAll(); - aclClassPersistence.deleteAll(); - aclSidPersistence.deleteAll(); - aclEntryPersistence.deleteAll(); - } - - @Test - public void listTraitsTest() throws Exception { - LOG.info("Start test-method listTraitsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/descriptors") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(OAuth2Cleanup.clean(traitService.listTraits(new PageRequest(0, 50)))))); - - LOG.info("Test listTraitsTest passed"); - } - - @Test - public void listTraitsWithPageParamTest() throws Exception { - LOG.info("Start test-method listTraitsWithPageParamTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/descriptors/?{page}", 0) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(OAuth2Cleanup.clean(traitService.listTraits(new PageRequest(0, 50)))))); - - LOG.info("Test listTraitsWithPageParamTest passed"); - } - - @Test - public void listMethodsTest() throws Exception { - LOG.info("Start test-method listMethodsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/methods") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(OAuth2Cleanup.clean(traitService.listMethods(new PageRequest(0, 50)))))); - - LOG.info("Test listMethods passed!"); - } - - @Test - public void listMethodsWithPageParamTest() throws Exception { - LOG.info("Start test-method listMethodsWithPageParamTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/methods/?{page}", 0) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(OAuth2Cleanup.clean(traitService.listMethods(new PageRequest(0, 50)))))); - - LOG.info("Test listMethodsWithPageParamTest passed!"); - } - - @Test - public void listMyMethodsTest() throws Exception { - LOG.info("Start test-method listMyMethodsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/mymethods") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(OAuth2Cleanup.clean(traitService.listMyMethods())))); - - LOG.info("Test listMyMethodsTest passed!"); - } - - @Test - public void listCategoriesTest() throws Exception { - LOG.info("Start test-method listCategoriesTest"); - - ObjectMapper objectmapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/categories") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectmapper.writeValueAsString(traitService.listCategories()))); - - LOG.info("Test listMyCategoriesList passed!"); - } - - @Test - public void createCategoryTest() throws Exception { - LOG.info("Start test-method createCategoryTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - TraitsController.CategoryJson categoryJson = new TraitsController.CategoryJson(); - categoryJson.name = traitService.listCategories().get(0).getName(); - categoryJson.i18n = traitService.listCategories().get(0).getNameL(); - - mockMvc.perform(post("/api/v0/category") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(categoryJson))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(traitService.listCategories().get(0)))); - - LOG.info("Test createCategoryTest is passed"); - } - - @Test - public void createPropertyTest() throws Exception { - LOG.info("Start test-method createPropertyTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - TraitsController.PropertyJson propertyJson = new TraitsController.PropertyJson(); - propertyJson.category = "nameOfParameterCategory"; - propertyJson.rdfUri = "rdfUri"; - propertyJson.i18n = objectMapper.writeValueAsString("en"); - propertyJson.title = "titleOfParameter"; - - mockMvc.perform(post("/api/v0/{crop}/property", crop.getName()) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(propertyJson))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(parameter))); - - LOG.info("Test createPropertyTest is passed"); - } - - @Test - public void createMethodTest() throws Exception { - LOG.info("Start test-method createMethodTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - TraitsController.MethodJson methodJson = new TraitsController.MethodJson(); - methodJson.rdfUri = method.getRdfUri(); - methodJson.description = method.getMethod(); - methodJson.fieldName = method.getFieldName(); - methodJson.fieldSize = 10; - methodJson.fieldType = method.getFieldType(); - methodJson.i18n = objectMapper.writeValueAsString("en"); - methodJson.options = method.getOptions(); - methodJson.unit = method.getUnit(); - methodJson.range = method.getRange(); - - mockMvc.perform(post("/api/v0/{propertyId}/method", parameter.getId()) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(methodJson))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(method))); - - LOG.info("Test createMethodTest"); - } - -} diff --git a/src/test/java/org/genesys2/tests/resttests/UserControllerTest.java b/src/test/java/org/genesys2/tests/resttests/UserControllerTest.java deleted file mode 100644 index 67c5f320ea21302a1b3c66fab6756133cc01fe00..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/UserControllerTest.java +++ /dev/null @@ -1,219 +0,0 @@ -package org.genesys2.tests.resttests; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -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 java.util.ArrayList; -import java.util.List; - -import org.genesys.blocks.security.UserException; -import org.genesys.blocks.security.model.BasicUser.AccountType; -import org.genesys.blocks.security.serialization.Permissions; -import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException; -import org.genesys2.server.api.v0.MeController; -import org.genesys2.server.model.UserRole; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.model.impl.User; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -// FIXME @Transactional? -@Ignore -public class UserControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(UserControllerTest.class); - - @Autowired - private WebApplicationContext webApplicationContext; - - private MockMvc mockMvc; - - private User user = new User(); - private FaoInstitute faoInstitute; - private List institutes = new ArrayList<>(); - - @Before - public void setUp() throws UserException, PasswordPolicyException { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .build(); - - - faoInstitute = new FaoInstitute(); - faoInstitute.setFullName("This is name of institute"); - faoInstitute.setCurrent(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setMaintainsCollection(true); - faoInstitute.setPgrActivity(true); - faoInstitute.setAccessionCount(1); - faoInstitute.setUniqueAcceNumbs(true); - faoInstitute.setCode("Code"); - - user = userService.createUser("salexandrbasov@gmail.com", "SYS_ADMIN", "Alexandr19011990", AccountType.LOCAL); - - institutes.add(faoInstitute); - instituteService.update(institutes); - - Permissions permission=new Permissions().grantNone(); - permission.create=true; - permission.manage=true; - - aclService.setPermissions(faoInstitute, user, permission); - - List authorities = new ArrayList<>(); - GrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(UserRole.ADMINISTRATOR.getName()); - authorities.add(simpleGrantedAuthority); - - UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, user, authorities); - - SecurityContextHolder.getContext().setAuthentication(authToken); - - teamService.addTeam("name"); - } - - @After - public void tearDown() { - teamRepository.deleteAll(); - userPersistence.deleteAll(); - instituteSettingRepository.deleteAll(); - instituteRepository.deleteAll(); - - aclObjectIdentityPersistence.deleteAll(); - aclClassPersistence.deleteAll(); - aclSidPersistence.deleteAll(); - aclEntryPersistence.deleteAll(); - } - - @Test - public void getProfileTest() throws Exception { - LOG.info("Start test-method getProfileTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - user.setPassword(null); - user.setId(null); - - mockMvc.perform(get("/api/v0/me").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(user))); - - LOG.info("Test getProfileTest passed!"); - } - - @Test - public void listInstitutesTest() throws Exception { - LOG.info("Start test-method listInstitutesTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/me/institutes").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(institutes))); - - LOG.info("Test listInstitutesTest passed!"); - } - - @Test - public void listTeamsTest() throws Exception { - LOG.info("Start test-method listTeamsTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/me/teams").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(teamRepository.findAll()))); - - LOG.info("Test listTeamsTest passed"); - } - - @Test - public void createTeamTest() throws Exception { - LOG.info("Start test-method createTeamTest"); - - teamRepository.deleteAll(); - ObjectMapper objectMapper = new ObjectMapper(); - - MeController.TeamJson teamJson = new MeController.TeamJson(); - teamJson.name = "name"; - - mockMvc.perform(post("/api/v0/me/teams") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(teamJson))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.name").value("name")) - .andExpect(content().string(objectMapper.writeValueAsString(teamRepository.findAll().get(0)))); - - LOG.info("Test createTeamTest passed"); - } - - @Test - public void changeLockTest() throws Exception { - LOG.info("Start test-method changeLockTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(post("/api/v0/user/{uuid}/locked", user.getUuid()) - .contentType(MediaType.APPLICATION_JSON) - .content(Boolean.TRUE.toString())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(Boolean.TRUE))); - - - LOG.info("Test changeLockTest passed"); - } - - @Test - public void changeEnabled() throws Exception { - LOG.info("Start test-method changeEnabled"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(post("/api/v0/user/{uuid}/enabled", user.getUuid()) - .contentType(MediaType.APPLICATION_JSON) - .content(Boolean.TRUE.toString())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(objectMapper.writeValueAsString(Boolean.TRUE))); - - LOG.info("Test changeEnabled passed"); - } - - @Test - public void leaveTeamTest() throws Exception { - LOG.info("Start test-method leaveTeamTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode JSON_OK = objectMapper.readTree("{\"result\":true}"); - - mockMvc.perform(post("/api/v0/me/teams/{teamId}/leave", teamRepository.findAll().get(0).getId()) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(content().string(JSON_OK.toString())); - - LOG.info("Test leaveTeamTest passed"); - } -} diff --git a/src/test/java/org/genesys2/tests/resttests/UsersControllerTest.java b/src/test/java/org/genesys2/tests/resttests/UsersControllerTest.java deleted file mode 100644 index 2f4f0abf6173dfe067a56de4e1c25cb3b924355a..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/resttests/UsersControllerTest.java +++ /dev/null @@ -1,253 +0,0 @@ -package org.genesys2.tests.resttests; - -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.doNothing; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -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.status; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.genesys.blocks.security.UserException; -import org.genesys.blocks.security.model.BasicUser.AccountType; -import org.genesys.blocks.security.serialization.Permissions; -import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException; -import org.genesys2.server.api.model.UserChangedDataJson; -import org.genesys2.server.model.UserRole; -import org.genesys2.server.model.impl.FaoInstitute; -import org.genesys2.server.model.impl.User; -import org.genesys2.server.service.CRMException; -import org.genesys2.server.service.ContentService; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.mail.javamail.MimeMessagePreparator; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Ignore -public class UsersControllerTest extends AbstractRestTest { - - private static final Logger LOG = LoggerFactory.getLogger(UserControllerTest.class); - - @Autowired - private WebApplicationContext webApplicationContext; - - private MockMvc mockMvc; - - private User user = new User(); - private FaoInstitute faoInstitute; - private List institutes = new ArrayList<>(); - - @Before - public void setUp() throws UserException, PasswordPolicyException, CRMException { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - - contentService.createGlobalArticle(ContentService.SMTP_EMAIL_VERIFICATION, contentService.getDefaultLocale(), "Verify email", "

Tho BOdy of oneArticle authorities = new ArrayList<>(); - GrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(UserRole.USER.getName()); - authorities.add(simpleGrantedAuthority); - - UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, user, authorities); - - SecurityContextHolder.getContext().setAuthentication(authToken); - - teamService.addTeam("name of team"); - } - - @After - public void tearDown() { - teamRepository.deleteAll(); - userPersistence.deleteAll(); - instituteSettingRepository.deleteAll(); - instituteRepository.deleteAll(); - - aclObjectIdentityPersistence.deleteAll(); - aclClassPersistence.deleteAll(); - aclSidPersistence.deleteAll(); - aclEntryPersistence.deleteAll(); - - articleRepository.deleteAll(); - Mockito.reset(javaMailSender); - } - - @Test - public void getUsersTest() throws Exception { - LOG.info("Start test-method getUsersTest"); - ObjectMapper objectMapper = new ObjectMapper(); - mockMvc.perform(get("/api/v0/users").contentType(MediaType.APPLICATION_JSON).param("startRow", "0").param("pageSize", "1")).andExpect(status().isOk()).andExpect(content() - .contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(userService.listWrapped(0, 1)))); - LOG.info("Test getUsersTest passed"); - } - - @Test - public void getAvailableRolesTest() throws Exception { - LOG.info("Start test-method getAvailableRolesTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/users/available_roles").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentType( - MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(userService.listAvailableRoles()))); - - LOG.info("Test getAvailableRolesTest passed"); - } - - @Test - public void getUserTest() throws Exception { - LOG.info("Start test-method getUserTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - Map resultMap = new HashMap<>(); - resultMap.put("user", user); - resultMap.put("userTeams", teamService.listUserTeams(user)); - - mockMvc.perform(get("/api/v0/users/user/{id}", user.getId()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentType( - MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(resultMap))); - - LOG.info("Test getUserTest passed"); - } - - @Test - public void getUserByUuidTest() throws Exception { - LOG.info("Start test-method getUserByUuidTest"); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(get("/api/v0/users/user/uuid/{id:.+}", user.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentType( - MediaType.APPLICATION_JSON)).andExpect(content().string(objectMapper.writeValueAsString(user))); - - LOG.info("Test getUserByUuidTest passed"); - } - - @Test - public void saveUserTest() throws Exception { - LOG.info("Start test-method saveUserTest"); - - teamRepository.deleteAll(); - userPersistence.deleteAll(); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(put("/api/v0/users/user").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(user))).andExpect(status().isOk()); - - LOG.info("Test saveUserTest passed"); - } - - @Test - public void updateUserTest() throws Exception { - LOG.info("Start test-method updateUserTest"); - - teamRepository.deleteAll(); - userPersistence.deleteAll(); - - ObjectMapper objectMapper = new ObjectMapper(); - - mockMvc.perform(post("/api/v0/users/user").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(user))).andExpect(status().isOk()); - - LOG.info("Test updateUserTest passed"); - } - - @Test - public void updateDataTest() throws Exception { - LOG.info("Start test-method updateDataTest"); - - UserChangedDataJson userChangedDataJson = new UserChangedDataJson(); - userChangedDataJson.setPwd1("newPwd"); - userChangedDataJson.setPwd2("newPwd"); - userChangedDataJson.setName("newName"); - userChangedDataJson.setEmail("new@mail.ru"); - userChangedDataJson.setUuid(user.getUuid()); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode JSON_OK = objectMapper.readTree("{\"result\":true}"); - - mockMvc.perform(post("/api/v0/users/user/data").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(userChangedDataJson))).andExpect(status() - .isOk()).andExpect(content().string(objectMapper.writeValueAsString(JSON_OK))); - LOG.info("Test updateDataTest passed"); - } - - @Test - public void updateRolesTest() throws Exception { - LOG.info("Start test-method updateRolesTest"); - - UserChangedDataJson userChangedDataJson = new UserChangedDataJson(); - userChangedDataJson.setRoles(user.getRoles()); - userChangedDataJson.setUuid(user.getUuid()); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode JSON_OK = objectMapper.readTree("{\"result\":true}"); - - mockMvc.perform(post("/api/v0/users/user/roles").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(userChangedDataJson))).andExpect(status() - .isOk()).andExpect(content().string(objectMapper.writeValueAsString(JSON_OK))); - LOG.info("Test updateRolesTest passed"); - } - - @Test - public void sendEmailTest() throws Exception { - LOG.info("Start test-method sendEmailTest"); - - doNothing().when(javaMailSender).send(isA(MimeMessagePreparator.class)); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode JSON_OK = objectMapper.readTree("{\"result\":true}"); - - mockMvc.perform(get("/api/v0/users/user/{uuid:.+}/send", user.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string( - objectMapper.writeValueAsString(JSON_OK))); - - LOG.info("Test sendEmailTest passed"); - } - - @Test - public void addRoleVettedUser() throws Exception { - LOG.info("Start test-method addRoleVettedUser"); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode JSON_OK = objectMapper.readTree("{\"result\":true}"); - - mockMvc.perform(get("/api/v0/users/user/{uuid:.+}/vetted-user", user.getUuid()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string( - objectMapper.writeValueAsString(JSON_OK))); - - LOG.info("Test addRoleVettedUser passed"); - } -} diff --git a/src/test/java/org/genesys2/tests/unit/AbstractServicesTest.java b/src/test/java/org/genesys2/tests/unit/AbstractServicesTest.java deleted file mode 100644 index d060af0af57155d73d4424e264c997cd59339e5e..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/unit/AbstractServicesTest.java +++ /dev/null @@ -1,382 +0,0 @@ -/** - * Copyright 2015 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.genesys2.tests.unit; - -import java.util.Set; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.apache.velocity.app.VelocityEngine; -import org.elasticsearch.common.collect.Sets; -import org.genesys.blocks.auditlog.service.ClassPKService; -import org.genesys.blocks.auditlog.service.impl.ClassPKServiceImpl; -import org.genesys.blocks.persistence.ClassPKRepository; -import org.genesys.blocks.security.service.CustomAclService; -import org.genesys.blocks.security.service.PasswordPolicy; -import org.genesys.blocks.security.service.impl.CustomAclServiceImpl; -import org.genesys.blocks.security.service.impl.SimplePasswordPolicy; -import org.genesys.catalog.service.ShortFilterService; -import org.genesys.catalog.service.impl.ShortFilterServiceImpl; -import org.genesys2.server.aspect.AsAdminAspect; -import org.genesys2.server.persistence.ActivityPostRepository; -import org.genesys2.server.persistence.ArticleRepository; -import org.genesys2.server.persistence.CropRepository; -import org.genesys2.server.persistence.CropRuleRepository; -import org.genesys2.server.persistence.CropTaxonomyRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepository; -import org.genesys2.server.persistence.GenesysLowlevelRepositoryCustomImpl; -import org.genesys2.server.persistence.Taxonomy2Repository; -import org.genesys2.server.persistence.TeamRepository; -import org.genesys2.server.persistence.TraitValueRepository; -import org.genesys2.server.persistence.TraitValueRepositoryImpl; -import org.genesys2.server.persistence.UserRepository; -import org.genesys2.server.persistence.VerificationTokenRepository; -import org.genesys2.server.persistence.dataset.DSDescriptorRepository; -import org.genesys2.server.service.ContentService; -import org.genesys2.server.service.CropService; -import org.genesys2.server.service.DescriptorService; -import org.genesys2.server.service.EMailService; -import org.genesys2.server.service.EMailVerificationService; -import org.genesys2.server.service.ElasticSearchManagementService; -import org.genesys2.server.service.ElasticService; -import org.genesys2.server.service.GenesysFilterService; -import org.genesys2.server.service.GenesysService; -import org.genesys2.server.service.GeoRegionService; -import org.genesys2.server.service.GeoService; -import org.genesys2.server.service.HtmlSanitizer; -import org.genesys2.server.service.InstituteService; -import org.genesys2.server.service.MappingService; -import org.genesys2.server.service.OrganizationService; -import org.genesys2.server.service.TaxonomyService; -import org.genesys2.server.service.TeamService; -import org.genesys2.server.service.TokenVerificationService; -import org.genesys2.server.service.TraitService; -import org.genesys2.server.service.UserService; -import org.genesys2.server.service.impl.AuthUserDetailsService; -import org.genesys2.server.service.impl.ContentServiceImpl; -import org.genesys2.server.service.impl.CropServiceImpl; -import org.genesys2.server.service.impl.DescriptorServiceImpl; -import org.genesys2.server.service.impl.EMailServiceImpl; -import org.genesys2.server.service.impl.EMailVerificationServiceImpl; -import org.genesys2.server.service.impl.ElasticSearchManagementServiceImpl; -import org.genesys2.server.service.impl.ElasticsearchSearchServiceImpl; -import org.genesys2.server.service.impl.FilterHandler; -import org.genesys2.server.service.impl.GenesysFilterServiceImpl; -import org.genesys2.server.service.impl.GenesysServiceImpl; -import org.genesys2.server.service.impl.GeoRegionServiceImpl; -import org.genesys2.server.service.impl.GeoServiceImpl; -import org.genesys2.server.service.impl.InstituteServiceImpl; -import org.genesys2.server.service.impl.MappingServiceImpl; -import org.genesys2.server.service.impl.OWASPSanitizer; -import org.genesys2.server.service.impl.OrganizationServiceImpl; -import org.genesys2.server.service.impl.TaxonomyServiceImpl; -import org.genesys2.server.service.impl.TeamServiceImpl; -import org.genesys2.server.service.impl.TokenVerificationServiceImpl; -import org.genesys2.server.service.impl.TraitServiceImpl; -import org.genesys2.server.service.impl.UserServiceImpl; -import org.genesys2.server.service.worker.ElasticUpdater; -import org.genesys2.server.service.worker.GeoRegionDataCLDR; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.genesys2.tests.BaseSpringTest; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.HierarchyMode; -import org.springframework.test.annotation.Rollback; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.ContextHierarchy; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextHierarchy(@ContextConfiguration(name = "this", classes = AbstractServicesTest.Config.class, initializers = PropertyPlacholderInitializer.class)) -@ActiveProfiles("dev") -@Transactional(transactionManager = "transactionManager") -@Rollback(true) -public abstract class AbstractServicesTest extends BaseSpringTest { - - @Configuration - @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL, classMode = DirtiesContext.ClassMode.AFTER_CLASS) - public static class Config { - - @Bean - public UserDetailsService userDetailsService() { - return new AuthUserDetailsService(); - } - - @Bean - public UserService userService() { - return new UserServiceImpl(); - } - - @Bean - public ContentService contentService() { - return new ContentServiceImpl(); - } - - @Bean - public ClassPKService classPkService() { - return new ClassPKServiceImpl(); - } - - @Bean - public HtmlSanitizer htmlSanitizer() { - return new OWASPSanitizer(); - } - - @Bean - public VelocityEngine velocityEngine() { - return new VelocityEngine(); - } - - @Bean - public DescriptorService descriptorService() { - return new DescriptorServiceImpl(); - } - - @Bean - public ThreadPoolTaskExecutor threadPoolTaskExecutor() { - return new ThreadPoolTaskExecutor(); - } - - @Bean - public EMailService eMailService() { - return new EMailServiceImpl(); - } - - @Bean - public JavaMailSender mailSender() { - return Mockito.mock(JavaMailSenderImpl.class); - } - - @Bean - public EMailVerificationService emailVerificationService() { - return new EMailVerificationServiceImpl(); - } - - @Bean - public TokenVerificationService tokenVerificationService() { - return new TokenVerificationServiceImpl(); - } - - @Bean - public TaxonomyService taxonomyService() { - return new TaxonomyServiceImpl(); - } - - @Bean - public CropService cropService() { - return new CropServiceImpl(); - } - - @Bean - public TeamService teamService() { - return new TeamServiceImpl(); - } - - @Bean - public GenesysLowlevelRepository genesysLowlevelRepositoryCustomImpl() { - return new GenesysLowlevelRepositoryCustomImpl(); - } - - @Bean - public CustomAclService aclService() { - return new CustomAclServiceImpl(); - } - - @Bean - public AsAdminAspect asAdminAspect() { - return new AsAdminAspect(); - } - - @Bean - public InstituteService instituteService() { - return new InstituteServiceImpl(); - } - - @Bean - public GenesysFilterService genesysFilterService() { - return new GenesysFilterServiceImpl(); - } - - @Bean - public MappingService mappingService() { - return new MappingServiceImpl(); - } - - @Bean - public GenesysService genesysService() { - return new GenesysServiceImpl(); - } - - @Bean - public TraitValueRepository traitValueRepository() { - return new TraitValueRepositoryImpl(); - } - - @Bean - public OrganizationService organizationService() { - return new OrganizationServiceImpl(); - } - - @Bean - public TraitService traitService() { - return new TraitServiceImpl(); - } - - @Bean - public GeoService geoService() { - return new GeoServiceImpl(); - } - - @Bean - public GeoRegionService geoRegionService() { - return new GeoRegionServiceImpl(); - } - - @Bean - public GeoRegionDataCLDR geoRegionDataCldr() { - return new GeoRegionDataCLDR(); - } - - @Bean - public PasswordPolicy passwordPolicy() { - return new SimplePasswordPolicy(); - } - - @Bean - public ElasticService searchService() { - return new ElasticsearchSearchServiceImpl(); - } - - @Bean - public ElasticSearchManagementService elasticSearchManagementService() { - return new ElasticSearchManagementServiceImpl(); - } - - @Bean - public ElasticUpdater elasticUpdater() { - return new ElasticUpdater(); - } - - @Bean - public FilterHandler filterHandler() { - return new FilterHandler(); - } - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } - - @Bean - public ShortFilterService shortFilterService() { - return new ShortFilterServiceImpl(); - } - - @Bean - public static Set supportedLocales() { - final Set supportedLocales = Sets.newHashSet("en", "es", "de", "fr", "fa", "ar", "ru", "zh", "pt"); - return supportedLocales; - } - } - - @Autowired - public UserDetailsService userDetailsService; - - @Autowired - public UserRepository userPersistence; - - @Autowired - public ActivityPostRepository postRepository; - - @Autowired - public ClassPKRepository classPkRepository; - - @Autowired - public DescriptorService descriptorService; - - @Autowired - public DSDescriptorRepository dSDescriptorRepository; - - @Autowired - public JavaMailSender mailSender; - - @Autowired - public EMailService eMailService; - - @Autowired - public VerificationTokenRepository verificationTokenRepository; - - @Autowired - public EMailVerificationService emailVerificationService; - - @Autowired - public ArticleRepository articleRepository; - - @Autowired - public HtmlSanitizer htmlSanitizer; - - @Autowired - public TaxonomyService taxonomyService; - - @Autowired - public TokenVerificationService tokenVerificationService; - - @Autowired - public VerificationTokenRepository tokenRepository; - - @Autowired - public InstituteService instituteService; - - @Autowired - public TeamRepository teamRepository; - - @Autowired - public TeamService teamService; - - @Autowired - public UserService userService; - - @Autowired - public CropService cropService; - - @Autowired - public CropRepository cropRepository; - - @Autowired - public CropRuleRepository cropRuleRepository; - - @Autowired - public CropTaxonomyRepository cropTaxonomyRepository; - - @Autowired - public Taxonomy2Repository taxonomy2Repository; - - @Autowired - public GenesysFilterService genesysFilterService; - - @Autowired - public MappingService mappingService; -} diff --git a/src/test/java/org/genesys2/tests/unit/Test1.java b/src/test/java/org/genesys2/tests/unit/Test1.java deleted file mode 100644 index 956fccbbc0d04c81a6f44174038f82ef2ed10e51..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/tests/unit/Test1.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.genesys2.tests.unit; - -public class Test1 { - -} diff --git a/src/test/java/org/genesys2/transifex/client/TransifexClientTest.java b/src/test/java/org/genesys2/transifex/client/TransifexClientTest.java deleted file mode 100644 index dea25a51f0141d4d06a01583c021a2d6d35328f0..0000000000000000000000000000000000000000 --- a/src/test/java/org/genesys2/transifex/client/TransifexClientTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * 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.genesys2.transifex.client; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.commons.lang.RandomStringUtils; -import org.genesys2.server.test.PropertyPlacholderInitializer; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.PropertySource; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@Ignore -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TransifexClientTest.Config.class, initializers = PropertyPlacholderInitializer.class) -public class TransifexClientTest { - - @PropertySource({ "classpath:application.properties", "classpath:/spring/spring.properties" }) - public static class Config{ - - @Bean - public TransifexService transifexService() { - return new TransifexServiceImpl(); - } - } - - @Value("${transifex.content.template}") - private String contentTemplate; - - @Autowired - private TransifexService transifexService; - - @Test - public void testPostResource() throws IOException, TransifexException { - // Post new resource - String resourceSlug = "test-".concat(RandomStringUtils.randomAlphanumeric(30)); - String resourceTitle = "Test ".concat(RandomStringUtils.randomAlphanumeric(60)); - - // This is template our xhtml - String content = String.format(contentTemplate, resourceTitle, "

This is a test

"); - - transifexService.createXhtmlResource(resourceSlug, resourceTitle, content); - - // Resource posted, must exist - assertTrue("Resource does not exist", transifexService.resourceExists(resourceSlug)); - - // Delete resource - transifexService.deleteResource(resourceSlug); - - // Resource was deleted, should not exist - assertFalse("Resource still exists", transifexService.resourceExists(resourceSlug)); - } - - @Test - public void testUpdateResource() throws IOException, TransifexException { - // Post new resource - String resourceSlug = "test-".concat(RandomStringUtils.randomAlphanumeric(30)); - String resourceTitle = "Test ".concat(RandomStringUtils.randomAlphanumeric(60)); - - // This is template our xhtml - String content = String.format(contentTemplate, resourceTitle, "

This is a test

Some other string

"); - - transifexService.updateXhtmlResource(resourceSlug, resourceTitle, content); - - // Resource posted, must exist - assertTrue("Resource does not exist", transifexService.resourceExists(resourceSlug)); - - try { - // Sleep for a while to allow testing on www.transifex.com - Thread.sleep(1000 * 30); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - // Update content and post again - content = String.format(contentTemplate, resourceTitle, "

Updated content

Some other string

"); - - // What now? - transifexService.updateXhtmlResource(resourceSlug, resourceTitle, content); - - // Delete resource - transifexService.deleteResource(resourceSlug); - - // Resource was deleted, should not exist - assertFalse("Resource still exists", transifexService.resourceExists(resourceSlug)); - } -} diff --git a/src/test/resources/spring/hibernate.properties b/src/test/resources/hibernate.properties similarity index 64% rename from src/test/resources/spring/hibernate.properties rename to src/test/resources/hibernate.properties index c879226aacaac3fd420b27dce7076b94aacc13c7..6d490f959690fac4506995a9f53d3894a3f0a95b 100644 --- a/src/test/resources/spring/hibernate.properties +++ b/src/test/resources/hibernate.properties @@ -11,8 +11,6 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false hibernate.cache.use_minimal_puts=true hibernate.cache.region_prefix=hibernate -#MEM:hibernate.cache.region.factory_class=org.hibernate.testing.cache.CachingRegionFactory -#hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastCacheRegionFactory -hibernate.cache.region.factory_class=org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper +#hibernate.cache.region.factory_class=org.hibernate.testing.cache.CachingRegionFactory hibernate.cache.use_structured_entries=true hibernate.generate_statistics=false diff --git a/src/test/resources/application.properties b/src/test/resources/junit.properties similarity index 77% rename from src/test/resources/application.properties rename to src/test/resources/junit.properties index b479f4a2fa4cb492a406e509b4f029036f750a7c..106b1745e6991df2949c7df0faf5811cb944dd09 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/junit.properties @@ -14,6 +14,16 @@ # limitations under the License. #------------------------------------------------------------------------------- +#DB connection properties +#In-memory HSQLDB +db.url=jdbc:hsqldb:mem:test;sql.syntax_mys=true;sql.ignore_case=true +db.driverClassName = org.hsqldb.jdbc.JDBCDriver +db.username = sa +db.password = +db.showSql=false +db.hbm2ddl=true +hibernate.dialect=org.genesys.blocks.util.BetterHSQLDialect + #Paginator paginator.default.maxPageSize=500 paginator.default.pageSize=2 @@ -30,5 +40,7 @@ default.oauthclient.clientSecret=changeme default.oauth.accessToken.validity=21600 default.oauth.refreshToken.validity=604800 -build.name=${project.artifactId}-${buildNumber} -build.revision=${buildNumber} +build.name=test-build +build.revision=current + +repository.ftp.port=-1 diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index c82c5b68e15f165798d3854ec25f6002bba09445..dc299f8da1de22fe91dba1469c1a5bb731c3bd46 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -29,8 +29,17 @@ log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=warn, stdout -log4j.category.org.genesys2=info +#log4j.category.org.genesys2=info +log4j.category.org.genesys.blocks.security=error +log4j.category.org.genesys2.server=warn #log4j.category.org.genesys2.server.service.worker.AccessionCounter=trace + #log4j.category.org.hibernate.cache=debug #log4j.category.org.hibernate.jdbc=debug -log4j.category.org.hibernate.jdbc.AbstractBatcher=debug +#log4j.category.org.hibernate.jdbc.AbstractBatcher=debug +#log4j.category.org.springframework.beans=debug +#log4j.category.org.springframework.test.context=trace +#log4j.category.org.springframework.test.context=debug + +# Internal Hibernate logging is at ERROR +log4j.category.org.hibernate.engine.jdbc=fatal diff --git a/src/test/resources/mcpd20177.csv b/src/test/resources/mcpd20177.csv new file mode 100644 index 0000000000000000000000000000000000000000..2309ff5e433ab1462da2ab1e9f10776f2c73083f --- /dev/null +++ b/src/test/resources/mcpd20177.csv @@ -0,0 +1,21 @@ +title,data_type,description,integer_only,max_value,min_value,published,version_tag,vocabulary_id,columnName,uom +Accession name,text,"Either a registered or other formal designation given to the accession. First letter uppercase. +Multiple names separated with semicolon.",N,,,Y,1997,,ACCENAME, +Accession number,text,"This number serves as a unique identifier for accessions and is assigned when an accession is entered into the collection. Once assigned this number should never be reassigned to another accession in the collection. Even if an accession is lost, its assigned number should never be reused. Letters should be used before the number to identify the genebank or national system (e.g. IDG indicates an accession that comes from the genebank at Bari, Italy; CGN indicates an accession from the genebank at Wageningen, The Netherlands; PI indicates an accession within the USA system)",N,,,Y,1997,,ACCENUMB, +Collecting date of sample [YYYYMMDD],numeric,"Collecting date of the sample where YYYY is the year, MM is the month and DD is the day.",Y,,,Y,1997,,COLLDATE, +Collecting number,text,"Original number assigned by the collector(s) of the sample, normally composed of the name or initials of the collector(s) followed by a number. This item is essential for identifying duplicates held in different collections. It should be unique and always accompany subsamples wherever they are sent. 4.",N,,,Y,1997,,COLLNUMB, +Location of collecting site,text,"Location information below the country level that describes where the accession was collected starting with the most detailed information. Might include the distance in kilometers and direction from the nearest town, village or map grid reference point, (e.g. CURITIBA 7S, PARANA means 7 km south of Curitiba in the state of Parana) 10.",N,,,Y,1997,,COLLSITE, +Collecting source,coded,"The coding scheme proposed can be used at 2 different levels of detail: Either by using the global codes such as 1, 2, 3, 4 or by using the more detailed coding such as 1.1, 1.2, 1.3, etc.",Y,,,Y,1997,,COLLSRC, +Donor institute code,coded,Code for the donor institute. The codes consist of the 3-letter ISO 3166 country code of the country where the institute is located plus number or an acronym as specified in the Institute database that will be made available by FAO. Preliminary codes (i.e. codes not yet incorporated in the FAO Institute database) start with an asterisk followed by a 3-letter ISO 3166 country code and an acronym.,N,,,Y,1997,,DONORCODE, +Donor number,text,"Number assigned to an accession by the donor. Letters should be used before the number to identify the genebank or national system (e.g. IDG indicates an accession that comes from the genebank at Bari, Italy; CGN indicates an accession from the genebank at Wageningen, The Netherlands; PI indicates an accession within the USA system)",N,,,Y,1997,,DONORNUMB, +Elevation of collecting site [masl],numeric,Elevation of collecting site expressed in metres above sea level. Negative values are allowed. ,N,,,Y,1997,,ELEVATION,m +Genus,text,Genus name for taxon. Initial uppercase letter required.,N,,,Y,1997,,GENUS, +Institute code,?,Code of the institute where the accession is maintained. The codes consist of the 3-letter ISO 3166 country code of the country where the institute is located plus number or an acronym as specified in the Institute database that will be made available by FAO. Preliminary codes (i.e. codes not yet incorporated in the FAO Institute database) start with an asterisk followed by a 3-letter ISO 3166 country code and an acronym.,N,,,Y,1997,,INSTCODE, +Latitude of collecting site,text,Degrees and minutes followed by N (North) or S (South) (e.g. 1030S). Missing data (minutes) should be indicated with hyphen (e.g. 10-S).,N,,,Y,1997,,LATITUDE, +Longitude of collecting site,text,Degrees and minutes followed by E (East) or W (West) (e.g. 07625W). Missing data (minutes) should be indicated with hyphen (e.g. 076-W). 12.,N,,,Y,1997,,LONGITUDE, +Country of origin,coded,"Name of the country in which the sample was originally collected or derived. Use the ISO 3166 extended codes, (i.e. current and old 3 letter ISO 3166 country codes)",N,,,Y,1997,,ORIGCTY, +Other number(s) associated with the accession,text,"Any other identification number known to exist in other collections for this accession. Letters should be used before the number to identify the genebank or national system (e.g. IDG indicates an accession that comes from the genebank at Bari, Italy; CGN indicates an accession from the genebank at Wageningen, The Netherlands; PI indicates an accession within the USA system). Multiple numbers can be added and should be separated with a semicolon",N,,,Y,1997,,OTHERNUMB, +Remarks,text,The remarks field is used to add notes or to elaborate on descriptors with value “99”(=Other). Prefix remarks with the field name they refer to and a colon (e.g. COLLSRC:roadside). Separate remarks referring to different fields are separated by semicolons.,N,,,Y,1997,,REMARKS, +Status of sample,coded,,Y,,,Y,1997,,SAMPSTAT, +Species,text,"Specific epithet portion of the scientific name in lowercase letters plus authority (only provided at the most detailed taxonomic level). Following abbreviation is allowed: ""sp.""",N,,,Y,1997,,SPECIES, +Subtaxa,text,Subtaxa can be used to store any additional taxonomic identifier plus authority (only provided at the most detailed taxonomic level). Following abbreviations are allowed: “ssp.” (for subspecies); “var.” (for variety); “convar.” (for convariety); “f.” (for form).,N,,,Y,1997,,SUBTAXA, diff --git a/src/test/resources/spring/hibernate-mysql.properties b/src/test/resources/spring/hibernate-mysql.properties deleted file mode 100644 index 5d647e773c8bb2e16bce65eb3688ba9eaedb7864..0000000000000000000000000000000000000000 --- a/src/test/resources/spring/hibernate-mysql.properties +++ /dev/null @@ -1,18 +0,0 @@ -#Hibernate specific properties -javax.persistence.sharedCache.mode=ENABLE_SELECTIVE -hibernate.connection.charSet=utf8 -hibernate.connection.autocommit=false -hibernate.jdbc.fetch_size=25 -hibernate.jdbc.batch_size=15 -hibernate.order_updates=true -hibernate.order_inserts=true - -hibernate.cache.use_second_level_cache=true -hibernate.cache.use_query_cache=false -hibernate.cache.use_minimal_puts=true -hibernate.cache.region_prefix=hibernate -#MEM:hibernate.cache.region.factory_class=org.hibernate.testing.cache.CachingRegionFactory -#hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastCacheRegionFactory -hibernate.cache.region.factory_class=org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false diff --git a/src/test/resources/spring/spring-database.properties b/src/test/resources/spring/spring-database.properties deleted file mode 100644 index 63dba6f256a289ac4511cd9141de322177d8a8ae..0000000000000000000000000000000000000000 --- a/src/test/resources/spring/spring-database.properties +++ /dev/null @@ -1,105 +0,0 @@ -#------------------------------------------------------------------------------- -# 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. -#------------------------------------------------------------------------------- - -base.url=http://localhost:8080 - -#DB connection properties -#In-memory HSQLDB - -db.url=jdbc:mysql://localhost/genesys?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false&rewriteBatchedStatements=true -db.driverClassName=com.mysql.jdbc.Driver -db.username=root -db.password= -db.showSql=true -db.hbm2ddl=true -hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect - -# reCAPTCHA API -captcha.privateKey=A -captcha.publicKey=B - -lucene.indexDir=./lucene/ - -# paths -download.files.dir=./data/ - -# ITPGRFA Easy-SMTA account (if you have one) -itpgrfa.easysmta.username= -itpgrfa.easysmta.password= - -# GA Account -google.analytics.account= - -# CDN -cdn.server=https://s1.cdn.genesys-pgr.org -cdn.base=${cdn.server}/html -cdn.flags.url=${cdn.base}/flags - -# TileServer CDN -tileserver.cdn='' - -# Content creation on startup -auto.createContent=false - -scheduler.tokens.cleanup.hours=1 - -# Mail configuration -mail.user.from=test@localhost -mail.requests.to=test@localhost -mail.async=true -mail.debug.message= Email has been sent succesfully\n\ - Details:\n\ - From:%s\n\ - To:%s\n\ - Subject: %s\n\ - Text: \n==================================\n\n\ - %s\ - \n\n================================== - - -# Hazelcast -hazelcast.instanceName=genesys -hazelcast.name=genesys -hazelcast.password=hazelcasts -hazelcast.port=5701 - -# AWS Autodetection -hazelcast.aws.access-key= -hazelcast.aws.secret-key= -hazelcast.aws.region=eu-west-1 -hazelcast.aws.security-group=sg-hazelcast - -# TileServer Cache -cache.tileserver.max-size=1000 -cache.tileserver.time-to-live-seconds=300 -cache.tileserver.max-idle-seconds=0 -cache.tileserver.eviction-policy=LRU - - -transifex.project=genesys-dev -transifex.username=Alexandr19011990 -transifex.password=Alexandr19011990 -transifex.min.translated=80 -transifex.base.api.url=https://www.transifex.com/api/2/ -transifex.hook.key=this-is-a-test-hook-key -#TODO perhaps, Velocity template? -transifex.content.template=\ - \ - \ - %s\ - \ - %s\ - diff --git a/src/test/resources/spring/spring.properties b/src/test/resources/spring/spring.properties deleted file mode 100644 index 9d1c94aae986c2e89653c34dea3bfb20eb4a9ae0..0000000000000000000000000000000000000000 --- a/src/test/resources/spring/spring.properties +++ /dev/null @@ -1,120 +0,0 @@ -#------------------------------------------------------------------------------- -# 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. -#------------------------------------------------------------------------------- - -host.name=localhost -base.url=http://${host.name}:8080 -cdn.servers=${base.url} -base.cookie-domain=${host.name} -base.cookie-secure=false -base.cookie-http-only=true - -#DB connection properties -#In-memory HSQLDB -db.url=jdbc:hsqldb:mem:test;sql.syntax_mys=true -db.driverClassName = org.hsqldb.jdbc.JDBCDriver -db.username = sa -db.password = -db.showSql=false -db.hbm2ddl=true -hibernate.dialect=org.genesys.blocks.util.BetterHSQLDialect - -# reCAPTCHA API -captcha.privateKey=A -captcha.publicKey=B - -lucene.indexDir=./lucene/ - -# paths -data.dir=./data -elasticsearch.data.path=${data.dir}/elastic -file.repository.dir=${data.dir}/repository - -# FTP -repository.ftp.keystore.path= -repository.ftp.keystore.password=changeit! -repository.ftp.port=8021 -repository.ftp.passivePorts=2300-2350 -repository.ftp.externalAddress= - -# ITPGRFA Easy-SMTA account (if you have one) -itpgrfa.easysmta.url=https://mls.planttreaty.org/itt/index.php?r=extsys/userinfo -itpgrfa.easysmta.username=bar -itpgrfa.easysmta.password=foo - -# GA Account -google.analytics.account= - -# Content creation on startup -auto.createContent=false - -scheduler.tokens.cleanup.hours=1 - -# Mail configuration -mail.host=localhost -mail.port=25 -mail.user.from=test@localhost -mail.requests.to=test@localhost -mail.async=false -mail.debug.message= Email has been sent succesfully\n\ - Details:\n\ - From:%s\n\ - To:%s\n\ - Subject: %s\n\ - Text: \n==================================\n\n\ - %s\ - \n\n================================== - - -# Hazelcast -hazelcast.instanceName=hz-genesys -hazelcast.name=genesys-hz-3.5 -hazelcast.password=hazelcasts -# Binding and public address -hazelcast.publicAddress= -hazelcast.interfaces= -hazelcast.port=5701 -hazelcast.members= - -# Cache configuration -cache.defaultCacheSize=2000 -cache.eviction-policy=LRU -# 1 hour - revalidate frequently used entries -cache.time-to-live-seconds=3600 -# 10 min -cache.max-idle-seconds=600 - -# ES -elasticsearch.cluster.name=es-genesys-development -# Allow HTTP connections on port 9200 -elasticsearch.enable.http=true -# Connect to external ES nodes. Comma separated list of hostname:port -# elasticsearch.cluster.nodes=localhost:9300,otherhost:9300 -elasticsearch.cluster.nodes= - -transifex.project=genesys-dev -transifex.username=Alexandr19011990 -transifex.password=Alexandr19011990 -transifex.min.translated=80 -transifex.base.api.url=https://www.transifex.com/api/2/ -transifex.hook.key=this-is-a-test-hook-key -#TODO perhaps, Velocity template? -transifex.content.template=\ - \ - \ - %s\ - \ - %s\ -