diff --git a/README.md b/README.md index 5ca50b9..41091f1 100644 --- a/README.md +++ b/README.md @@ -5,5 +5,5 @@ ## Install and run: - Run **git clone** and then **cd uoa-repository-manager-service**. - Provide all not-set or redacted configurations, inside the **src/main/resources/application.properties** file. -- Build the app with: `mvn clean install -s ` +- Build the app with: `mvn clean install` - Run the app with: `java -jar ./target/uoa-repository-manager-service.jar` diff --git a/pom.xml b/pom.xml index 5b76779..6e4c908 100644 --- a/pom.xml +++ b/pom.xml @@ -64,6 +64,11 @@ h2 + + org.apache.solr + solr-solrj + 9.1.1 + eu.dnetlib.dhp @@ -362,6 +367,30 @@ + + dnet45-bootstrap-snapshot + D-Net 45 Bootstrap Snapshot + https://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-bootstrap-snapshot + + false + + + true + + default + + + dnet45-bootstrap-release + D-Net 45 Bootstrap Release + https://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-bootstrap-release + + true + + + false + + default + dnet-deps dnet-dependencies diff --git a/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java b/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java index e2689eb..5cd225b 100644 --- a/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java +++ b/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java @@ -20,7 +20,7 @@ public class AsyncConfiguration implements AsyncConfigurer { @Override public void handleUncaughtException(Throwable throwable, Method method, Object... objects) { - //logger.error("Async error", throwable); + logger.error("Async error", throwable); } }; } diff --git a/src/main/java/eu/dnetlib/repo/manager/controllers/DashboardController.java b/src/main/java/eu/dnetlib/repo/manager/controllers/DashboardController.java index c04ad14..3fd6650 100644 --- a/src/main/java/eu/dnetlib/repo/manager/controllers/DashboardController.java +++ b/src/main/java/eu/dnetlib/repo/manager/controllers/DashboardController.java @@ -55,22 +55,21 @@ public class DashboardController { @PreAuthorize("hasAuthority('REGISTERED_USER')") public CollectionMonitorSummary getCollectionMonitorSummary( @PathVariable("repoId") String repoId, - @RequestParam(name = "size", required = false, defaultValue = "20") int size) throws JSONException { + @RequestParam(name = "size", required = false, defaultValue = "20") int summarySize) throws JSONException { + + List aggregationInfoList = aggregationService.getRepositoryAggregations(repoId); - List aggregationInfo = aggregationService.getRepositoryAggregations(repoId, 0, size); CollectionMonitorSummary collectionMonitorSummary = new CollectionMonitorSummary(); - collectionMonitorSummary.setAggregationInfo(aggregationInfo); - size = 0; - do { - aggregationInfo = aggregationService.getRepositoryAggregations(repoId, size, size + 50); - for (AggregationInfo aggregationDetail : aggregationInfo) { - if (aggregationDetail.isIndexedVersion()) { - collectionMonitorSummary.setLastIndexedVersion(aggregationDetail); - break; - } + // Set the "aggregationInfo" for the first requested aggregations, in order to create a "summary". + collectionMonitorSummary.setAggregationInfo(aggregationInfoList.subList(0, Math.min(summarySize, aggregationInfoList.size()))); + + // Search for the last indexed version and set the "collectionMonitorSummary". + for ( AggregationInfo aggregationInfo : aggregationInfoList ) { + if ( aggregationInfo.isIndexedVersion() ) { + collectionMonitorSummary.setLastIndexedVersion(aggregationInfo); + break; } - size += 30; - } while (aggregationInfo.size() != 0 && collectionMonitorSummary.getLastIndexedVersion() == null); + } return collectionMonitorSummary; } diff --git a/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java b/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java index 9112339..7712547 100644 --- a/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java +++ b/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java @@ -26,7 +26,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import javax.ws.rs.core.Response; -import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Map; @@ -63,7 +62,7 @@ public class RepositoryController { @ResponseBody public List getRepositoriesByCountry(@PathVariable("country") String country, @PathVariable("mode") String mode, - @RequestParam(value = "managed", required = false) Boolean managed) throws JSONException, IOException { + @RequestParam(value = "managed", required = false) Boolean managed) { return repositoryService.getRepositoriesByCountry(country, mode, managed); } @@ -83,7 +82,7 @@ public class RepositoryController { public void updateRepositoriesTerms(@RequestBody List repositoriesTerms) throws Exception { Date date = new Date(); if (repositoriesTerms != null) { - for (RepositoryTerms terms : repositoriesTerms) { + for (RepositoryTerms terms : repositoriesTerms) { Repository repository = repositoryService.getRepositoryById(terms.getId()); repository.setConsentTermsOfUse(terms.getConsentTermsOfUse()); repository.setFullTextDownload(terms.getFullTextDownload()); @@ -104,7 +103,7 @@ public class RepositoryController { @RequestParam("requestSortBy") String requestSortBy, @RequestParam("order") String order, @PathVariable("page") int page, - @PathVariable("size") int pageSize) throws Exception { + @PathVariable("size") int pageSize) { return repositoryService.searchRegisteredRepositories(country, typology, englishName, officialName, requestSortBy, order, page, pageSize); } @@ -113,13 +112,13 @@ public class RepositoryController { produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @PostAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (returnObject.registeredby==null and hasAuthority('REGISTERED_USER'))") - public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException { + public Repository getRepositoryById(@PathVariable("id") String id) throws ResourceNotFoundException { Repository repo = repositoryService.getRepositoryById(id); if (repo != null) - logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredby()); + logger.info("Returning repository {} registered by {}", repo.getId(), repo.getRegisteredby()); else - logger.info("Requested repository " + id + " not found"); + logger.info("Requested repository {} not found", id); return repo; } @@ -142,7 +141,7 @@ public class RepositoryController { @ResponseBody public List getRepositoriesByName(@PathVariable("name") String name, @PathVariable("page") String page, - @PathVariable("size") String size) throws JSONException { + @PathVariable("size") String size) { return repositoryService.getRepositoriesByName(name, page, size); } @@ -150,7 +149,7 @@ public class RepositoryController { produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @PostAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (@repositoryService.getRepositoryById(#id).registeredby==null and hasAuthority('REGISTERED_USER'))") - public List getRepositoryInterface(@PathVariable("id") String id) throws JSONException { + public List getRepositoryInterface(@PathVariable("id") String id) { return repositoryService.getRepositoryInterface(id); } @@ -160,7 +159,7 @@ public class RepositoryController { // @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or (hasAuthority(@authorizationService.convertRepoIdToRoleId(#repository.id)) or hasAuthority(@authorizationService.convertRepoIdToRoleId(returnObject.id)))") @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER')") public Repository addRepository(@RequestParam("datatype") String datatype, - @RequestBody Repository repository) throws Exception { + @RequestBody Repository repository) { return repositoryService.addRepository(datatype, repository); } @@ -193,7 +192,7 @@ public class RepositoryController { consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#repository.id)") - public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception { + public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) { return repositoryService.updateRepository(repository, authentication); } @@ -261,7 +260,7 @@ public class RepositoryController { @RequestMapping(value = "/getListLatestUpdate/{mode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public Map getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException { + public Map getListLatestUpdate(@PathVariable("mode") String mode) { return repositoryService.getListLatestUpdate(mode); } diff --git a/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java b/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java index 255bac7..9f4d8b7 100644 --- a/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java +++ b/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java @@ -1,109 +1,108 @@ -package eu.dnetlib.repo.manager.controllers; - -import eu.dnetlib.repo.manager.domain.dto.Role; -import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; -import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; -import eu.dnetlib.repo.manager.service.security.AuthorizationService; -import eu.dnetlib.repo.manager.service.security.RoleMappingService; -import eu.dnetlib.repo.manager.utils.JsonUtils; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.Collection; - -//@RestController -//@RequestMapping(value = "/role-management") -//@Api(description = "Role Management", value = "role-management") -public class UserRoleController { - - private final AaiRegistryService aaiRegistryService; - private final AuthoritiesUpdater authoritiesUpdater; - private final RoleMappingService roleMappingService; - private final AuthorizationService authorizationService; - - @Autowired - UserRoleController(AaiRegistryService aaiRegistryService, - AuthoritiesUpdater authoritiesUpdater, - RoleMappingService roleMappingService, - AuthorizationService authorizationService) { - this.aaiRegistryService = aaiRegistryService; - this.authoritiesUpdater = authoritiesUpdater; - this.roleMappingService = roleMappingService; - this.authorizationService = authorizationService; - } - - /** - * Get the role with the given id. - **/ - @RequestMapping(method = RequestMethod.GET, path = "/role/{id}") -// @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") - public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) { - int roleId = aaiRegistryService.getCouId(type, id); - return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build(); - } - - /** - * Create a new role with the given name and description. - **/ - @RequestMapping(method = RequestMethod.POST, path = "/role") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')") - public Response createRole(@RequestBody Role role) { - aaiRegistryService.createRole(role); - return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build(); - } - - /** - * Subscribe to a type(Community, etc.) with id(ee, egi, etc.) - */ - @ApiOperation(value = "subscribe") - @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") - public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) { - Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); - if (coPersonId == null) { - coPersonId = aaiRegistryService.getCoPersonIdByEmail(); - } - Integer couId = aaiRegistryService.getCouId(type, id); - if (couId != null) { - Integer role = aaiRegistryService.getRoleId(coPersonId, couId); - aaiRegistryService.assignMemberRole(coPersonId, couId, role); - - // Add role to current authorities - authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id)); - - return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build(); - } else { - return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build(); - } - } - ///////////////////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////////////////////////////////////////////// - - @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") - public ResponseEntity getUsersByCouId(@PathVariable("id") Integer id) { -// calls.getUserByCoId() - return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString()); - } - - - @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email") - public ResponseEntity> getRolesByEmail(@PathVariable("email") String email) { - return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email)); - } - - - @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my") - @PreAuthorize("hasAuthority('REGISTERED_USER')") - public ResponseEntity> getRoleNames() { - return ResponseEntity.ok(authorizationService.getUserRoles()); - } - -} +//package eu.dnetlib.repo.manager.controllers; +// +//import eu.dnetlib.repo.manager.domain.dto.Role; +//import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; +//import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; +//import eu.dnetlib.repo.manager.service.security.AuthorizationService; +//import eu.dnetlib.repo.manager.service.security.RoleMappingService; +//import eu.dnetlib.repo.manager.utils.JsonUtils; +//import io.swagger.annotations.ApiOperation; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.http.HttpStatus; +//import org.springframework.http.ResponseEntity; +//import org.springframework.security.access.prepost.PreAuthorize; +//import org.springframework.web.bind.annotation.*; +// +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.Response; +//import java.util.Collection; +// +////@RestController +////@RequestMapping(value = "/role-management") +////@Api(description = "Role Management", value = "role-management") +//public class UserRoleController { +// +// private final AaiRegistryService aaiRegistryService; +// private final AuthoritiesUpdater authoritiesUpdater; +// private final RoleMappingService roleMappingService; +// private final AuthorizationService authorizationService; +// +// @Autowired +// UserRoleController(AaiRegistryService aaiRegistryService, +// AuthoritiesUpdater authoritiesUpdater, +// RoleMappingService roleMappingService, +// AuthorizationService authorizationService) { +// this.aaiRegistryService = aaiRegistryService; +// this.authoritiesUpdater = authoritiesUpdater; +// this.roleMappingService = roleMappingService; +// this.authorizationService = authorizationService; +// } +// +// /** +// * Get the role with the given id. +// **/ +// @RequestMapping(method = RequestMethod.GET, path = "/role/{id}") +//// @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") +// public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) { +// int roleId = aaiRegistryService.getCouId(type, id); +// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build(); +// } +// +// /** +// * Create a new role with the given name and description. +// **/ +// @RequestMapping(method = RequestMethod.POST, path = "/role") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')") +// public Response createRole(@RequestBody Role role) { +// aaiRegistryService.createRole(role); +// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build(); +// } +// +// /** +// * Subscribe to a type(Community, etc.) with id(ee, egi, etc.) +// */ +// @ApiOperation(value = "subscribe") +// @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") +// public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) { +// Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); +// if (coPersonId == null) { +// coPersonId = aaiRegistryService.getCoPersonIdsByEmail(); +// } +// Integer couId = aaiRegistryService.getCouId(type, id); +// if (couId != null) { +// aaiRegistryService.assignMemberRole(coPersonId, couId); +// +// // Add role to current authorities +// authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id)); +// +// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build(); +// } else { +// return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build(); +// } +// } +// ///////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////// +// +// @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") +// public ResponseEntity getUsersByCouId(@PathVariable("id") Integer id) { +//// calls.getUserByCoId() +// return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString()); +// } +// +// +// @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email") +// public ResponseEntity> getRolesByEmail(@PathVariable("email") String email) { +// return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email)); +// } +// +// +// @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my") +// @PreAuthorize("hasAuthority('REGISTERED_USER')") +// public ResponseEntity> getRoleNames() { +// return ResponseEntity.ok(authorizationService.getUserRoles()); +// } +// +//} diff --git a/src/main/java/eu/dnetlib/repo/manager/service/BrokerServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/BrokerServiceImpl.java index 48fb2f8..d4506d2 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/BrokerServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/BrokerServiceImpl.java @@ -8,7 +8,6 @@ import eu.dnetlib.repo.manager.domain.Tuple; import eu.dnetlib.repo.manager.domain.broker.*; import eu.dnetlib.repo.manager.exception.BrokerException; import org.apache.commons.lang.NotImplementedException; -import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -17,8 +16,6 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.stereotype.Service; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; @@ -27,6 +24,7 @@ import org.springframework.web.util.UriComponentsBuilder; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStream; +import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; @@ -52,7 +50,7 @@ public class BrokerServiceImpl implements BrokerService { private HttpHeaders httpHeaders; - private HashMap topics = new HashMap<>(); + private final HashMap topics = new HashMap<>(); @PostConstruct private void initDnetTopicsMap() { @@ -78,7 +76,7 @@ public class BrokerServiceImpl implements BrokerService { @Override - public DatasourcesBroker getDatasourcesOfUser(String user, String includeShared, String includeByOthers) throws JSONException { + public DatasourcesBroker getDatasourcesOfUser(String user, String includeShared, String includeByOthers) { long start = System.currentTimeMillis(); DatasourcesBroker ret = new DatasourcesBroker(); try { @@ -96,7 +94,7 @@ public class BrokerServiceImpl implements BrokerService { logger.error("Exception on getDatasourcesOfUser", e); } long end = System.currentTimeMillis(); - System.out.println("Getting datasources of user in " + (end - start) + "ms"); + logger.debug("Getting datasources of user in " + (end - start) + "ms"); return ret; } @@ -129,14 +127,15 @@ public class BrokerServiceImpl implements BrokerService { final String service = "/events/{page}/{pageSize}"; + long pageNum = Long.parseLong(page); + advQueryObject.setPage(pageNum); + Map uriParams = new HashMap<>(); - uriParams.put("page", Long.parseLong(page)); + uriParams.put("page", pageNum); uriParams.put("pageSize", Long.parseLong(size)); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service); - MultiValueMap headers = new LinkedMultiValueMap<>(); - advQueryObject.setPage(Long.parseLong(page)); HttpEntity entity = new HttpEntity<>(advQueryObject, httpHeaders); ResponseEntity resp; try { @@ -144,8 +143,7 @@ public class BrokerServiceImpl implements BrokerService { builder.buildAndExpand(uriParams).encode().toUri(), HttpMethod.POST, entity, - new ParameterizedTypeReference() { - } + new ParameterizedTypeReference() {} ); } catch (RestClientException e) { throw new BrokerException(e); @@ -171,8 +169,7 @@ public class BrokerServiceImpl implements BrokerService { // sort the collection by the second field of the tuple which is size entries.sort((e1, e2) -> (int) (e2.getFirst().getSize() - e1.getFirst().getSize())); long stop = System.currentTimeMillis(); - System.out.println("getDatasourcesOfUserType returned in " + (stop - start) + "ms "); - + logger.debug("getDatasourcesOfUserType returned in " + (stop - start) + "ms "); return entries; } @@ -180,7 +177,7 @@ public class BrokerServiceImpl implements BrokerService { public EventsPage showEvents(String datasourceName, String topic, String page, - String size) throws BrokerException, JSONException { + String size) throws BrokerException { final String service = "/events"; @@ -209,14 +206,14 @@ public class BrokerServiceImpl implements BrokerService { final String service = "/subscriptions"; - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service) - .queryParam("email", userEmail); + URI uri = UriComponentsBuilder.fromHttpUrl(openairePath + service) + .queryParam("email", userEmail).build().encode().toUri(); - logger.debug("{}", builder.build().encode().toUri()); + logger.debug("{}", uri); ResponseEntity>> resp; try { resp = restTemplate.exchange( - builder.build().encode().toUri(), + uri, HttpMethod.GET, null, new ParameterizedTypeReference>>() { @@ -228,10 +225,9 @@ public class BrokerServiceImpl implements BrokerService { } @Override - public Map> getSimpleSubscriptionsOfUserByRepoId(String userEmail, String repoId) throws BrokerException { - Map> subscriptionsOfUser = getSimpleSubscriptionsOfUser(userEmail); + public Map> getSimpleSubscriptionsOfUserByRepoId(String userEmail, String repoId) { //throws BrokerException { throw new NotImplementedException(); -// return null; + //Map> subscriptionsOfUser = getSimpleSubscriptionsOfUser(userEmail); } @Override diff --git a/src/main/java/eu/dnetlib/repo/manager/service/DashboardServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/DashboardServiceImpl.java index a344fcc..38f15cc 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/DashboardServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/DashboardServiceImpl.java @@ -39,41 +39,50 @@ public class DashboardServiceImpl implements DashboardService { try { List repositoriesOfUser = repositoryService.getRepositoriesSnippetsOfUser(userEmail, page, size); - for (RepositorySnippet repository : repositoriesOfUser) { + for (RepositorySnippet repository : repositoriesOfUser) + { + String repoId = repository.getId(); + String repoOfficialName = repository.getOfficialname(); + RepositorySummaryInfo repositorySummaryInfo = new RepositorySummaryInfo(); - repositorySummaryInfo.setId(repository.getId()); - repositorySummaryInfo.setRepositoryName(repository.getOfficialname()); + repositorySummaryInfo.setId(repoId); + repositorySummaryInfo.setRepositoryName(repoOfficialName); repositorySummaryInfo.setLogoURL(repository.getLogoUrl()); //TODO getRepositoryAggregations returns only the 20 more recent items. Is it positive that we will find an indexed version there? + boolean isIndexedVersionFound = false; long start = System.currentTimeMillis(); - List aggregationInfoList = aggregationService.getRepositoryAggregations(repository.getId(), 0, 20); + List aggregationInfoList = aggregationService.getRepositoryAggregations(repoId, 0, 20); for (AggregationInfo aggregationInfo : aggregationInfoList) { if (aggregationInfo.isIndexedVersion()) { repositorySummaryInfo.setRecordsCollected(aggregationInfo.getNumberOfRecords()); repositorySummaryInfo.setLastIndexedVersion(DateUtils.toDate(aggregationInfo.getDate())); + isIndexedVersionFound = true; break; } } long end = System.currentTimeMillis(); - System.out.println("Got repo aggregations in " + (end - start) + "ms"); + if ( isIndexedVersionFound ) + logger.debug("Got repo aggregations in " + (end - start) + "ms"); + else + logger.warn("Could not find repo aggregations, after " + (end - start) + "ms!"); try { - MetricsInfo metricsInfo = repositoryService.getMetricsInfoForRepository(repository.getId()); + MetricsInfo metricsInfo = repositoryService.getMetricsInfoForRepository(repoId); repositorySummaryInfo.setTotalDownloads(metricsInfo.getMetricsNumbers().getTotalDownloads()); repositorySummaryInfo.setTotalViews(metricsInfo.getMetricsNumbers().getTotalViews()); } catch (RepositoryServiceException e) { - logger.error("Exception getting metrics info for repository: " + repository.getId(), e); + logger.error("Exception getting metrics info for repository: {}, {} ", repoId, repoOfficialName, e); } try { - List events = brokerService.getTopicsForDatasource(repository.getOfficialname()); + List events = brokerService.getTopicsForDatasource(repoOfficialName); Long totalEvents = 0L; for (BrowseEntry browseEntry : events) totalEvents += browseEntry.getSize(); repositorySummaryInfo.setEnrichmentEvents(totalEvents); } catch (BrokerException e) { - logger.error("Exception getting broker events for repository: " + repository.getId(), e); + logger.error("Exception getting broker events for repository: {}, {} ", repoId, repoOfficialName, e); } repositorySummaryInfoList.add(repositorySummaryInfo); diff --git a/src/main/java/eu/dnetlib/repo/manager/service/EmailUtils.java b/src/main/java/eu/dnetlib/repo/manager/service/EmailUtils.java index fed2c64..ddfdb9d 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/EmailUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/EmailUtils.java @@ -32,38 +32,38 @@ public interface EmailUtils { void sendUserRegistrationEmail(Repository repository, Authentication authentication); @Async - void sendAdminRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication); + void sendAdminRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication); @Async - void sendUserRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication); + void sendUserRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication); /****SUCCESSFUL REGISTRATION RESULTS EMAILS****/ @Async - void sendUserRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendUserRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); @Async - void sendAdminRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendAdminRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); /****FAILURE REGISTRATION RESULTS EMAILS****/ @Async - void sendUserRegistrationResultsFailureEmail(String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendUserRegistrationResultsFailureEmail(String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); @Async - void sendAdminRegistrationResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendAdminRegistrationResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); /****SUCCESSFUL UPDATE RESULTS EMAILS****/ @Async - void sendUserUpdateResultsSuccessEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendUserUpdateResultsSuccessEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); @Async - void sendAdminUpdateResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendAdminUpdateResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); /****FAILURE UPDATE RESULTS EMAILS****/ @Async - void sendUserUpdateResultsFailureEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendUserUpdateResultsFailureEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); @Async - void sendAdminUpdateResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication); + void sendAdminUpdateResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication); /****FAILURE UPDATE INTERFACE COMPLIANCE****/ @Async @@ -91,10 +91,10 @@ public interface EmailUtils { void sendUserUpdateRepositoryInfoEmail(Repository repository, Authentication authentication); @Async - void sendAdminUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication); + void sendAdminUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication); @Async - void sendUserUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication); + void sendUserUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication); @Async void sendSubmitJobForValidationEmail(Authentication authentication, JobForValidation jobForValidation); @@ -102,6 +102,7 @@ public interface EmailUtils { @Async void sendUponJobCompletion(String repoId, String repoInterfaceId, + String compatibility, int scoreUsage, int scoreContent, boolean isSuccess, diff --git a/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java index 6fc7ce8..353082b 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java @@ -5,6 +5,7 @@ import eu.dnetlib.domain.functionality.validator.JobForValidation; import eu.dnetlib.repo.manager.domain.InterfaceComplianceRequest; import eu.dnetlib.repo.manager.domain.Repository; import eu.dnetlib.repo.manager.domain.RepositoryInterface; +import eu.dnetlib.repo.manager.domain.dto.User; import eu.dnetlib.repo.manager.exception.ValidationServiceException; import eu.dnetlib.utils.MailLibrary; import org.mitre.openid.connect.model.OIDCAuthenticationToken; @@ -12,15 +13,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; +import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; @Component("emailUtils") +@Async public class EmailUtilsImpl implements EmailUtils { private final static Logger logger = LoggerFactory.getLogger(EmailUtilsImpl.class); @@ -48,687 +53,596 @@ public class EmailUtilsImpl implements EmailUtils { @Override public void sendAdministratorRequestToEnableMetrics(PiwikInfo piwikInfo) { + String subject = "[OpenAIRE-Usage Statistics] New request to enable usage statistics"; - try { - String subject = "[OpenAIRE-Usage Statistics] New request to enable usage statistics"; + String message = + "we have received a request to enable the OpenAIRE usage statistics for the following repository \n" + + "\n" + + "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" + + "Requestor - " + piwikInfo.getRequestorName() + ", " + piwikInfo.getRequestorEmail() + "\n" + + "Matomo ID - " + piwikInfo.getSiteId() + "\n" + + "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" + + "\n" + + "For more information about this request, go here: \n" + + this.baseUrl + "/admin/metrics"; + message = createAdminMail(message); - String message = - "we have received a request to enable the OpenAIRE usage statistics for the following repository \n" + - "\n" + - "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" + - "Requestor - " + piwikInfo.getRequestorName() + ", " + piwikInfo.getRequestorEmail() + "\n" + - "Matomo ID - " + piwikInfo.getSiteId() + "\n" + - "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" + - "\n" + - "For more information about this request, go here: \n" + - this.baseUrl + "/admin/metrics"; - message = createAdminMail(message); - - this.sendMail(this.usageStatsAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending request to enable metrics email to administrator: " + this.usageStatsAdminEmail, e); - } + this.sendMail(this.usageStatsAdminEmail, subject, message); } @Override public void sendUserRequestToEnableMetrics(PiwikInfo piwikInfo) { + String subject = "[OpenAIRE-Usage Statistics] Your request to enable usage statistics"; - try { - String subject = "[OpenAIRE-Usage Statistics] Your request to enable usage statistics"; + String message = "Dear " + piwikInfo.getRequestorName() + ",\n" + + "\n" + + "we have received your request to enable the OpenAIRE usage statistics for your repository\n" + + "\n" + + "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" + + "Matomo ID - " + piwikInfo.getSiteId() + "\n" + + "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" + + "\n" + + "In order to enable the usage statistics, you must install the OpenAIRE's tracking code in your repository software. " + + "OpenAIRE's usage statistics service tracking code is maintained on Github as a patch for various versions of DSpace " + + "(https://github.com/openaire/OpenAIRE-Piwik-DSpace) and as an Eprints plugin for version 3 " + + "(https://github.com/openaire/EPrints-OAPiwik). In case the platform is different from DSpace or EPrints please contact " + + "the OpenAIRE team in repositoryusagestats@openaire.eu in order to find a solution.\n" + + "\n" + + "For more information about your request and configuration details, go here: \n" + + this.baseUrl + "/getImpact/instructions/" + piwikInfo.getRepositoryId() + "\n" + + "\n" + + "Once you have finished configuring your repository or if you have any questions, please notify the OpenAIRE team by sending \n" + + "an email to repositoryusagestats@openaire.eu\n" + + "\n" + + "Best,\n" + + "The OpenAIRE team"; - String message = "Dear " + piwikInfo.getRequestorName() + ",\n" + - "\n" + - "we have received your request to enable the OpenAIRE usage statistics for your repository\n" + - "\n" + - "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" + - "Matomo ID - " + piwikInfo.getSiteId() + "\n" + - "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" + - "\n" + - "In order to enable the usage statistics, you must install the OpenAIRE's tracking code in your repository software. " + - "OpenAIRE's usage statistics service tracking code is maintained on Github as a patch for various versions of DSpace " + - "(https://github.com/openaire/OpenAIRE-Piwik-DSpace) and as an Eprints plugin for version 3 " + - "(https://github.com/openaire/EPrints-OAPiwik). In case the platform is different from DSpace or EPrints please contact " + - "the OpenAIRE team in repositoryusagestats@openaire.eu in order to find a solution.\n" + - "\n" + - "For more information about your request and configuration details, go here: \n" + - this.baseUrl + "/getImpact/instructions/" + piwikInfo.getRepositoryId() + "\n" + - "\n" + - "Once you have finished configuring your repository or if you have any questions, please notify the OpenAIRE team by sending \n" + - "an email to repositoryusagestats@openaire.eu\n" + - "\n" + - "Best,\n" + - "The OpenAIRE team"; - - this.sendMail(piwikInfo.getRequestorEmail(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending request to enable metrics email to user: " + piwikInfo.getRequestorEmail(), e); - } + this.sendMail(piwikInfo.getRequestorEmail(), subject, message); } @Override public void sendAdministratorMetricsEnabled(PiwikInfo piwikInfo) { + String subject = "[OpenAIRE-Usage Statistics] Usage statistics have been enabled"; - try { - String subject = "[OpenAIRE-Usage Statistics] Usage statistics have been enabled"; + String message = + "The installation and configuration of OpenAIRE's tracking code for the following repository " + + "has been completed and validated and the usage statistics have been enabled in OpenAIRE.\n" + + "\n" + + "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" + + "Requestor - " + piwikInfo.getRequestorName() + ", " + piwikInfo.getRequestorEmail() + "\n" + + "Piwik ID - " + piwikInfo.getSiteId() + "\n" + + "Authentication token - " + piwikInfo.getAuthenticationToken(); + message = createAdminMail(message); - String message = - "The installation and configuration of OpenAIRE's tracking code for the following repository " + - "has been completed and validated and the usage statistics have been enabled in OpenAIRE.\n" + - "\n" + - "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" + - "Requestor - " + piwikInfo.getRequestorName() + ", " + piwikInfo.getRequestorEmail() + "\n" + - "Piwik ID - " + piwikInfo.getSiteId() + "\n" + - "Authentication token - " + piwikInfo.getAuthenticationToken(); - message = createAdminMail(message); - - this.sendMail(this.usageStatsAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending metrics enabled notification email to administator: " + this.usageStatsAdminEmail, e); - } + this.sendMail(this.usageStatsAdminEmail, subject, message); } @Override public void sendUserMetricsEnabled(PiwikInfo piwikInfo) { + String subject = "[OpenAIRE-Usage Statistics] Usage statistics have been enabled"; - try { - String subject = "[OpenAIRE-Usage Statistics] Usage statistics have been enabled"; + String message = "Dear " + piwikInfo.getRequestorName() + ",\n" + + "\n" + + "The installation and configuration of OpenAIRE's tracking code for your repository \"" + piwikInfo.getRepositoryName() + + "\" has been completed and validated and the usage statistics have been enabled in OpenAIRE.\n" + + "\n" + + "You can preview the statistics in your repository's dashboard: \n" + + this.baseUrl + "/getImpact/" + piwikInfo.getRepositoryId() + "\n" + + "\n" + + " For more information and questions, you can contact the openaire support team by sending an email to " + + "repositoryusagestats@openaire.eu\n" + + "\n" + + "Best Regards,\n" + + "The OpenAIRE team"; - String message = "Dear " + piwikInfo.getRequestorName() + ",\n" + - "\n" + - "The installation and configuration of OpenAIRE's tracking code for your repository \"" + piwikInfo.getRepositoryName() + - "\" has been completed and validated and the usage statistics have been enabled in OpenAIRE.\n" + - "\n" + - "You can preview the statistics in your repository's dashboard: \n" + - this.baseUrl + "/getImpact/" + piwikInfo.getRepositoryId() + "\n" + - "\n" + - " For more information and questions, you can contact the openaire support team by sending an email to " + - "repositoryusagestats@openaire.eu\n" + - "\n" + - "Best Regards,\n" + - "The OpenAIRE team"; - - this.sendMail(piwikInfo.getRequestorEmail(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending metrics enabled notification email to user: " + piwikInfo.getRequestorEmail(), e); - } + this.sendMail(piwikInfo.getRequestorEmail(), subject, message); } @Override public void sendAdminRegistrationEmail(Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE content provider registration for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String subject = "OpenAIRE content provider registration for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to register the " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]" + - " to the OpenAIRE compliant list of content providers. " + - "\n\n" + - "User Contact: " + authentication.getName() + " (" + ((OIDCAuthenticationToken) authentication).getUserInfo().getEmail() + ")" + - "\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically."; - message = createAdminMail(message); + String message = + "We received a request to register the " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]" + + " to the OpenAIRE compliant list of content providers. " + + "\n\n" + + "User Contact: " + ((OIDCAuthenticationToken) authentication).getUserInfo().getName() + + " (" + ((OIDCAuthenticationToken) authentication).getUserInfo().getEmail() + ")" + + "\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to the administrator", e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override public void sendUserRegistrationEmail(Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE content provider registration for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String subject = "OpenAIRE content provider registration for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to register the " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]" + - " to the OpenAIRE compliant list of content providers. " + - "\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically.\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "We received a request to register the " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]" + + " to the OpenAIRE compliant list of content providers. " + + "\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically.\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(repository.getRegisteredby(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); + Collection emailTo = new HashSet<>(); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override - public void sendAdminRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) { - try { - String subject = "OpenAIRE new interface registration request started for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendAdminRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication) { + String subject = "OpenAIRE new interface registration request started for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to add the following interface: \n\n" + - "Base URL: " + repositoryInterface.getBaseurl() + "\n" + - "Set: " + repositoryInterface.getAccessSet() + "\n" + - "Guidelines: " + repositoryInterface.getCompatibilityOverride() + "\n\n" + - "to " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; + String message = + "We received a request to add the following interface: \n\n" + + "Base URL: " + repositoryInterface.getBaseurl() + "\n" + + "Set: " + repositoryInterface.getAccessSet() + "\n" + + "Selected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + "\n\n" + + "to " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; - if (comment != null) - message += "\nThe users comment was '" + comment + "'\n"; + if (comment != null) + message += "\nThe users comment was '" + comment + "'\n"; - message += "A validation process for this interface against the OpenAIRE guidelines compatibility " + - "has been started. You will be informed in another message once the process is finished." + - "\n\n" + - "User Contact: " + authentication.getName() + " (" + ((OIDCAuthenticationToken) authentication).getUserInfo().getEmail() + ")" + - "\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically."; - message = createAdminMail(message); + message += "A validation process for this interface against the OpenAIRE guidelines compatibility " + + "has been started. You will be informed in another message once the process is finished." + + "\n\n" + + "User Contact: " + ((OIDCAuthenticationToken) authentication).getUserInfo().getName() + + " (" + ((OIDCAuthenticationToken) authentication).getUserInfo().getEmail() + ")" + + "\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration of interface notification email to the administrator", e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override - public void sendUserRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) { - try { - String subject = "OpenAIRE new interface registration request started for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to add the following interface: \n\n" + - "Base URL: " + repositoryInterface.getBaseurl() + "\n" + - "Set: " + repositoryInterface.getAccessSet() + "\n" + - "Guidelines: " + repositoryInterface.getCompatibilityOverride() + "\n\n" + - "to " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; + public void sendUserRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication) { + String subject = "OpenAIRE new interface registration request started for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String message = + "We received a request to add the following interface: \n\n" + + "Base URL: " + repositoryInterface.getBaseurl() + "\n" + + "Set: " + repositoryInterface.getAccessSet() + "\n" + + "Selected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + "\n\n" + + "to " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; - if (comment != null) { - message += "\n Your comment was '" + comment + "'\n"; - } - - message += "A validation process for this interface against the OpenAIRE guidelines compatibility " + - "has been started. You will be informed in another message once the process is finished." + - "\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically."; - message = createUserMail(message, authentication); - - this.sendMail(repository.getRegisteredby(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration of interface notification email to user: " + repository.getRegisteredby(), e); + if (comment != null) { + message += "\n Your comment was '" + comment + "'\n"; } + + message += "A validation process for this interface against the OpenAIRE guidelines compatibility " + + "has been started. You will be informed in another message once the process is finished." + + "\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically."; + message = createUserMail(message, authentication); + + Collection emailTo = new HashSet<>(); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); + } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override - public void sendUserRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE new interface registration request - results (success) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendUserRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE new interface registration request - results (success) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on " + "[" + repository.getOfficialname() + "]" + - " was successful and the datasource type \"" + repository.getEoscDatasourceType() + "\" will be prepared for aggregation in OpenAIRE." + - "\n\n" + - "Please note that it usually takes about 3-4 weeks until a data source is indexed and it's metadata visible on openaire.eu.\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "the compatibility test on " + "[" + repository.getOfficialname() + "]" + + " was successful and the datasource type \"" + repository.getEoscDatasourceType() + "\" will be prepared for aggregation in OpenAIRE." + + "\n\n" + + "Please note that it usually takes about 3-4 weeks until a data source is indexed and it's metadata visible on openaire.eu.\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(repository.getRegisteredby(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); + Collection emailTo = new HashSet<>(); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override - public void sendAdminRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE new interface registration request - results (success) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendAdminRegistrationResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE new interface registration request - results (success) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on " + "[" + repository.getOfficialname() + "]" + - " was successful and the datasource type \"" + repository.getEoscDatasourceType() + "\" will be prepared for aggregation in OpenAIRE." + - "\n\n" + - "Please note that it usually takes about 3-4 weeks until a data source is indexed and it's metadata visible on openaire.eu.\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nUser Contact:" + issuerEmail + "" + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createAdminMail(message); + String message = + "the compatibility test on " + "[" + repository.getOfficialname() + "]" + + " was successful and the datasource type \"" + repository.getEoscDatasourceType() + "\" will be prepared for aggregation in OpenAIRE." + + "\n\n" + + "Please note that it usually takes about 3-4 weeks until a data source is indexed and it's metadata visible on openaire.eu.\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nDesired Selected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nUser Contact: " + issuerEmail + "" + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override - public void sendUserRegistrationResultsFailureEmail(String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE new interface registration request - results (failure) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on " + "[" + repository.getOfficialname() + "]" + - " was not successful and the registration process was interrupted." + - "\n\n" + - "We will check what caused the problem and get back to you within a couple of days.\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + public void sendUserRegistrationResultsFailureEmail(String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE new interface registration request - results (failure) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String message = + "the compatibility test on " + "[" + repository.getOfficialname() + "]" + + " was not successful and the registration process was interrupted." + + "\n\n" + + "We will check what caused the problem and get back to you within a couple of days.\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(repository.getRegisteredby(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); + Collection emailTo = new HashSet<>(); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override - public void sendAdminRegistrationResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE new interface registration request - results (failure) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendAdminRegistrationResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE new interface registration request - results (failure) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on " + "[" + repository.getOfficialname() + "]" + - " was not successful and the registration process was interrupted." + - "\n\n" + - "We will check what caused the problem and get back to you within a couple of days.\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nUser Contact:" + issuerEmail + "" + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createAdminMail(message); + String message = + "the compatibility test on [" + repository.getOfficialname() + "]" + + " was not successful and the registration process was interrupted." + + "\n\n" + + "We will check what caused the problem and get back to you within a couple of days.\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nUser Contact: " + issuerEmail + "" + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override - public void sendUserUpdateResultsSuccessEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE interface update request - results (success) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendUserUpdateResultsSuccessEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE interface update request - results (success) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on [" + repository.getOfficialname() + "] has been successful\n\n" + - "We will check your transmitted information and adjust the aggregation settings accordingly. Please note that it usually takes about 3-4 weeks until the changes are visible on openaire.eu." + "\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "the compatibility test on [" + repository.getOfficialname() + "] has been successful\n\n" + + "We will check your transmitted information and adjust the aggregation settings accordingly. Please note that it usually takes about 3-4 weeks until the changes are visible on openaire.eu." + "\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(issuer, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to the administrator", e); - } + this.sendMail(issuer, subject, message); } @Override - public void sendAdminUpdateResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE interface update request - results (success) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendAdminUpdateResultsSuccessEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE interface update request - results (success) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on [" + repository.getOfficialname() + "] has been successful\n\n" + - "We will check your transmitted information and adjust the aggregation settings accordingly. Please note that it usually takes about 3-4 weeks until the changes are visible on openaire.eu." + "\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nUser Contact:" + issuerEmail + "" + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createAdminMail(message); + String message = + "the compatibility test on [" + repository.getOfficialname() + "] has been successful\n\n" + + "We will check your transmitted information and adjust the aggregation settings accordingly. Please note that it usually takes about 3-4 weeks until the changes are visible on openaire.eu." + "\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nUser Contact: " + issuerEmail + "" + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to the administrator", e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override - public void sendUserUpdateResultsFailureEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE interface update request - results (failure) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendUserUpdateResultsFailureEmail(String issuer, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE interface update request - results (failure) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on " + "[" + repository.getOfficialname() + "]" + - " was not successful." + - "\n\n" + - "WWe will check your transmitted information to see what caused the problem and get back to you within a couple of days.\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "the compatibility test on [" + repository.getOfficialname() + "] was not successful." + + "\n\n" + + "We will check your transmitted information to see what caused the problem and get back to you within a couple of days.\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(issuer, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); - } + this.sendMail(issuer, subject, message); } @Override - public void sendAdminUpdateResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE interface update request - results (failure) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendAdminUpdateResultsFailureEmail(String issuerEmail, String jobId, RepositoryInterface repositoryInterface, String desiredCompatibility, Repository repository, Authentication authentication) { + String subject = "OpenAIRE interface update request - results (failure) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "the compatibility test on " + "[" + repository.getOfficialname() + "]" + - " was not successful." + - "\n\n" + - "WWe will check your transmitted information to see what caused the problem and get back to you within a couple of days.\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + repositoryInterface.getCompatibilityOverride() + - "\n\nUser Contact:" + issuerEmail + "" + - "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated manually\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createAdminMail(message); + String message = + "the compatibility test on " + "[" + repository.getOfficialname() + "]" + + " was not successful." + + "\n\n" + + "WWe will check your transmitted information to see what caused the problem and get back to you within a couple of days.\n\n" + + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + + "\n\nUser Contact: " + issuerEmail + "" + + "\n\nYou can review the validation results here.\n" + valBaseUrl + "" + jobId + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated manually\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override public void sendUserUpdateInterfaceComplianceFailure(List emails, Repository repository, RepositoryInterface repositoryInterface, InterfaceComplianceRequest request) { - try { - String subject = "OpenAIRE interface update compliance request - results (failure) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String subject = "OpenAIRE interface update compliance request - results (failure) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "The request for changing the compatibility of " + "[" + repository.getOfficialname() + "]" + - " was not successful." + - "\n\n" + + String message = + "The request for changing the compatibility of " + "[" + repository.getOfficialname() + "]" + + " was not successful." + + "\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + request.getDesiredCompatibilityLevel() + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated automatically\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createRepoAdminsMail(message); + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + request.getDesiredCompatibilityLevel() + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated automatically\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createRepoAdminsMail(message); - this.sendMail(emails, subject, message); - - } catch (Exception e) { - logger.error("Notification email to repository admins failed.\nRepository: {}\nRequest: {}", repository, request, e); - } + this.sendMail(emails, subject, message); } @Override public void sendAdminUpdateInterfaceComplianceFailure(Repository repository, RepositoryInterface repositoryInterface, InterfaceComplianceRequest request) { - try { - String subject = "OpenAIRE interface update compliance request - results (failure) for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String subject = "OpenAIRE interface update compliance request - results (failure) for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "The request for changing the compatibility of " + "[" + repository.getOfficialname() + "]" + - " was not successful." + - "\n\n" + + String message = + "The request for changing the compatibility of " + "[" + repository.getOfficialname() + "]" + + " was not successful." + + "\n\n" + - "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + - "\nOfficial Name:" + repository.getOfficialname() + - "\n\nBase URL: " + repositoryInterface.getBaseurl() + - "\n\nValidation Set: " + repositoryInterface.getAccessSet() + - "\n\nGuidelines: " + request.getDesiredCompatibilityLevel() + - "\n\n\nPlease do not reply to this email\n" + - "This message has been generated automatically\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createAdminMail(message); + "Registration identifier in OpenAIRE: " + repository.getNamespaceprefix() + + "\nOfficial Name:" + repository.getOfficialname() + + "\n\nBase URL: " + repositoryInterface.getBaseurl() + + "\n\nSet: " + repositoryInterface.getAccessSet() + + "\n\nSelected Guidelines: " + request.getDesiredCompatibilityLevel() + + "\n\n\nPlease do not reply to this email\n" + + "This message has been generated automatically\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override public void sendUserValidationResults(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE validator - Test results "; + String subject = "OpenAIRE validator - Test results "; - String message = - "the validation request you have submitted has finished. You can retrieve the results by following this url: " + valBaseUrl + "" + jobId + " .\n\n" + - "Please do not reply to this message.\n" + - "This message has been generated automatically.\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "the validation request you have submitted has finished. You can retrieve the results by following this url: " + valBaseUrl + "" + jobId + " .\n\n" + + "Please do not reply to this message.\n" + + "This message has been generated automatically.\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(issuer, subject, message); - - } catch (Exception e) { - logger.error("Error while sending validation submission notification email to user: " + issuer, e); + Collection emailTo = new HashSet<>(); + emailTo.add(issuer); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override public void sendAdminValidationResults(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE validator - Test results "; + String subject = "OpenAIRE validator - Test results "; - String message = - "a validation request has finished. You can retrieve the results by following this url: " + valBaseUrl + "" + jobId + " .\n\n" + - "\n\nUser Contact:" + issuer + "" + - "Please do not reply to this message.\n" + - "This message has been generated automatically.\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createAdminMail(message); + String message = + "a validation request has finished. You can retrieve the results by following this url: " + valBaseUrl + "" + jobId + " .\n\n" + + "\n\nUser Contact: " + issuer + "" + + "Please do not reply to this message.\n" + + "This message has been generated automatically.\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending validation submission notification email to user: " + issuer, e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override public void sendAdminGeneralFailure(String issuer, String jobId, RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE validator - job failure"; + String subject = "OpenAIRE validator - job failure"; - String message = - "the validation job that was automatically submitted for the update/registration of the interface " + repositoryInterface.getId() + " (" + repositoryInterface.getBaseurl() + ", " + repositoryInterface.getAccessSet() + ") of the repository " + repository.getId() + " (" + repository.getOfficialname() + ") failed to complete." + - "This message has been generated automatically."; - message = createAdminMail(message); + String message = + "the validation job that was automatically submitted for the update/registration of the interface " + + repositoryInterface.getId() + " (" + repositoryInterface.getBaseurl() + ", " + + repositoryInterface.getAccessSet() + ") of the repository " + repository.getId() + + " (" + repository.getOfficialname() + ") failed to complete." + + "This message has been generated automatically."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending validation submission notification email to user: " + issuer, e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override public void sendAdminUpdateRepositoryInfoEmail(Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE content provider update information for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String subject = "OpenAIRE content provider update information for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to update the basic information for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically."; - message = createAdminMail(message); + String message = + "We received a request to update the basic information for " + repository.getEoscDatasourceType() + + "[" + repository.getOfficialname() + "].\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to the administrator", e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override public void sendUserUpdateRepositoryInfoEmail(Repository repository, Authentication authentication) { - try { - String subject = "OpenAIRE content provider update information for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + String subject = "OpenAIRE content provider update information for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to update the basic information for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically.\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "We received a request to update the basic information for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically.\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(repository.getRegisteredby(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); + Collection emailTo = new HashSet<>(); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override - public void sendAdminUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) { - try { - String subject = "OpenAIRE interface update request started for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendAdminUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication) { + String subject = "OpenAIRE interface update request started for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to update the following interface: \n\n" + - "Base URL: " + repositoryInterface.getBaseurl() + "\n" + - "Set: " + repositoryInterface.getAccessSet() + "\n" + - "Guidelines: " + repositoryInterface.getCompatibilityOverride() + "\n\n" + - "for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; + String message = + "We received a request to update the following interface: \n\n" + + "Base URL: " + repositoryInterface.getBaseurl() + "\n" + + "Set: " + repositoryInterface.getAccessSet() + "\n" + + "Selected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + "\n\n" + + "for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; - if (comment != null) - message += "\nThe users comment was '" + comment + "'\n"; + if (comment != null) + message += "\nThe users comment was '" + comment + "'\n"; - message += "A new iteration process of the validation against the OpenAIRE guidelines compatibility has been started.\n\n" + - "User Contact: " + authentication.getName() + " (" + ((OIDCAuthenticationToken) authentication).getUserInfo().getEmail() + ")" + - "\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically."; - message = createAdminMail(message); + message += "A new iteration process of the validation against the OpenAIRE guidelines compatibility has been started.\n\n" + + "User Contact: " + ((OIDCAuthenticationToken) authentication).getUserInfo().getName() + + " (" + ((OIDCAuthenticationToken) authentication).getUserInfo().getEmail() + ")" + + "\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically."; + message = createAdminMail(message); - this.sendMail(this.provideAdminEmail, subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to the administrator", e); - } + this.sendMail(this.provideAdminEmail, subject, message); } @Override - public void sendUserUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) { - try { - String subject = "OpenAIRE interface update request started for " + - repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; + public void sendUserUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, String desiredCompatibility, Authentication authentication) { + String subject = "OpenAIRE interface update request started for " + + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "]"; - String message = - "We received a request to update the following interface: \n\n" + - "Base URL: " + repositoryInterface.getBaseurl() + "\n" + - "Set: " + repositoryInterface.getAccessSet() + "\n" + - "Guidelines: " + repositoryInterface.getCompatibilityOverride() + "\n\n" + - "for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; + String message = + "We received a request to update the following interface: \n\n" + + "Base URL: " + repositoryInterface.getBaseurl() + "\n" + + "Set: " + repositoryInterface.getAccessSet() + "\n" + + "Selected Guidelines: " + getSelectedGuidelines(desiredCompatibility, repositoryInterface) + "\n\n" + + "for " + repository.getEoscDatasourceType() + "[" + repository.getOfficialname() + "].\n"; - if (comment != null) { - message += "\n Your comment was '" + comment + "'\n"; - } - - message += "A new iteration process of the validation against the OpenAIRE guidelines compatibility has been started.\n\n" + - "Please do not reply to this message\n" + - "This message has been generated automatically.\n\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); - - this.sendMail(repository.getRegisteredby(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending registration notification email to user: " + repository.getRegisteredby(), e); + if (comment != null) { + message += "\n Your comment was '" + comment + "'\n"; } + + message += "A new iteration process of the validation against the OpenAIRE guidelines compatibility has been started.\n\n" + + "Please do not reply to this message\n" + + "This message has been generated automatically.\n\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); + + Collection emailTo = new HashSet<>(); + if (repository.getRegisteredby() != null) { + emailTo.add(repository.getRegisteredby()); + } + emailTo.add(User.from(((OIDCAuthenticationToken) authentication).getUserInfo()).getEmail()); + this.sendMail(emailTo, subject, message); } @Override public void sendSubmitJobForValidationEmail(Authentication authentication, JobForValidation jobForValidation) { - try { - String subject = "OpenAIRE validator - Test submission "; + String subject = "OpenAIRE validator - Test submission "; - String message = - "The validation request you have submitted has started.\n" + - "Please do not reply to this message.\n" + - "This message has been generated automatically.\n" + - "If you have any questions, write to 'helpdesk@openaire.eu'."; - message = createUserMail(message, authentication); + String message = + "The validation request you have submitted has started.\n" + + "Please do not reply to this message.\n" + + "This message has been generated automatically.\n" + + "If you have any questions, write to 'helpdesk@openaire.eu'."; + message = createUserMail(message, authentication); - this.sendMail(jobForValidation.getUserEmail(), subject, message); - - } catch (Exception e) { - logger.error("Error while sending validation submission notification email to user: " + jobForValidation.getUserEmail(), e); - } + this.sendMail(jobForValidation.getUserEmail(), subject, message); } @Override public void sendUponJobCompletion( String repoId, String repoInterfaceId, + String compatibility, int scoreUsage, int scoreContent, boolean isSuccess, @@ -745,11 +659,11 @@ public class EmailUtilsImpl implements EmailUtils { if (!isUpdate) { if (isSuccess) { if (scoreContent >= 50 && scoreUsage >= 50) { - this.sendUserRegistrationResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); - this.sendAdminRegistrationResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendUserRegistrationResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendAdminRegistrationResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); } else { - this.sendUserRegistrationResultsFailureEmail(jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); - this.sendAdminRegistrationResultsFailureEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendUserRegistrationResultsFailureEmail(jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendAdminRegistrationResultsFailureEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); } } else { this.sendAdminGeneralFailure(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); @@ -757,11 +671,11 @@ public class EmailUtilsImpl implements EmailUtils { } else { if (isSuccess) { if (scoreContent >= 50 && scoreUsage >= 50) { - this.sendUserUpdateResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); - this.sendAdminUpdateResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendUserUpdateResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendAdminUpdateResultsSuccessEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); } else { - this.sendUserUpdateResultsFailureEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); - this.sendAdminUpdateResultsFailureEmail(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendUserUpdateResultsFailureEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); + this.sendAdminUpdateResultsFailureEmail(issuerEmail, jobId, repositoryInterface, compatibility, repository, SecurityContextHolder.getContext().getAuthentication()); } } else { this.sendAdminGeneralFailure(issuerEmail, jobId, repositoryInterface, repository, SecurityContextHolder.getContext().getAuthentication()); @@ -774,7 +688,7 @@ public class EmailUtilsImpl implements EmailUtils { this.sendMail(Collections.singletonList(email), subject, message); } - public void sendMail(List recipients, String subject, String message) { + public void sendMail(Collection recipients, String subject, String message) { try { logger.debug("Sending e-mail\nRecipients: {}\nSubject: {}\nMessage: {}", recipients, subject, message); mailLibrary.sendEmail(recipients.toArray(new String[]{}), subject, message); @@ -811,4 +725,8 @@ public class EmailUtilsImpl implements EmailUtils { } return user; // It may be just "user". TODO - Wouldn't be better if it was null? } + + private String getSelectedGuidelines(String desiredCompatibility, RepositoryInterface repositoryInterface) { + return desiredCompatibility != null ? desiredCompatibility : repositoryInterface.getCompatibilityOverride(); + } } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/InterfaceComplianceService.java b/src/main/java/eu/dnetlib/repo/manager/service/InterfaceComplianceService.java index db72fea..2a59c31 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/InterfaceComplianceService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/InterfaceComplianceService.java @@ -6,7 +6,6 @@ import eu.dnetlib.repo.manager.exception.ResourceConflictException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.repository.InterfaceComplianceRequestsRepository; import eu.dnetlib.repo.manager.service.security.AuthorizationService; -import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; @@ -50,7 +49,7 @@ public class InterfaceComplianceService { List repositoryAdmins = authorizationService.getAdminsOfRepo(request.getRepositoryId()); emailUtils.sendUserUpdateInterfaceComplianceFailure(repositoryAdmins.stream().map(User::getEmail).collect(Collectors.toList()), repo, iFace, request); emailUtils.sendAdminUpdateInterfaceComplianceFailure(repo, iFace, request); - } catch (JSONException | ResourceNotFoundException e) { + } catch (ResourceNotFoundException e) { logger.error("Error", e); } } @@ -59,7 +58,7 @@ public class InterfaceComplianceService { private Set getOutdated() { Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DATE, -7); + calendar.add(Calendar.DATE, -7); // 7-days-old return this.repository.findAllBySubmissionDateBefore(calendar.getTime()); } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/MonitorServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/MonitorServiceImpl.java index 3f0de75..e5e9339 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/MonitorServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/MonitorServiceImpl.java @@ -52,7 +52,7 @@ public class MonitorServiceImpl implements MonitorService { String dateFrom, String dateTo, String validationStatus, - String includeJobsTotal) throws JSONException, ValidatorServiceException { + String includeJobsTotal) throws ValidatorServiceException, NumberFormatException { ///////////////////////////////////////////////////////////////////////////////////////// // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly // @@ -95,7 +95,6 @@ public class MonitorServiceImpl implements MonitorService { || (job.getValidationType().equals("U") && job.getContentJobStatus().equals("none") && job.getUsageJobStatus().equals("finished") && job.getUsageJobScore() <= 50)) { job.setValidationStatus("failed"); } - } } @@ -140,7 +139,6 @@ public class MonitorServiceImpl implements MonitorService { ///////////////////////////////////////////////////////////////////////////////////////// return retJobs; - } private int getJobsTotalNumberOfUser(String user, String jobType, String validationStatus) throws ValidatorServiceException { @@ -166,13 +164,12 @@ public class MonitorServiceImpl implements MonitorService { } @Override - public StoredJob getJobSummary(String jobId, - String groupBy) throws JSONException { + public StoredJob getJobSummary(String jobId, String groupBy) { logger.debug("Getting job summary with id : " + jobId); StoredJob job = null; try { job = getValidationService().getStoredJob(Integer.parseInt(jobId), groupBy); - } catch (ValidatorServiceException e) { + } catch (Exception e) { logger.error(e.getMessage(), e); } ///////////////////////////////////////////////////////////////////////////////////////// @@ -189,4 +186,5 @@ public class MonitorServiceImpl implements MonitorService { ///////////////////////////////////////////////////////////////////////////////////////// return job; } + } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/PiWikServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/PiWikServiceImpl.java index f5c9d56..667cf12 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/PiWikServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/PiWikServiceImpl.java @@ -226,12 +226,12 @@ public class PiWikServiceImpl implements PiWikService { @Override public Integer getTotal() { - return new JdbcTemplate(dataSource).queryForObject(GET_PIWIK_SITES_TOTAL, new Object[]{}, Integer.class); + return new JdbcTemplate(dataSource).queryForObject(GET_PIWIK_SITES_TOTAL, Integer.class, new Object[]{}); } @Override public Integer getValidated(boolean validated) { String finalizedQuery = GET_PIWIK_SITES_TOTAL + " where validated = ?"; - return new JdbcTemplate(dataSource).queryForObject(finalizedQuery, new Object[]{validated}, Integer.class); + return new JdbcTemplate(dataSource).queryForObject(finalizedQuery, Integer.class, validated); } } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java index 4235064..369f21d 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java @@ -1,12 +1,12 @@ package eu.dnetlib.repo.manager.service; +import eu.dnetlib.api.functionality.ValidatorServiceException; import eu.dnetlib.repo.manager.domain.*; import eu.dnetlib.repo.manager.exception.RepositoryServiceException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import org.json.JSONException; import org.springframework.security.core.Authentication; -import java.io.IOException; import java.util.List; import java.util.Map; @@ -16,45 +16,43 @@ public interface RepositoryService { // TODO: move this elsewhere Country[] getCountries(); - List getRepositories(List ids) throws JSONException; + List getRepositories(List ids); - List getRepositories(List ids, int page, int size) throws JSONException; + List getRepositories(List ids, int page, int size); List getRepositoriesSnippets(List ids) throws Exception; List getRepositoriesSnippets(List ids, int page, int size) throws Exception; - List getRepositoriesByCountry(String country, String mode, Boolean managed) throws JSONException, IOException; + List getRepositoriesByCountry(String country, String mode, Boolean managed); // TODO: remove? - List getRepositoriesOfUser(String page, String size) throws JSONException, IOException; + List getRepositoriesOfUser(String page, String size); // TODO: remove? - List getRepositoriesOfUser(String userEmail, - String page, - String size) throws JSONException, IOException; + List getRepositoriesOfUser(String userEmail, String page, String size); - List getRepositoriesSnippetsOfUser(String page, String size) throws Exception; + List getRepositoriesSnippetsOfUser(String page, String size); - List getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception; + List getRepositoriesSnippetsOfUser(String userEmail, String page, String size); - RepositorySnippet getRepositorySnippetById(String id) throws JSONException, ResourceNotFoundException; + RepositorySnippet getRepositorySnippetById(String id) throws ResourceNotFoundException; - Repository getRepositoryById(String id) throws JSONException, ResourceNotFoundException; + Repository getRepositoryById(String id) throws ResourceNotFoundException; List getRepositoriesByName(String name, String page, - String size) throws JSONException; + String size); List searchRegisteredRepositories(String country, String typology, String englishName, String officialName, String requestSortBy, String order, - int page, int pageSize) throws Exception; + int page, int pageSize); Integer getTotalRegisteredRepositories(); - List getRepositoryInterface(String id) throws JSONException; + List getRepositoryInterface(String id); - Repository addRepository(String datatype, Repository repository) throws Exception; + Repository addRepository(String datatype, Repository repository); void deleteRepositoryInterface(String id, String registeredBy); @@ -70,11 +68,9 @@ public interface RepositoryService { List getTimezones(); - Repository updateRepository(Repository repository, Authentication authentication) throws Exception; + Repository updateRepository(Repository repository, Authentication authentication); - List getUrlsOfUserRepos(String user_email, - String page, - String size); + List getUrlsOfUserRepos(String userEmail, String page, String size); Map getCompatibilityClasses(String mode); @@ -86,7 +82,7 @@ public interface RepositoryService { Map getListLatestUpdate(String mode); - RepositoryInterface updateRepositoryInterface(String repoId, String comment, RepositoryInterface repositoryInterface, String desiredCompatibilityLevel) throws Exception; + RepositoryInterface updateRepositoryInterface(String repoId, String comment, RepositoryInterface repositoryInterface, String desiredCompatibilityLevel) throws ResourceNotFoundException, ValidatorServiceException; void updateInterfaceCompliance(String repositoryId, String repositoryInterfaceId, String compliance); } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java index 4ce000e..00eeeda 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java @@ -4,24 +4,20 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import eu.dnetlib.api.functionality.ValidatorServiceException; import eu.dnetlib.domain.enabling.Vocabulary; import eu.dnetlib.domain.functionality.validator.JobForValidation; import eu.dnetlib.repo.manager.domain.*; -import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.User; import eu.dnetlib.repo.manager.exception.RepositoryServiceException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; -import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; import eu.dnetlib.repo.manager.service.security.AuthorizationService; import eu.dnetlib.repo.manager.service.security.RoleMappingService; import eu.dnetlib.repo.manager.utils.Converter; import eu.dnetlib.repo.manager.utils.DateUtils; import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader; import org.apache.commons.codec.digest.DigestUtils; -import org.json.JSONException; import org.mitre.openid.connect.model.OIDCAuthenticationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,13 +30,11 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import javax.annotation.PostConstruct; -import java.io.IOException; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -53,7 +47,6 @@ public class RepositoryServiceImpl implements RepositoryService { private final AuthorizationService authorizationService; private final RoleMappingService roleMappingService; private final AaiRegistryService registryCalls; - private final AuthoritiesUpdater authoritiesUpdater; private final RestTemplate restTemplate; private final ObjectMapper objectMapper; private final VocabularyLoader vocabularyLoader; @@ -88,11 +81,9 @@ public class RepositoryServiceImpl implements RepositoryService { public RepositoryServiceImpl(AuthorizationService authorizationService, RoleMappingService roleMappingService, AaiRegistryService registryCalls, - AuthoritiesUpdater authoritiesUpdater, VocabularyLoader vocabularyLoader, RestTemplate restTemplate, ObjectMapper objectMapper, -// Converter converter, @Lazy EmailUtils emailUtils, @Lazy ValidatorService validatorService, @Lazy PiWikService piWikService, @@ -100,7 +91,6 @@ public class RepositoryServiceImpl implements RepositoryService { this.authorizationService = authorizationService; this.roleMappingService = roleMappingService; this.registryCalls = registryCalls; - this.authoritiesUpdater = authoritiesUpdater; this.vocabularyLoader = vocabularyLoader; this.piWikService = piWikService; this.emailUtils = emailUtils; @@ -136,7 +126,7 @@ public class RepositoryServiceImpl implements RepositoryService { } httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE)); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); for (String vocName : vocabularyNames) { vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT)); @@ -161,7 +151,7 @@ public class RepositoryServiceImpl implements RepositoryService { // and the "requestFilter.setId(repoId)" should return only one result at a time, thus, // another way for paging must be implemented. @Override - public List getRepositories(List ids) throws JSONException { + public List getRepositories(List ids) { return getRepositories(ids, 0, 10); } @@ -190,7 +180,7 @@ public class RepositoryServiceImpl implements RepositoryService { // and the "requestFilter.setId(repoId)" should return only one result at a time, thus, // another way for paging must be implemented. @Override - public List getRepositoriesSnippets(List ids) throws Exception { + public List getRepositoriesSnippets(List ids) { return getRepositoriesSnippets(ids, 0, 10); } @@ -198,8 +188,8 @@ public class RepositoryServiceImpl implements RepositoryService { // and the "requestFilter.setId(repoId)" should return only one result at a time, thus, // another way for paging must be implemented. @Override - public List getRepositoriesSnippets(List ids, int page, int size) throws Exception { - List resultSet; + public List getRepositoriesSnippets(List ids, int page, int size) { + List resultSet = null; List datasourceDetailsList = new ArrayList<>(); // here page should be 0 @@ -208,7 +198,6 @@ public class RepositoryServiceImpl implements RepositoryService { for (String repoId : ids) { requestFilter.setId(repoId); - DatasourceResponse rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, DatasourceResponse.class); if (rs == null) { logger.error("The \"DatasourceResponse\" is null!"); @@ -217,15 +206,18 @@ public class RepositoryServiceImpl implements RepositoryService { } } - resultSet = objectMapper.readValue(objectMapper.writeValueAsString(datasourceDetailsList), - objectMapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)); - - if (logger.isDebugEnabled()) { - logger.debug("resultSet: {}", objectMapper.writeValueAsString(resultSet)); + try { + resultSet = objectMapper.readValue(objectMapper.writeValueAsString(datasourceDetailsList), + objectMapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)); + if (logger.isDebugEnabled()) { + logger.debug("resultSet: {}", objectMapper.writeValueAsString(resultSet)); + } + resultSet.parallelStream().forEach(repositorySnippet -> { + repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId())); + }); + } catch (JsonProcessingException e) { + logger.error("Error deserializing.", e); } - resultSet.parallelStream().forEach(repositorySnippet -> { - repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId())); - }); return resultSet; } @@ -233,7 +225,7 @@ public class RepositoryServiceImpl implements RepositoryService { @Override public List getRepositoriesByCountry(String country, String mode, - Boolean managed) throws IOException { + Boolean managed) { logger.debug("Getting repositories by country!"); int page = 0; int size = 100; @@ -256,7 +248,7 @@ public class RepositoryServiceImpl implements RepositoryService { } public List searchRegisteredRepositories(String country, String typology, String englishName, - String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception { + String officialName, String requestSortBy, String order, int page, int pageSize) { logger.debug("Searching registered repositories"); @@ -289,7 +281,7 @@ public class RepositoryServiceImpl implements RepositoryService { } @Override - public List getRepositoriesOfUser(String page, String size) throws JSONException { + public List getRepositoriesOfUser(String page, String size) { logger.debug("Retrieving repositories of authenticated user : {}", ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail()); Collection repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles()); @@ -297,19 +289,19 @@ public class RepositoryServiceImpl implements RepositoryService { } @Override - public List getRepositoriesOfUser(String userEmail, String page, String size) throws JSONException { + public List getRepositoriesOfUser(String userEmail, String page, String size) { logger.debug("Retrieving repositories of authenticated user : {}", userEmail); Collection repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRolesByEmail(userEmail)); return getRepositories(new ArrayList<>(repoIds)); } @Override - public List getRepositoriesSnippetsOfUser(String page, String size) throws Exception { + public List getRepositoriesSnippetsOfUser(String page, String size) { return getRepositoriesSnippetsOfUser(null, page, size); } @Override - public List getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception { + public List getRepositoriesSnippetsOfUser(String userEmail, String page, String size) { int from = Integer.parseInt(page) * Integer.parseInt(size); int to = from + Integer.parseInt(size); List repoIds = new ArrayList<>(); @@ -363,7 +355,7 @@ public class RepositoryServiceImpl implements RepositoryService { @Override public List getRepositoriesByName(String name, String page, - String size) throws JSONException { + String size) { logger.debug("Retrieving repositories with official name : {}", name); UriComponents uriComponents = searchDatasourceUri("0", "100"); @@ -402,7 +394,7 @@ public class RepositoryServiceImpl implements RepositoryService { } @Override - public Repository addRepository(String datatype, Repository repository) throws Exception { + public Repository addRepository(String datatype, Repository repository) { logger.debug("storing '{}' repository with id: {}", datatype, repository.getId()); @@ -433,32 +425,7 @@ public class RepositoryServiceImpl implements RepositoryService { this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication()); } - // TODO: move the following code elsewhere (creation and assignment of role to user) ?? - // Create new role - String newRoleName = roleMappingService.getRoleIdByRepoId(repository.getId()); - Role newRole = new Role(newRoleName, repository.getOfficialname()); - Integer couId = null; - try { - couId = registryCalls.createRole(newRole); - } catch (HttpClientErrorException e) { - couId = registryCalls.getCouId(newRoleName); - if (couId == null) { - logger.error(String.format("Could not create role '%s'", newRoleName), e); - } - } catch (Exception e) { - logger.error(String.format("Could not create role '%s'", newRoleName), e); - throw e; - } - - // Assign new role to the user that created it - Integer coPersonId = registryCalls.getCoPersonIdByIdentifier(); - if (couId != null) { - Integer role = registryCalls.getRoleId(coPersonId, couId); - registryCalls.assignMemberRole(coPersonId, couId, role); - - // Add role to current user authorities - authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(repository.getId())); - } + authorizationService.createAndAssignRoleToAuthenticatedUser(repository.getId(), repository.getOfficialname()); return repository; } @@ -486,7 +453,7 @@ public class RepositoryServiceImpl implements RepositoryService { } @Override - public Repository updateRepository(Repository repository, Authentication authentication) throws Exception { + public Repository updateRepository(Repository repository, Authentication authentication) { UriComponents uriComponents = UriComponentsBuilder .fromHttpUrl(baseAddress + "/ds/update/") .build() @@ -507,7 +474,7 @@ public class RepositoryServiceImpl implements RepositoryService { return repository; } - private void storeRepository(Repository repository, Authentication authentication) throws Exception { + private void storeRepository(Repository repository, Authentication authentication) { Date utilDate = new Date(); Timestamp date = new Timestamp(utilDate.getTime()); @@ -550,13 +517,12 @@ public class RepositoryServiceImpl implements RepositoryService { RepositoryInterface repositoryInterface, String desiredCompatibilityLevel) throws Exception { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - Repository e = this.getRepositoryById(repoId); - repositoryInterface = fillInterfaceFields(e, repositoryInterface, datatype); + Repository repo = this.getRepositoryById(repoId); + repositoryInterface = fillInterfaceFields(repo, repositoryInterface, datatype); UriComponents uriComponents = UriComponentsBuilder .fromHttpUrl(baseAddress + "/ds/api/add/") - .build() - .encode(); + .build().encode(); HttpEntity httpEntity = new HttpEntity<>(repositoryInterface, httpHeaders); restTemplate.postForObject(uriComponents.toUri(), httpEntity, String.class); @@ -564,15 +530,17 @@ public class RepositoryServiceImpl implements RepositoryService { // Explicitly update validation set (updating the interface does not allow updating the set value) this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet()); - emailUtils.sendAdminRegisterInterfaceEmail(e, comment, repositoryInterface, authentication); - emailUtils.sendUserRegisterInterfaceEmail(e, comment, repositoryInterface, authentication); + emailUtils.sendAdminRegisterInterfaceEmail(repo, comment, repositoryInterface, desiredCompatibilityLevel, authentication); + emailUtils.sendUserRegisterInterfaceEmail(repo, comment, repositoryInterface, desiredCompatibilityLevel, authentication); - if (desiredCompatibilityLevel != null && (repositoryInterface.getCompatibility() == null || !repositoryInterface.getCompatibility().equals(desiredCompatibilityLevel))) { + String prevCompatibilityLevel = repositoryInterface.getCompatibility(); + if ( (desiredCompatibilityLevel != null) + && ((prevCompatibilityLevel == null) || ! prevCompatibilityLevel.equals(desiredCompatibilityLevel))) { InterfaceComplianceRequest request = new InterfaceComplianceRequest(repoId, repositoryInterface.getId(), desiredCompatibilityLevel); interfaceComplianceService.create(request); } - submitInterfaceValidation(e, getAuthenticatedUser().getEmail(), repositoryInterface, false, repositoryInterface.getCompatibility()); + submitInterfaceValidation(repo, getAuthenticatedUser().getEmail(), repositoryInterface, false, desiredCompatibilityLevel); return repositoryInterface; } @@ -581,7 +549,7 @@ public class RepositoryServiceImpl implements RepositoryService { public RepositoryInterface updateRepositoryInterface(String repoId, String comment, RepositoryInterface repositoryInterface, - String desiredCompatibilityLevel) throws Exception { + String desiredCompatibilityLevel) throws ResourceNotFoundException, ValidatorServiceException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Repository repository = this.getRepositoryById(repoId); if (repositoryInterface.getId() != null) { @@ -593,8 +561,8 @@ public class RepositoryServiceImpl implements RepositoryService { this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet()); - emailUtils.sendAdminUpdateInterfaceEmail(repository, comment, repositoryInterface, authentication); - emailUtils.sendUserUpdateInterfaceEmail(repository, comment, repositoryInterface, authentication); + emailUtils.sendAdminUpdateInterfaceEmail(repository, comment, repositoryInterface, desiredCompatibilityLevel, authentication); + emailUtils.sendUserUpdateInterfaceEmail(repository, comment, repositoryInterface, desiredCompatibilityLevel, authentication); if (desiredCompatibilityLevel != null && (repositoryInterface.getCompatibility() == null || !repositoryInterface.getCompatibility().equals(desiredCompatibilityLevel))) { InterfaceComplianceRequest request = new InterfaceComplianceRequest(repoId, repositoryInterface.getId(), desiredCompatibilityLevel); @@ -704,8 +672,8 @@ public class RepositoryServiceImpl implements RepositoryService { RequestFilter requestFilter = new RequestFilter(); requestFilter.setRegisteredby(userEmail); - Object result = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String[].class); - return (result != null) ? Collections.singletonList(result.toString()) : null; + String[] result = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String[].class); + return (result != null) ? Arrays.asList(result) : null; } private Vocabulary getVocabulary(String vocName) { @@ -721,7 +689,7 @@ public class RepositoryServiceImpl implements RepositoryService { public Map getCompatibilityClasses(String mode) { logger.debug("Getting compatibility classes for mode: {}", mode); - Map retMap = new HashMap(); + Map retMap = new HashMap<>(); Map compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap(); boolean foundData = false; @@ -756,7 +724,7 @@ public class RepositoryServiceImpl implements RepositoryService { logger.debug("Getting datasource classes for mode: {}", mode); - Map retMap = new HashMap(); + Map retMap = new HashMap<>(); // TODO: refactor (remove?) for (Map.Entry entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) { @@ -850,7 +818,7 @@ public class RepositoryServiceImpl implements RepositoryService { return Collections.singletonMap("lastCollectionDate", DateUtils.toString(getRepositoryInterface("openaire____::" + mode).get(0).getLastCollectionDate())); } - private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) throws Exception { + private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) { UriComponents uriComponents = UriComponentsBuilder .fromHttpUrl(baseAddress + "/ds/api/oaiset") .queryParam("dsId", repositoryId) @@ -994,22 +962,19 @@ public class RepositoryServiceImpl implements RepositoryService { } private List getRoleIdsFromUserRoles(String userEmail) { - Integer coPersonId = registryCalls.getCoPersonIdByEmail(userEmail); + List coPersonId = registryCalls.getCoPersonIdsByEmail(userEmail); JsonArray roles; ArrayList roleIds = new ArrayList<>(); ArrayList couIds = new ArrayList<>(); if (coPersonId != null) { roles = registryCalls.getRolesWithStatus(coPersonId, AaiRegistryService.RoleStatus.ACTIVE); for (JsonElement role : roles) { - JsonObject object = role.getAsJsonObject(); - if (object.get("CouId") == null) { - continue; - } - couIds.add(object.get("CouId").getAsInt()); + JsonElement couId = role.getAsJsonObject().get("CouId"); + if (couId != null) + couIds.add(couId.getAsInt()); } roleIds.addAll(registryCalls.getCouNames(couIds).values()); - } return roleIds; } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java index 002c867..ba41dda 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java @@ -95,22 +95,20 @@ public class SushiliteServiceImpl implements SushiliteService { Customer customer = reportResponseWrapper.getReportResponse().getReportWrapper().getReport().getCustomer(); List allReportItems = customer.getReportItems(); - if ( allReportItems != null) { + if ( allReportItems != null ) { try { int totalItems = allReportItems.size(); int size = Integer.parseInt(pageSize); int offset = (Integer.parseInt(page) * size); - - if (offset < totalItems ) { + if ( offset < totalItems ) { int upperIndex = (offset + size); - if (upperIndex > totalItems) { + if ( upperIndex > totalItems ) { upperIndex = totalItems; } requestedItemList = allReportItems.subList(offset, upperIndex); } } catch (NumberFormatException e) { - logger.debug("Exception on getReportResults - trying to cast strings to integers", e); - //emailUtils.reportException(e); + logger.error("Exception on getReportResults - trying to cast strings to integers", e); throw e; } } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/ValidatorServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/ValidatorServiceImpl.java index 908090c..7619147 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/ValidatorServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/ValidatorServiceImpl.java @@ -185,7 +185,7 @@ public class ValidatorServiceImpl implements ValidatorService { } } } - if (ruleSet != null){ + if (ruleSet != null) { for (int ruleId : job.getRules()) { if (ruleSet.getContentRulesIds().contains(ruleId)) contentRules.add(ruleId); @@ -210,16 +210,13 @@ public class ValidatorServiceImpl implements ValidatorService { @Override public List getSetsOfRepository(String url) { logger.debug("Getting sets of repository with url : {}", url); - List sets = null; - try { sets = OaiTools.getSetsOfRepo(url); } catch (Exception e) { logger.error("Exception on getSetsOfRepository", e); } - - return sets; + return sets; // It may be null. } @Override @@ -239,13 +236,16 @@ public class ValidatorServiceImpl implements ValidatorService { RuleSet ruleSet = null; try { for (List ruleSets : this.rulesetMap.values()) { - for (RuleSet rSet : ruleSets) - if (rSet.getGuidelinesAcronym().equals(acronym)) { + for ( RuleSet rSet : ruleSets ) { + if ( rSet.getGuidelinesAcronym().equals(acronym) ) { ruleSet = rSet; break; } + } + if ( ruleSet != null ) + break; } - return ruleSet; + return ruleSet; // It may be null. } catch (Exception e) { logger.error("Error getting ruleset", e); return null; @@ -310,10 +310,11 @@ public class ValidatorServiceImpl implements ValidatorService { @Override public void onComplete(String repoId, String interfaceId, String jobId, String issuerEmail, boolean isUpdate, boolean isSuccess, int scoreUsage, int scoreContent) throws Exception { - emailUtils.sendUponJobCompletion(repoId,interfaceId,scoreUsage,scoreContent,isSuccess,isUpdate,issuerEmail, jobId); InterfaceComplianceRequestId requestId = InterfaceComplianceRequestId.of(repoId, interfaceId); Optional request = interfaceComplianceService.getById(requestId); + String compatibility = null; if (request.isPresent()) { + compatibility = request.get().getDesiredCompatibilityLevel(); logger.info("Changing compatibility level. Request: {}", request); if (scoreContent > 50) { @@ -321,6 +322,7 @@ public class ValidatorServiceImpl implements ValidatorService { } interfaceComplianceService.delete(requestId); } + emailUtils.sendUponJobCompletion(repoId,interfaceId,compatibility,scoreUsage,scoreContent,isSuccess,isUpdate,issuerEmail, jobId); } } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java index 6fe4888..6cb453f 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java @@ -11,28 +11,36 @@ import java.util.Map; public interface AaiRegistryService { /** - * 1.1 Get CoPersonId by authenticated user's Email + * 1.1 Get CoPersonId List by authenticated user's Email * * @return */ - Integer getCoPersonIdByEmail(); + List getCoPersonIdsByEmail(); /** - * 1.2 Get CoPersonId by Email - * - * @param email - * @return - */ - Integer getCoPersonIdByEmail(String email); - - /** - * 1. Get CoPersonId List by Email + * 1.2 Get CoPersonId List by Email * * @param email * @return */ List getCoPersonIdsByEmail(String email); + /** + * 1.3 Get a list of User Identifiers by Email + * + * @param email + * @return + */ + List getUserIdentifiersByEmail(String email); + + /** + * 1.3 Get a list of User Identifiers by Email + * + * @param coPersonId + * @return + */ + List getUserIdentifiersByCoPersonId(Integer coPersonId); + /** * 2. Get CoPersonId by AAI identifier * @@ -97,6 +105,14 @@ public interface AaiRegistryService { */ JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status); + /** + * 5.3 Get User non admin active roles + * + * @param coPersonIds + * @return + */ + JsonArray getRolesWithStatus(List coPersonIds, RoleStatus status); + /** * 6. Get Role id of User base on couId. * @@ -188,9 +204,8 @@ public interface AaiRegistryService { * * @param coPersonId * @param couId - * @param id */ - void assignMemberRole(Integer coPersonId, Integer couId, Integer id); + void assignMemberRole(Integer coPersonId, Integer couId); /** * 16. Remove a member role from a User diff --git a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java index dc7c5f1..c7d4743 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java @@ -6,8 +6,8 @@ import com.google.gson.JsonObject; import com.nimbusds.jose.util.StandardCharset; import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.User; +import eu.dnetlib.repo.manager.service.aai.registry.utils.HttpUtils; import eu.dnetlib.repo.manager.service.aai.registry.utils.RegistryUtils; -import eu.dnetlib.repo.manager.utils.HttpUtils; import org.mitre.openid.connect.model.OIDCAuthenticationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -16,29 +16,24 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; -import javax.validation.constraints.NotNull; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Service public class RegistryCalls implements AaiRegistryService { private static final Logger logger = LoggerFactory.getLogger(RegistryCalls.class); - private final String coid; public final HttpUtils httpUtils; public final RegistryUtils jsonUtils; + private final String coid; @Autowired - RegistryCalls(@Value("${services.provide.aai.registry.coid:2}") String coid, - HttpUtils httpUtils, RegistryUtils registryUtils) { - this.coid = coid; + RegistryCalls(HttpUtils httpUtils, RegistryUtils registryUtils, @Value("${services.provide.aai.registry.coid}") String coid) { this.httpUtils = httpUtils; this.jsonUtils = registryUtils; + this.coid = coid; } private String mapType(String type, boolean communityMap) { @@ -51,42 +46,51 @@ public class RegistryCalls implements AaiRegistryService { } @Override - public Integer getCoPersonIdByEmail() { + public List getUserIdentifiersByEmail(String email) { + List ids = new ArrayList<>(); + for (Integer coPersonId : getCoPersonIdsByEmail(email)) { + ids.addAll(getUserIdentifiersByCoPersonId(coPersonId)); + } + return ids; + } + + @Override + public List getUserIdentifiersByCoPersonId(Integer coPersonId) { + List ids = new ArrayList<>(); + Map params = new HashMap<>(); + params.put("copersonid", coPersonId.toString()); + + JsonElement response = httpUtils.get("identifiers.json", params); + if (response != null) { + JsonArray infos = response.getAsJsonObject().get("Identifiers").getAsJsonArray(); + infos.forEach(info -> { + JsonObject jsonInfo = info.getAsJsonObject(); + if (!jsonInfo.get("Deleted").getAsBoolean()) { + ids.add(jsonInfo.get("Identifier").getAsString()); + } + }); + } + return ids; + } + + @Override + public List getCoPersonIdsByEmail() { try { OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); String email = authentication.getUserInfo().getEmail(); - Map params = new HashMap<>(); - params.put("coid", coid); - params.put("mail", email); - JsonElement response = httpUtils.get("co_people.json", params); - return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; + return getCoPersonIdsByEmail(email); } catch (Exception e) { logger.error("Get User info: An error occurred ", e); return null; } } - @Override - public Integer getCoPersonIdByEmail(String email) { - Map params = new HashMap<>(); - params.put("coid", coid); - params.put("mail", email); - JsonElement response = httpUtils.get("co_people.json", params); - if (response != null) { - JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray(); - if (coPeople.size() > 0) { - return coPeople.get(0).getAsJsonObject().get("Id").getAsInt(); - } - } - return null; - } - @Override public List getCoPersonIdsByEmail(String email) { List coPersonIds = new ArrayList<>(); Map params = new HashMap<>(); - params.put("coid", coid); params.put("mail", email); + params.put("coid", coid); JsonElement response = httpUtils.get("co_people.json", params); if (response != null) { JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray(); @@ -111,8 +115,8 @@ public class RegistryCalls implements AaiRegistryService { public Integer getCoPersonIdByIdentifier(String sub) { Map params = new HashMap<>(); - params.put("coid", coid); params.put("search.identifier", sub); + params.put("coid", coid); JsonElement response = httpUtils.get("co_people.json", params); return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; } @@ -120,7 +124,6 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getCous(String name) { Map params = new HashMap<>(); - params.put("coid", coid); if (name != null) { try { params.put("name", URLEncoder.encode(name, StandardCharset.UTF_8.name()).toLowerCase()); @@ -169,10 +172,13 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status) { - JsonArray roles = getRoles(coPersonId); - if (roles == null) { - roles = new JsonArray(); - } + return getRolesWithStatus(Collections.singletonList(coPersonId), status); + } + + @Override + public JsonArray getRolesWithStatus(List coPersonIds, RoleStatus status) { + JsonArray roles = new JsonArray(); + coPersonIds.parallelStream().forEach(coPersonId -> roles.addAll(getRoles(coPersonId))); JsonArray activeRoles = new JsonArray(); if (status != null) { for (JsonElement role : roles) { @@ -181,7 +187,6 @@ public class RegistryCalls implements AaiRegistryService { } } } - assert activeRoles != null; return activeRoles; } @@ -225,7 +230,6 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getCouGroups(Integer couId) { Map params = new HashMap<>(); - params.put("coid", coid); params.put("couid", couId.toString()); JsonElement response = httpUtils.get("co_groups.json", params); return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray(); @@ -356,18 +360,15 @@ public class RegistryCalls implements AaiRegistryService { } @Override - public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) { - if (id != null) { - httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Active")); - } else { - httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active")); - } + public void assignMemberRole(Integer coPersonId, Integer couId) { + httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active")); } + @Override public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) { if (id != null) { - httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted")); + httpUtils.put("co_person_roles/" + id + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted")); } } @@ -392,7 +393,7 @@ public class RegistryCalls implements AaiRegistryService { params.put("copersonid", coPersonId.toString()); JsonElement response = httpUtils.get("names.json", params); JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null; - if ( info != null ) { + if (info != null) { JsonObject jsonInfo = info.getAsJsonObject(); return jsonInfo.get("Given").getAsString() + " " + jsonInfo.get("Family").getAsString(); } else @@ -427,7 +428,7 @@ public class RegistryCalls implements AaiRegistryService { } } if (id != null) { - httpUtils.delete("co_group_members/" + id.toString() + ".json"); + httpUtils.delete("co_group_members/" + id + ".json"); } } diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/HttpUtils.java similarity index 77% rename from src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java rename to src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/HttpUtils.java index 957da55..b294717 100644 --- a/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/HttpUtils.java @@ -1,4 +1,4 @@ -package eu.dnetlib.repo.manager.utils; +package eu.dnetlib.repo.manager.service.aai.registry.utils; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -9,9 +9,13 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; import java.nio.charset.StandardCharsets; +import java.util.Collections; import java.util.Map; @Component @@ -48,7 +52,7 @@ public class HttpUtils { public JsonElement get(String path, Map params) { RestTemplate restTemplate = new RestTemplate(); - String url = registryUrl + path + ((params != null) ? createParams(params) : null); + String url = createUrl(registryUrl + path, params); ResponseEntity responseEntity = restTemplate.exchange (url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class); return getResponseEntityAsJsonElement(responseEntity); @@ -57,23 +61,18 @@ public class HttpUtils { public JsonElement delete(String path) { RestTemplate restTemplate = new RestTemplate(); String url = registryUrl + path; - ResponseEntity responseEntity = restTemplate.exchange - (url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(user, password)), String.class); + ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(user, password)), String.class); return getResponseEntityAsJsonElement(responseEntity); } - - private String createParams(Map params) { - StringBuilder ret = new StringBuilder("?"); - int count = 0; - for (Map.Entry param : params.entrySet()) { - ret.append(param.getKey()).append("=").append(param.getValue()); - count++; - if (count != params.entrySet().size()) { - ret.append("&"); - } - } - return ret.toString(); + private String createUrl(String baseAddress, Map params) { + LinkedMultiValueMap multiValueMap = new LinkedMultiValueMap<>(); + params.forEach((k, v) -> multiValueMap.put(k, Collections.singletonList(v))); + UriComponents uriComponents = UriComponentsBuilder + .fromHttpUrl(baseAddress) + .queryParams(multiValueMap) + .build().encode(); + return uriComponents.toString(); } private HttpHeaders createHeaders(String username, String password) { @@ -87,12 +86,13 @@ public class HttpUtils { private JsonElement getResponseEntityAsJsonElement(ResponseEntity responseEntity) { - if ( responseEntity == null ) + if (responseEntity == null) return null; String responseBody = responseEntity.getBody(); - if ( responseBody != null ) { - logger.debug(responseBody); + if (responseBody != null) { + logger.trace(responseBody); + try { return new JsonParser().parse(responseBody); } catch (Exception e) { diff --git a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java index 7fe74f1..24576b0 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java @@ -6,6 +6,8 @@ import eu.dnetlib.repo.manager.domain.dto.Role; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import java.util.Date; + @Component public class RegistryUtils { @@ -29,8 +31,11 @@ public class RegistryUtils { coPersonRole.addProperty("Title", ""); coPersonRole.addProperty("O", "Openaire"); coPersonRole.addProperty("Status", status); - coPersonRole.addProperty("ValidFrom", ""); - coPersonRole.addProperty("ValidThrough", ""); + if(status.equals("Active")) { + coPersonRole.addProperty("ValidFrom", new Date().toString()); + } else { + coPersonRole.addProperty("ValidThrough", new Date().toString()); + } coPersonRoles.add(coPersonRole); role.addProperty("RequestType", "CoPersonRoles"); role.addProperty("Version", version); diff --git a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java index 3696321..8c8a665 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java @@ -43,7 +43,7 @@ public interface AuthorizationService { * @return * @throws ResourceNotFoundException */ - boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException; + void addAdmin(String resourceId, String email) throws ResourceNotFoundException; /** * Remove user from resource admins. @@ -53,12 +53,20 @@ public interface AuthorizationService { * @return * @throws ResourceNotFoundException */ - boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException; + void removeAdmin(String resourceId, String email) throws ResourceNotFoundException; + + /** + * Creates a role based on the resourceId and assigns it to the current user. + * + * @param resourceId usually the repository Id. + * @param roleDescription usually the repository official name. + */ + void createAndAssignRoleToAuthenticatedUser(String resourceId, String roleDescription); /** * Returns the roles of the authenticated user. - * + * * @return */ Collection getUserRoles(); diff --git a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java index 4ce5e70..e1f66f9 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java @@ -1,6 +1,7 @@ package eu.dnetlib.repo.manager.service.security; import com.google.gson.JsonElement; +import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.User; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; @@ -11,6 +12,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import java.util.ArrayList; import java.util.Collection; @@ -79,49 +81,74 @@ public class AuthorizationServiceImpl implements AuthorizationService { @Override - public boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException { - Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); - if (coPersonId != null) { - String role = roleMappingService.getRoleIdByRepoId(resourceId); - Integer couId = aaiRegistryService.getCouId(role); - if (couId != null) { - Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); - aaiRegistryService.assignMemberRole(coPersonId, couId, roleId); + public void addAdmin(String resourceId, String email) throws ResourceNotFoundException { + String role = roleMappingService.getRoleIdByRepoId(resourceId); + Integer couId = aaiRegistryService.getCouId(role); + if (couId == null) { + throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + } + List coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email); + for (Integer coPersonId : coPersonIds) { + assert coPersonId != null; + aaiRegistryService.assignMemberRole(coPersonId, couId); - // Add role to user current authorities - authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); - - return true; - } else { - throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + // Add role to user current authorities + for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { + authoritiesUpdater.addRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); } - } else { - throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email); } } @Override - public boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException { - Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); - if (coPersonId != null) { - String role = roleMappingService.getRoleIdByRepoId(resourceId); - Integer couId = aaiRegistryService.getCouId(role); - Integer roleId = null; - if (couId != null) { - roleId = aaiRegistryService.getRoleId(coPersonId, couId); - } - if (couId != null && roleId != null) { + public void removeAdmin(String resourceId, String email) throws ResourceNotFoundException { + String role = roleMappingService.getRoleIdByRepoId(resourceId); + Integer couId = aaiRegistryService.getCouId(role); + if (couId == null) { + throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + } + List coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email); + for (Integer coPersonId : coPersonIds) { + assert coPersonId != null; + Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); + if (roleId != null) { aaiRegistryService.removeMemberRole(coPersonId, couId, roleId); // Remove role from user current authorities - authoritiesUpdater.removeRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); - - return true; + for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { + authoritiesUpdater.removeRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); + } } else { - throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + logger.error("Cannot find RoleId for role: {}", role); } - } else { - throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email); + } + } + + @Override + public void createAndAssignRoleToAuthenticatedUser(String resourceId, String roleDescription) { + // Create new role + String newRoleName = roleMappingService.getRoleIdByRepoId(resourceId); + Role newRole = new Role(newRoleName, roleDescription); + + Integer couId; + try { + couId = aaiRegistryService.createRole(newRole); + } catch (HttpClientErrorException e) { + couId = aaiRegistryService.getCouId(newRoleName); + if (couId == null) { + logger.error(String.format("Could not create role '%s'", newRoleName), e); + } + } catch (Exception e) { + logger.error(String.format("Could not create role '%s'", newRoleName), e); + throw e; + } + + // Assign new role to the current authenticated user + Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); + if (couId != null) { + aaiRegistryService.assignMemberRole(coPersonId, couId); + + // Add role to current user authorities + authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(resourceId)); } } @@ -131,17 +158,17 @@ public class AuthorizationServiceImpl implements AuthorizationService { UserInfo userInfo = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo(); roles = getUserRolesByEmail(userInfo.getEmail()); - if (logger.isDebugEnabled()) { - logger.debug("User Roles: {}", String.join(",", roles)); + if (logger.isTraceEnabled()) { + logger.trace("User Roles: {}", String.join(",", roles)); } return roles; } @Override public Collection getUserRolesByEmail(String email) { - int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); + List coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email); List list = new ArrayList<>(); - for (JsonElement element : aaiRegistryService.getRolesWithStatus(coPersonId, AaiRegistryService.RoleStatus.ACTIVE)) { + for (JsonElement element : aaiRegistryService.getRolesWithStatus(coPersonIds, AaiRegistryService.RoleStatus.ACTIVE)) { if (element.getAsJsonObject().get("CouId") != null) { list.add(element.getAsJsonObject().get("CouId").getAsInt()); } diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/Converter.java b/src/main/java/eu/dnetlib/repo/manager/utils/Converter.java index 3dccc4e..b250602 100644 --- a/src/main/java/eu/dnetlib/repo/manager/utils/Converter.java +++ b/src/main/java/eu/dnetlib/repo/manager/utils/Converter.java @@ -6,7 +6,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; -import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; @@ -22,13 +21,11 @@ public class Converter { public static List readFile(String filename) { String line; List list = new ArrayList<>(); - try { - InputStream in = Converter.class.getResourceAsStream("/eu/**/" + filename); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); // It may throw an NPE. + try ( BufferedReader br = new BufferedReader(new InputStreamReader(Objects.requireNonNull(Converter.class.getResourceAsStream("/eu/**/" + filename)))) ) + { while ((line = br.readLine()) != null) { list.add(line.trim()); } - br.close(); } catch (Exception e) { logger.error("Error opening file!", e); } diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/DatasourceManagerClient.java b/src/main/java/eu/dnetlib/repo/manager/utils/DatasourceManagerClient.java deleted file mode 100644 index 118dd05..0000000 --- a/src/main/java/eu/dnetlib/repo/manager/utils/DatasourceManagerClient.java +++ /dev/null @@ -1,5 +0,0 @@ -package eu.dnetlib.repo.manager.utils; - -public class DatasourceManagerClient { - // -} diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/OaiTools.java b/src/main/java/eu/dnetlib/repo/manager/utils/OaiTools.java index 1e030e6..d9c7008 100644 --- a/src/main/java/eu/dnetlib/repo/manager/utils/OaiTools.java +++ b/src/main/java/eu/dnetlib/repo/manager/utils/OaiTools.java @@ -25,7 +25,7 @@ public class OaiTools { disableSslVerification(); } - private static Logger logger = LoggerFactory.getLogger(OaiTools.class); + private static final Logger logger = LoggerFactory.getLogger(OaiTools.class); public static List getSetsOfRepo(String baseUrl) throws Exception { try { @@ -36,8 +36,8 @@ public class OaiTools { List sets = new ArrayList<>(setList.asList()); while (token != null) { setList = harvester.listSets(token); - token = setList.getResumptionToken(); sets.addAll(setList.asList()); + token = setList.getResumptionToken(); } List ret = new ArrayList(); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 02c21d1..409f18f 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -15,11 +15,11 @@ spring: services: provide: - dev-machine: 88.197.53.71 + dev-machine: 88.197.53.71 # VM-71 aai: baseURL: https://aai.openaire.eu oidc: - domain: .openaire.eu + domain: .openaire.eu # use empty value for local, otherwise: ".openaire.eu" id: XX issuer: ${services.provide.aai.baseURL}/oidc/ redirectURL: http://localhost:${server.port}${server.servlet.context-path}/openid_connect_login @@ -37,13 +37,13 @@ services: broker: api: api/ openaire: openaireBroker - port: 8080 - url: https://broker1-dev-dnet.d4science.org + port: 443 + url: https://beta.broker.openaire.eu clients: dsm: https://dev-openaire.d4science.org/openaire search: https://beta.services.openaire.eu/search/v2/api usageEvents: http://beta.lbs.openaire.eu:8080/ajax/summary - usagestats: https://services.openaire.eu/usagestats + usagestats: https://beta.services.openaire.eu/usagestats db: driverClassName: org.postgresql.Driver password: dnetPwd diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml index a98fd99..2e6c355 100644 --- a/src/main/resources/log4j2.xml +++ b/src/main/resources/log4j2.xml @@ -9,7 +9,13 @@ - + + + + + + + diff --git a/src/test/java/eu/dnetlib/repo/manager/integration/metrics/PrometheusTest.java b/src/test/java/eu/dnetlib/repo/manager/integration/metrics/PrometheusTest.java index 897aaea..381558d 100644 --- a/src/test/java/eu/dnetlib/repo/manager/integration/metrics/PrometheusTest.java +++ b/src/test/java/eu/dnetlib/repo/manager/integration/metrics/PrometheusTest.java @@ -11,6 +11,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; @@ -51,7 +52,7 @@ public class PrometheusTest { @Test public void testPiwikMetrics() { - assertTrue(piWikService.getValidated(false).equals(TOTAL - VALIDATED)); + assertEquals((long) piWikService.getValidated(false), (TOTAL - VALIDATED)); String report = prometheusController.getPiwikMetrics(); assertTrue(report.contains("provide_repositories_registered_total " + TOTAL)); assertTrue(report.contains("provide_usagecounts_repositories_registered_total " + TOTAL)); diff --git a/src/test/java/eu/dnetlib/repo/manager/integration/service/InterfaceComplianceRequestTests.java b/src/test/java/eu/dnetlib/repo/manager/integration/service/InterfaceComplianceRequestTests.java index 8a19e7d..a84ccb6 100644 --- a/src/test/java/eu/dnetlib/repo/manager/integration/service/InterfaceComplianceRequestTests.java +++ b/src/test/java/eu/dnetlib/repo/manager/integration/service/InterfaceComplianceRequestTests.java @@ -40,17 +40,17 @@ class InterfaceComplianceRequestTests { } private InterfaceComplianceRequestId createRequestId() { - InterfaceComplianceRequestId id = new InterfaceComplianceRequestId(); - id.setRepositoryId("repository"); - id.setInterfaceId("interface"); - return id; + InterfaceComplianceRequestId requestId = new InterfaceComplianceRequestId(); + requestId.setRepositoryId("repository"); + requestId.setInterfaceId("interface"); + return requestId; } private InterfaceComplianceRequest createRequest(String compatibilityLevel) { InterfaceComplianceRequest request = new InterfaceComplianceRequest(); - InterfaceComplianceRequestId id = createRequestId(); - request.setRepositoryId(id.getRepositoryId()); - request.setInterfaceId(id.getInterfaceId()); + InterfaceComplianceRequestId requestId = createRequestId(); + request.setRepositoryId(requestId.getRepositoryId()); + request.setInterfaceId(requestId.getInterfaceId()); request.setDesiredCompatibilityLevel(compatibilityLevel); request.setSubmissionDate(new Date()); return request;