Commit 68ba8658 authored by Alexander Basov's avatar Alexander Basov Committed by Matija Obreza
Browse files

TraitsControllerTest and UsersControllerTest completed

parent b3d99b77
package org.genesys2.server.persistence.domain.mock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.model.genesys.Method;
import org.genesys2.server.persistence.domain.GenesysLowlevelRepository;
import org.genesys2.server.persistence.domain.MethodRepository;
import org.genesys2.server.service.impl.DirectMysqlQuery;
import org.genesys2.server.service.impl.FilterHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.ArgumentPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.*;
import java.util.List;
@Repository
public class GenesysLowlevelRepositoryMock implements GenesysLowlevelRepository {
public static final Log LOG = LogFactory.getLog(GenesysLowlevelRepositoryMock.class);
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private MethodRepository methodRepository;
@Override
@PreAuthorize("hasRole('ADMINISTRATOR')")
@Transactional(readOnly = false)
public void updateFaoInstituteRefs() {
LOG.info("Updating institute references");
int count = this.jdbcTemplate.update("UPDATE `accession` A inner join `faoinstitute` FI on FI.code=A.instCode set A.instituteId=FI.id;");
LOG.info("Institute references updated: " + count);
LOG.info("Updating institute accession count");
count = this.jdbcTemplate
.update("UPDATE faoinstitute FI inner join (select instituteId, count(*) X from accession group by instituteId) A on A.instituteId=FI.id set FI.accessionCount=A.X;");
LOG.info("Institute accession counts updated: " + count);
}
// @Override
// @Transactional(readOnly = false, propagation = Propagation.SUPPORTS)
// public void updateInstituteAccessionCount(long instituteId) {
// LOG.debug("Updating institute accession count for instituteId=" +
// instituteId);
// // int count = jdbcTemplate
// //
// .update("UPDATE faoinstitute FI inner join (select instituteId, count(*) X from accession where instituteId= ? group by instituteId) A on A.instituteId=FI.id set FI.accessionCount=A.X where FI.id = ?;",
// // instituteId, instituteId);
// jdbcTemplate.update("UPDATE faoinstitute SET accessionCount = (select count(*) from accession where instituteId=?) where id = ?;",
// instituteId, instituteId);
// LOG.info("Institute accession count updated for " + instituteId);
// }
@Override
@PreAuthorize("hasRole('ADMINISTRATOR')")
@Transactional(readOnly = false)
public void updateCountryRefs() {
LOG.info("Updating country references");
final int count = this.jdbcTemplate
.update("UPDATE `accession` A inner join `country` C on C.code3=A.orgCty set A.orgCtyId=C.id WHERE A.orgCty IS NOT NULL;");
LOG.info("Country references updated: " + count);
}
@Override
@PreAuthorize("hasRole('ADMINISTRATOR')")
@Transactional(readOnly = false)
public void updateFaoInstituteCountries() {
LOG.info("Updating country references");
final int count = this.jdbcTemplate.update("UPDATE `faoinstitute` I inner join `country` C on C.code3=left(I.code, 3) set I.countryId=C.id;");
LOG.info("Country references updated: " + count);
}
@Override
public void ensureMethodTable(final Method method) {
LOG.info("Ensuring method table for " + method);
try {
LOG.info("Checking for table with name " + method.getId().toString());
final DatabaseMetaData databaseMetadata = this.jdbcTemplate.getDataSource().getConnection().getMetaData();
final ResultSet matchingTables = databaseMetadata.getTables(null, null, method.getId().toString(), new String[] { "TABLE" });
if (matchingTables.next()) {
LOG.info("Found existing table: " + matchingTables.getObject(3));
throw new RuntimeException("Method data table already exists!");
} else {
/*
* CREATE TABLE `100` ( `id` bigint(20) NOT NULL AUTO_INCREMENT,
* `ALIS_Id` bigint(20) NOT NULL, `Meta_id` int(6) NOT NULL,
* `LEAFSTREAK` char(2) NOT NULL, PRIMARY KEY (`id`), KEY
* `ALIS_Id` (`ALIS_Id`), KEY `LEAFSTREAK` (`LEAFSTREAK`) )
* ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
final StringBuilder createTableSql = new StringBuilder();
// Common table elements
createTableSql.append("CREATE TABLE `").append(method.getId())
.append("` (id BIGINT NOT NULL AUTO_INCREMENT, accessionId BIGINT NOT NULL, metadataId BIGINT NOT NULL, ");
// Value column
createTableSql.append(' ').append(method.getFieldName()).append(" ");
createTableSql.append(getValueColumnDDL(method));
createTableSql.append(" NOT NULL");
// PK
createTableSql.append(", PRIMARY KEY (id)");
// FK metadata
// createTableSql.append(", INDEX `genesys_Metadata_").append(method.getId()).append("` (`Meta_Id` ASC)");
createTableSql.append(", CONSTRAINT genesys_Metadata_").append(method.getId())
.append(" FOREIGN KEY (metadataId) REFERENCES metadata (id ) ON DELETE NO ACTION ON UPDATE NO ACTION");
// FK accession
// createTableSql.append(", INDEX `genesys_Accession_idx` (`ALIS_Id` ASC)");
createTableSql.append(", CONSTRAINT genesys_Accession_").append(method.getId())
.append(" FOREIGN KEY (accessionId) REFERENCES accession (id ) ON DELETE NO ACTION ON UPDATE NO ACTION");
// This is optional, but let's keep it
// createTableSql.append(", KEY `").append(method.getFieldName()).append("` (`").append(method.getFieldName()).append("`)");
createTableSql.append(")");
LOG.warn("Creating method table: " + createTableSql.toString());
this.jdbcTemplate.execute(createTableSql.toString());
}
LOG.info("Done");
} catch (final SQLException e) {
LOG.error(e);
}
}
private String getValueColumnDDL(final Method method) {
if (method.getFieldType() == 0) {
return "VARCHAR(" + method.getFieldSize() + ")";
} else if (method.getFieldType() == 1) {
return "DOUBLE";
} else if (method.getFieldType() == 2) {
return "BIGINT";
}
throw new RuntimeException("Unsupported data type " + method.getFieldType());
}
@Override
@Transactional(readOnly = false)
public void refreshMetadataMethods() {
this.jdbcTemplate.update("delete from metadatamethod");
this.jdbcTemplate.update("delete from accessiontrait");
final List<Long> methodIds = this.jdbcTemplate.queryForList("select id from method", Long.class);
for (final long methodId : methodIds) {
LOG.info("Updating metadatamethod for methodId=" + methodId);
// // Delete stuff without Metadata
// int deleted = jdbcTemplate.update("delete from `" + methodId +
// "` where Meta_Id in (select X.Meta_Id from (select distinct Meta_Id from `"
// + methodId +
// "`) X left outer join metadata M on M.Meta_Id=X.Meta_Id where M.Meta_Id is null)");
// if (deleted > 0) {
// LOG.warn("Deleted " + deleted +
// " observations with missing metadata from method=" + methodId);
// }
// Insert reference to metadatamethod
try {
final int inserted = this.jdbcTemplate.update("insert into metadatamethod (metadataId, methodId) (select distinct metadataId, " + methodId
+ " from `" + methodId + "`)");
if (inserted == 0) {
LOG.warn("Method " + methodId + " has no entries?");
} else {
LOG.warn("Inserted " + inserted + " method references for metadata for methodId=" + methodId);
}
} catch (final BadSqlGrammarException e) {
LOG.warn(e);
}
try {
final int inserted2 = this.jdbcTemplate
.update("insert into accessiontrait (metadataId , accessionId, methodId) (select distinct metadataId, accessionId, " + methodId
+ " from `" + methodId + "`)");
if (inserted2 == 0) {
LOG.warn("Method " + methodId + " has no entries?");
} else {
LOG.warn("Inserted " + inserted2 + " accession references methodId=" + methodId);
}
} catch (final BadSqlGrammarException e) {
LOG.warn(e);
}
}
}
@Override
@Cacheable(value = "statistics", key = "'filtered-count-' + #filters")
public int countAccessions(final FilterHandler.AppliedFilters filters) {
final DirectMysqlQuery directQuery = new DirectMysqlQuery("accession", "a");
directQuery.jsonFilter(filters, new DirectMysqlQuery.MethodResolver() {
@Override
public Method getMethod(final long methodId) {
return GenesysLowlevelRepositoryMock.this.methodRepository.findOne(methodId);
}
});
return this.jdbcTemplate.queryForObject(directQuery.getCountQuery("a.id"), directQuery.getParameters(), Integer.class);
}
@Override
public void listAccessions(final FilterHandler.AppliedFilters filter, final RowCallbackHandler rowCallbackHandler) {
final DirectMysqlQuery directQuery = new DirectMysqlQuery("accession", "a");
directQuery.innerJoin("acce", "acce", "acce.id=a.id");
directQuery.outerJoin("taxonomy2", "t", "t.id=a.taxonomyId2");
directQuery.jsonFilter(filter, new DirectMysqlQuery.MethodResolver() {
@Override
public Method getMethod(final long methodId) {
return GenesysLowlevelRepositoryMock.this.methodRepository.findOne(methodId);
}
});
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con.prepareStatement(directQuery
.getQuery("a.id, acce.uuid, a.instCode, a.acceNumb, t.genus, t.species, t.taxonName, a.orgCty, a.acqSrc, a.acqDate, a.mlsStat, a.available, a.historic, a.storage, a.sampStat, a.duplSite, acce.createdBy, acce.createdDate, acce.lastModifiedBy, acce.lastModifiedDate"));
final ArgumentPreparedStatementSetter apss = new ArgumentPreparedStatementSetter(directQuery.getParameters());
apss.setValues(stmt);
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listAccessionIds(final FilterHandler.AppliedFilters filter, final Sort sort, final RowCallbackHandler rowCallbackHandler) {
final DirectMysqlQuery directQuery = new DirectMysqlQuery("accession", "a");
directQuery.jsonFilter(filter, new DirectMysqlQuery.MethodResolver() {
@Override
public Method getMethod(final long methodId) {
return GenesysLowlevelRepositoryMock.this.methodRepository.findOne(methodId);
}
});
directQuery.sort(sort);
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con.prepareStatement(directQuery
.getQuery("a.id"));
final ArgumentPreparedStatementSetter apss = new ArgumentPreparedStatementSetter(directQuery.getParameters());
apss.setValues(stmt);
// Set mysql JConnector to stream results
// stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listAccessionsGeo(final FilterHandler.AppliedFilters filter, final RowCallbackHandler rowCallbackHandler) {
final DirectMysqlQuery directQuery = new DirectMysqlQuery("accessiongeo", "geo");
directQuery.innerJoin("accession", "a", "a.id=geo.accessionId");
directQuery.jsonFilter(filter, new DirectMysqlQuery.MethodResolver() {
@Override
public Method getMethod(final long methodId) {
return GenesysLowlevelRepositoryMock.this.methodRepository.findOne(methodId);
}
});
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con.prepareStatement(directQuery
.getQuery("a.id, geo.latitude, geo.longitude, geo.elevation, geo.datum, geo.uncertainty, geo.method, geo.version"));
final ArgumentPreparedStatementSetter apss = new ArgumentPreparedStatementSetter(directQuery.getParameters());
apss.setValues(stmt);
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listAccessionsAlias(final FilterHandler.AppliedFilters filter, final RowCallbackHandler rowCallbackHandler) {
// from n inner join accession a on a.id=n.accessionId
final DirectMysqlQuery directQuery = new DirectMysqlQuery("accessionalias", "n");
directQuery.innerJoin("accession", "a", "a.id=n.accessionId");
directQuery.jsonFilter(filter, new DirectMysqlQuery.MethodResolver() {
@Override
public Method getMethod(final long methodId) {
return GenesysLowlevelRepositoryMock.this.methodRepository.findOne(methodId);
}
});
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con.prepareStatement(directQuery.getQuery("a.id, n.instCode, n.name, n.aliasType, n.lang, n.version"));
final ArgumentPreparedStatementSetter apss = new ArgumentPreparedStatementSetter(directQuery.getParameters());
apss.setValues(stmt);
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listAccessionsAlias(final RowCallbackHandler rowCallbackHandler) {
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con
.prepareStatement("select n.accessionId, n.instCode, n.name, n.aliasType, n.lang, n.version, n.id from accessionalias n order by n.accessionId");
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listAccessionsColl(final FilterHandler.AppliedFilters filter, final RowCallbackHandler rowCallbackHandler) {
// from accessioncollect coll inner join accession a on
// a.id=coll.accessionId
final DirectMysqlQuery directQuery = new DirectMysqlQuery("accessioncollect", "coll");
directQuery.innerJoin("accession", "a", "a.id=coll.accessionId");
directQuery.jsonFilter(filter, new DirectMysqlQuery.MethodResolver() {
@Override
public Method getMethod(final long methodId) {
return GenesysLowlevelRepositoryMock.this.methodRepository.findOne(methodId);
}
});
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con.prepareStatement(directQuery
.getQuery("a.id, coll.collMissId, coll.collNumb, coll.collDate, coll.collSrc, coll.collSite, coll.collCode, coll.collName, coll.collInstAddress, coll.version"));
final ArgumentPreparedStatementSetter apss = new ArgumentPreparedStatementSetter(directQuery.getParameters());
apss.setValues(stmt);
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listMetadataAccessions(final long id, final RowCallbackHandler rowCallbackHandler) {
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con
.prepareStatement("select distinct a.id, a.instCode, a.acceNumb, t.genus from accessiontrait at inner join accession a on a.id=at.accessionId left outer join taxonomy2 t on t.id=a.taxonomyId2 where at.metadataId = ?");
stmt.setLong(1, id);
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
@Override
public void listAccessionsAccenames(final RowCallbackHandler rowCallbackHandler) {
this.jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
final PreparedStatement stmt = con.prepareStatement("select accessionId, names, otherIds from accessionname");
// Set mysql JConnector to stream results
stmt.setFetchSize(Integer.MIN_VALUE);
return stmt;
}
}, rowCallbackHandler);
}
}
......@@ -6,17 +6,18 @@ import org.genesys2.server.persistence.acl.AclClassPersistence;
import org.genesys2.server.persistence.acl.AclEntryPersistence;
import org.genesys2.server.persistence.acl.AclObjectIdentityPersistence;
import org.genesys2.server.persistence.acl.AclSidPersistence;
import org.genesys2.server.persistence.domain.GenesysLowlevelRepository;
import org.genesys2.server.persistence.domain.GenesysLowlevelRepositoryCustomImpl;
import org.genesys2.server.persistence.domain.TeamRepository;
import org.genesys2.server.persistence.domain.UserPersistence;
import org.genesys2.server.persistence.domain.*;
import org.genesys2.server.persistence.domain.mock.GenesysLowlevelRepositoryMock;
import org.genesys2.server.service.*;
import org.genesys2.server.service.impl.*;
import org.genesys2.server.servlet.controller.rest.TraitsController;
import org.genesys2.server.servlet.controller.rest.UserController;
import org.genesys2.server.servlet.controller.rest.UsersController;
import org.genesys2.server.test.JpaDataConfig;
import org.genesys2.server.test.PropertyPlacholderInitializer;
import org.genesys2.spring.config.HazelcastConfig;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.NoOpCacheManager;
......@@ -24,6 +25,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
......@@ -84,7 +88,7 @@ public abstract class AbstractRestTest {
@Bean
public GenesysLowlevelRepository genesysLowlevelRepository() {
return new GenesysLowlevelRepositoryCustomImpl();
return new GenesysLowlevelRepositoryMock();
}
@Bean
......@@ -96,8 +100,109 @@ public abstract class AbstractRestTest {
public AsAdminAspect asAdminAspect() {
return new AsAdminAspect();
}
@Bean
public UsersController restUsersController(){
return new UsersController();
}
@Bean
public OAuth2ClientDetailsService auth2ClientDetailsService(){
return new OAuth2ClientDetailsServiceImpl();
}
@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 traitService(){
return new TraitServiceImpl();
}
@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();
}
}
@Autowired
FaoInstituteRepository instituteRepository;
@Autowired
FaoInstituteSettingRepository instituteSettingRepository;
@Autowired
MethodRepository methodRepository;
@Autowired
GenesysLowlevelRepository genesysLowlevelRepository;
@Autowired
TraitsController traitsController;
@Autowired
TraitService traitService;
@Autowired
ArticleRepository articleRepository;
@Autowired
ContentService contentService;
@Autowired
JavaMailSender javaMailSender;
@Autowired
UsersController restUsersController;
@Autowired
UserService userService;
......@@ -130,4 +235,16 @@ public abstract class AbstractRestTest {
@Autowired
TeamService teamService;
@Autowired
GenesysService genesysService;
@Autowired CropService cropService;
@Autowired
CropRepository cropRepository;
@Autowired ParameterRepository parameterRepository;
@Autowired ParameterCategoryRepository parameterCategoryRepository;
}
package org.genesys2.resttests;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.exception.UserException;
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.genesys.ParameterCategory;
import org.genesys2.server.model.impl.Crop;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.server.servlet.controller.rest.OAuth2Cleanup;