diff --git a/Dockerfile b/Dockerfile index 2bc1b7d..b88fe6a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,10 @@ -FROM tomcat:7.0.90-jre8 +#FROM tomcat:7.0.90-jre8 +FROM tomcat:8.5.71-jre8-openjdk-bullseye MAINTAINER "pkanakakis@di.uoa.gr" RUN ["rm", "-fr", "/usr/local/tomcat/webapps/ROOT"] COPY ./target/uoa-repository-manager-service.war /usr/local/tomcat/webapps/uoa-repository-manager-service.war #COPY src/main/resources/dnet-override-new.properties /usr/local/tomcat/lib/dnet-override.properties -COPY src/main/resources/application.properties /usr/local/tomcat/lib/dnet-override.properties +COPY validator.env /usr/local/tomcat/lib/dnet-override.properties #COPY src/main/resources/application.properties /usr/local/tomcat/lib/application.properties #COPY src/main/resources/email-texts.properties /usr/local/tomcat/lib/email-texts.properties VOLUME /var/log/uoa-repository-manager-service:/var/log/uoa-repository-manager-service/ diff --git a/pom.xml b/pom.xml index a257c4e..b827685 100644 --- a/pom.xml +++ b/pom.xml @@ -4,48 +4,139 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - eu.dnetlib - dnet45-parent - 1.0.0-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 2.5.4 + 4.0.0 + eu.dnetlib uoa-repository-manager-service 1.0.0-SNAPSHOT war + + 2.5.4 + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-log4j2 - org.hibernate - hibernate-validator-annotation-processor - 4.1.0.Final + org.springframework.boot + spring-boot-starter-web - log4j - log4j - ${log4j.version} + org.springframework.boot + spring-boot-starter-data-jdbc + + + org.springframework.boot + spring-boot-actuator-autoconfigure + + + org.springframework.boot + spring-boot-starter-tomcat + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-validation + + + + + + eu.dnetlib + uoa-clients + [2.0.0-SNAPSHOT, 3.0.0) + + + log4j + log4j + + + + javax.servlet + javax.servlet-api + + + com.google.gwt + gwt-user + + eu.dnetlib dnet-runtime - [1.0.0-SNAPSHOT, 2.0.0) - - - org.apache.geronimo.specs - geronimo-javamail_1.4_spec - + 1.0.2-SNAPSHOT + + + log4j + log4j + - + eu.dnetlib - uoa-utils + uoa-hcm [2.0.0-SNAPSHOT, 3.0.0) + + + log4j + log4j + + + + + + + + + + + + + + + + + eu.dnetlib uoa-domain @@ -55,6 +146,10 @@ cglib cglib + + log4j + log4j + @@ -79,22 +174,6 @@ 2.2 - - eu.dnetlib - uoa-commons - [2.0.0-SNAPSHOT, 3.0.0) - - - eu.dnetlib - uoa-clients - [2.0.0-SNAPSHOT, 3.0.0) - - - eu.dnetlib - uoa-hcm - [2.0.0-SNAPSHOT, 3.0.0) - - commons-io commons-io @@ -112,36 +191,37 @@ 2.7.2 - - xerces - xercesImpl - 2.11.0 - + + + + + + + + + + + - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-jdbc - ${spring.version} - + + + + + com.sun.jersey @@ -185,11 +265,11 @@ - - org.apache.tomcat - tomcat-catalina - 9.0.22 - + + + + + commons-fileupload @@ -211,15 +291,27 @@ org.springframework.session spring-session-data-redis - 1.3.1.RELEASE + + + redis.clients jedis - 2.9.0 - + ${jedis.version} + + + +org.apache.commons +commons-pool2 + com.google.code.gson gson @@ -231,18 +323,18 @@ cors-filter 2.5 - com.netflix.hystrix hystrix-core 1.5.18 - + + javax.xml.ws @@ -297,21 +389,21 @@ - - org.springframework.boot - spring-boot-actuator - 1.3.5.RELEASE - + + + + + - - io.micrometer - micrometer-core - 1.7.2 - + + + + + io.micrometer micrometer-registry-prometheus @@ -322,9 +414,23 @@ + + + + + org.springframework.session + spring-session-bom + 2021.0.2 + pom + import + + + + ${project.build.directory}/${project.build.finalName}/WEB-INF/classes + + + org.springframework.boot + spring-boot-maven-plugin + + cz.habarta.typescript-generator typescript-generator-maven-plugin @@ -377,5 +488,30 @@ - + + + dnet-deps + dnet-dependencies + https://maven.d4science.org/nexus/content/repositories/dnet-deps + default + + + dnet45-snapshots + D-Net 45 Snapshots + https://maven.d4science.org/nexus/content/repositories/dnet45-snapshots + default + + true + + + + dnet45-releases + D-Net 45 Releases + https://maven.d4science.org/nexus/content/repositories/dnet45-releases + default + + true + + + diff --git a/src/main/java/eu/dnetlib/repo/manager/Application.java b/src/main/java/eu/dnetlib/repo/manager/Application.java new file mode 100644 index 0000000..0eeb9c8 --- /dev/null +++ b/src/main/java/eu/dnetlib/repo/manager/Application.java @@ -0,0 +1,12 @@ +package eu.dnetlib.repo.manager; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/src/main/java/eu/dnetlib/repo/manager/config/ActuatorConfig.java b/src/main/java/eu/dnetlib/repo/manager/config/ActuatorConfig.java deleted file mode 100644 index 875b2a1..0000000 --- a/src/main/java/eu/dnetlib/repo/manager/config/ActuatorConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package eu.dnetlib.repo.manager.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration; -import org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration; -import org.springframework.boot.actuate.autoconfigure.PublicMetricsAutoConfiguration; -import org.springframework.boot.actuate.endpoint.MetricsEndpoint; -import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; -import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter; -import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -import java.util.Collection; - -@Configuration -@EnableWebMvc -@Import({ - EndpointAutoConfiguration.class, - PublicMetricsAutoConfiguration.class, -// HealthIndicatorAutoConfiguration.class -}) - -public class ActuatorConfig { // TODO: remove this with migration to Spring Boot 2 - - @Bean - @Autowired - public EndpointHandlerMapping endpointHandlerMapping(Collection endpoints) { - return new EndpointHandlerMapping(endpoints); - } - - @Bean - @Autowired - public EndpointMvcAdapter metricsEndPoint(MetricsEndpoint delegate) { - return new EndpointMvcAdapter(delegate); - } -} diff --git a/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java b/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java new file mode 100644 index 0000000..9ffa643 --- /dev/null +++ b/src/main/java/eu/dnetlib/repo/manager/config/AsyncConfiguration.java @@ -0,0 +1,27 @@ +package eu.dnetlib.repo.manager.config; + +import eu.dnetlib.repo.manager.service.ValidatorServiceImpl; +import org.apache.log4j.Logger; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; + +import java.lang.reflect.Method; + +@Configuration +@EnableAsync +public class AsyncConfiguration implements AsyncConfigurer { + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new AsyncUncaughtExceptionHandler() { + private final Logger logger = Logger.getLogger(getClass()); + + @Override + public void handleUncaughtException(Throwable throwable, Method method, Object... objects) { + //logger.error("Async error", throwable); + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/eu/dnetlib/repo/manager/config/Config.java b/src/main/java/eu/dnetlib/repo/manager/config/Config.java index bd5d4bf..cbef70b 100644 --- a/src/main/java/eu/dnetlib/repo/manager/config/Config.java +++ b/src/main/java/eu/dnetlib/repo/manager/config/Config.java @@ -1,75 +1,81 @@ -package eu.dnetlib.repo.manager.config; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.*; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; -import org.springframework.session.web.http.CookieSerializer; -import org.springframework.session.web.http.DefaultCookieSerializer; -import org.springframework.web.client.RestTemplate; - -import javax.annotation.PostConstruct; - -@Configuration -@EnableRedisHttpSession -@PropertySource(value = {"classpath:application.properties"} ) -@ComponentScan(basePackages = { - "org.eurocris.openaire.cris.validator.service", - "eu.dnetlib.repo.manager.*"}) -public class Config { - - private static Logger LOGGER = Logger.getLogger(Config.class); - - @Value("${redis.host}") - private String host; - - @Value("${redis.port:6379}") - private String port; - - @Value("${redis.password}") - private String password; - - @Value("${aai.mode}") - private String aai_mode; - - @PostConstruct - private void init(){ - LOGGER.info(String.format("Redis : %s Port : %s Password : %s",host,port,password)); - } - - @Bean - public JedisConnectionFactory connectionFactory() { - LOGGER.info(String.format("Redis : %s Port : %s Password : %s",host,port,password)); - JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); - jedisConnectionFactory.setHostName(host); - jedisConnectionFactory.setPort(Integer.parseInt(port)); - jedisConnectionFactory.setUsePool(true); - if(password != null) jedisConnectionFactory.setPassword(password); - return jedisConnectionFactory; - } - - @Bean - public CookieSerializer cookieSerializer() { - DefaultCookieSerializer serializer = new DefaultCookieSerializer(); - serializer.setCookieName("openAIRESession"); - serializer.setCookiePath("/"); - if(aai_mode.equalsIgnoreCase("production") || aai_mode.equalsIgnoreCase("beta")) - serializer.setDomainName(".openaire.eu"); -// serializer.setDomainName(".athenarc.gr"); - LOGGER.info("Serializer : " + serializer); - return serializer; - } - - @Bean - public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(); - restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.set("Content-Type", "application/json"); - return restTemplate; - } - -} +package eu.dnetlib.repo.manager.config; + +import eu.dnetlib.api.enabling.ISLookUpService; +import eu.dnetlib.api.functionality.ValidatorService; +import eu.dnetlib.clients.enabling.islookup.ws.ISLookUpClient; +import eu.dnetlib.clients.functionality.validator.ws.ValidatorWebService; +import eu.dnetlib.clients.functionality.validator.ws.ValidatorWebServiceClient; +import eu.dnetlib.domain.enabling.Vocabulary; +import gr.uoa.di.driver.enabling.ISLookUp; +import gr.uoa.di.driver.enabling.islookup.ISLookUpImpl; +import gr.uoa.di.driver.enabling.vocabulary.ISVocabularyLoader; +import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader; +import gr.uoa.di.driver.util.ServiceLocator; +import gr.uoa.di.driver.util.StaticServiceLocator; +import gr.uoa.di.driver.xml.VocabularyXmlConverter; +import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.*; + +@Configuration +public class Config { + + @Value("${ISLookUpService.url}") + private String lookupURL; + + @Value("${ValidatorService.url}") + private String validatorUrl; + + @Bean(name="vocabularyLoader") + public VocabularyLoader createVocabularyLoader() throws Exception { + ISVocabularyLoader loader = new ISVocabularyLoader(); + + loader.setLookUp(createVocabularyLookUp()); + + return loader; + } + + @Bean("validatorServiceLocator") + public ServiceLocator createValidatorServiceLocator() { + JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); + + factory.setServiceClass(ValidatorWebService.class); + factory.setAddress(validatorUrl); + + ValidatorWebService service = (ValidatorWebService) factory.create(); + + ValidatorWebServiceClient client = new ValidatorWebServiceClient(); + client.setWebService(service); + + StaticServiceLocator locator = new StaticServiceLocator<>(); + locator.setService(client); + + return locator; + } + + // @Bean(name="vocabularyLookUp") + private ISLookUp createVocabularyLookUp() throws Exception { + ISLookUpImpl lookUp = new ISLookUpImpl<>(); + + lookUp.setLookupLocator(createIsLookupServiceLocator()); + lookUp.setConverter(new VocabularyXmlConverter()); + + return lookUp; + } + + private ServiceLocator createIsLookupServiceLocator() throws Exception { + JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); + + factory.setServiceClass(eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService.class); + factory.setAddress(lookupURL); + eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService client = (eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService) factory.create(); + + ISLookUpClient service = new ISLookUpClient(); + service.setWebService(client); + + StaticServiceLocator locator = new StaticServiceLocator<>(); + locator.setService(service); + + return locator; + } +} \ No newline at end of file diff --git a/src/main/java/eu/dnetlib/repo/manager/config/DatasourceConfiguration.java b/src/main/java/eu/dnetlib/repo/manager/config/DatasourceConfiguration.java index 1b0c95b..09a38a8 100644 --- a/src/main/java/eu/dnetlib/repo/manager/config/DatasourceConfiguration.java +++ b/src/main/java/eu/dnetlib/repo/manager/config/DatasourceConfiguration.java @@ -14,16 +14,16 @@ public class DatasourceConfiguration { private static Logger LOGGER = Logger.getLogger(DatasourceConfiguration.class); - @Value("${repomanager.db.driverClassName}") + @Value("${services.repomanager.db.driverClassName}") private String driverClassname; - @Value("${repomanager.db.url}") + @Value("${services.repomanager.db.url}") private String URL; - @Value("${repomanager.db.username}") + @Value("${services.repomanager.db.username}") private String username; - @Value("${repomanager.db.password}") + @Value("${services.repomanager.db.password}") private String password; @Bean diff --git a/src/main/java/eu/dnetlib/repo/manager/config/MailConfig.java b/src/main/java/eu/dnetlib/repo/manager/config/MailConfig.java new file mode 100644 index 0000000..560d2b6 --- /dev/null +++ b/src/main/java/eu/dnetlib/repo/manager/config/MailConfig.java @@ -0,0 +1,57 @@ +package eu.dnetlib.repo.manager.config; + +import eu.dnetlib.utils.MailLibrary; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MailConfig { + + @Value("${services.repomanager.mail.host}") + private String host; + + @Value("${services.repomanager.mail.port}") + private int port; + + @Value("${services.repomanager.mail.authenticate}") + private boolean authenticate; + + @Value("${services.repomanager.mail.username}") + private String username; + + @Value("${services.repomanager.mail.password}") + private String password; + + @Value("${services.repomanager.mail.from}") + private String from; + + @Value("${services.repomanager.mail.replyTo}") + private String replyTo; + + @Value("${services.repomanager.mail.mode}") + private String mode; + + @Value("${services.repomanager.mail.debug}") + private boolean debug; + + @Bean + public MailLibrary createMailLibrary() { + MailLibrary lib = new MailLibrary(); + + lib.setAuthenticate(authenticate); + lib.setDebug(debug); + lib.setFrom(from); + lib.setMailhost(host); + lib.setSmtpPort(port); + lib.setMode(mode); + lib.setReplyTo(replyTo); + lib.setUsername(username); + lib.setPassword(password); + lib.setMode(mode); + + lib.init(); + + return lib; + } +} 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 9b96fd8..84d4968 100644 --- a/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java +++ b/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java @@ -163,13 +163,13 @@ public class RepositoryController { @RequestMapping(value = "/updateRepository", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#repository.id)") + @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOfInterface(#repository.id)") public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception { return repositoryService.updateRepository(repository, authentication); } @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE) - @PreAuthorize("@authorizationService.isMemberOf(#id)") + @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOfInterface(#id)") public void deleteRepositoryInterface(@RequestParam("id") String id, @RequestParam("registeredBy") String registeredBy) { repositoryService.deleteRepositoryInterface(id, registeredBy); @@ -180,13 +180,24 @@ public class RepositoryController { @ResponseBody @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)") public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype, - @RequestParam("id") String id, + @RequestParam("repoId") String id, @RequestParam("registeredBy") String registeredBy, @RequestParam(value = "comment", required = false) String comment, @RequestBody RepositoryInterface repositoryInterface) throws Exception { return repositoryService.addRepositoryInterface(datatype, id, registeredBy, comment, repositoryInterface); } + @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST, + consumes = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)") + public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String id, + @RequestParam("registeredBy") String registeredBy, + @RequestParam(value = "comment", required = false) String comment, + @RequestBody RepositoryInterface repositoryInterface) throws Exception { + return repositoryService.updateRepositoryInterface(id, registeredBy, comment, repositoryInterface); + } + @RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @@ -231,18 +242,6 @@ public class RepositoryController { return repositoryService.getListLatestUpdate(mode); } - @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST, - consumes = MediaType.APPLICATION_JSON_VALUE) - @ResponseBody - @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)") - public RepositoryInterface updateRepositoryInterface(@RequestParam("id") String id, - @RequestParam("registeredBy") String registeredBy, - @RequestParam(value = "comment", required = false) String comment, - @RequestBody RepositoryInterface repositoryInterface) throws Exception { - return repositoryService.updateRepositoryInterface(id, registeredBy, comment, repositoryInterface); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// 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 5edd88c..c455e26 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/BrokerServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/BrokerServiceImpl.java @@ -50,9 +50,6 @@ public class BrokerServiceImpl implements BrokerService { private HashMap topics = new HashMap(); - @Autowired - private EmailUtils emailUtils; - @PostConstruct private void initDnetTopicsMap() { @@ -66,8 +63,7 @@ public class BrokerServiceImpl implements BrokerService { for (JsonNode term : root.path("terms")) topics.put(term.path("code").textValue(), parseTerm(term)); } catch (IOException e) { - LOGGER.debug("Exception on initDnetTopicsMap", e); - emailUtils.reportException(e); + LOGGER.error("Exception on initDnetTopicsMap", e); } } @@ -93,8 +89,7 @@ public class BrokerServiceImpl implements BrokerService { // ret.setDatasourcesOfOthers(getDatasourcesOfUserType(getRepositoriesOfUser(user))); // } } catch (Exception e) { - LOGGER.debug("Exception on getDatasourcesOfUser", e); - emailUtils.reportException(e); + LOGGER.error("Exception on getDatasourcesOfUser", e); } long end = System.currentTimeMillis(); System.out.println("Getting datasources of user in " + (end - start) + "ms"); @@ -117,8 +112,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference>() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on getTopicsForDatasource", e); - emailUtils.reportException(e); throw new BrokerException(e); } @@ -151,13 +144,9 @@ public class BrokerServiceImpl implements BrokerService { } ); } catch (RestClientException e) { - LOGGER.debug("Exception on advancedShowEvents", e); - emailUtils.reportException(e); throw new BrokerException(e); } return resp.getBody(); - - } @@ -210,8 +199,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on showEvents", e); - emailUtils.reportException(e); throw new BrokerException(e); } return resp.getBody(); @@ -236,8 +223,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference>>() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on getSimpleSubscriptionsOfUser", e); - emailUtils.reportException(e); throw new BrokerException(e); } return resp.getBody(); @@ -272,8 +257,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on OpenaireSubscription", e); - emailUtils.reportException(e); throw new BrokerException(e); } @@ -296,8 +279,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on unsubscribe", e); - emailUtils.reportException(e); throw new BrokerException(e); } return new ResponseEntity<>("OK", HttpStatus.OK); @@ -320,8 +301,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on getSubscription", e); - emailUtils.reportException(e); throw new BrokerException(e); } return resp.getBody(); @@ -351,8 +330,6 @@ public class BrokerServiceImpl implements BrokerService { new ParameterizedTypeReference() { }); } catch (RestClientException e) { - LOGGER.debug("Exception on getNotificationsBySubscriptionId", e); - emailUtils.reportException(e); throw new BrokerException(e); } return resp.getBody(); 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 4a96da6..7e5ba3a 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/DashboardServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/DashboardServiceImpl.java @@ -14,9 +14,6 @@ public class DashboardServiceImpl implements DashboardService { private static final Logger logger = Logger.getLogger(DashboardServiceImpl.class); - @Autowired - private EmailUtils emailUtils; - @Autowired private RepositoryService repositoryService; 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 63efbec..5bc1912 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/EmailUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/EmailUtils.java @@ -4,69 +4,92 @@ import eu.dnetlib.domain.data.PiwikInfo; import eu.dnetlib.domain.data.Repository; import eu.dnetlib.domain.data.RepositoryInterface; import eu.dnetlib.domain.functionality.validator.JobForValidation; +import org.springframework.scheduling.annotation.Async; import org.springframework.security.core.Authentication; public interface EmailUtils { - - void reportException(Exception exception); - + @Async void sendAdministratorRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception; + @Async void sendUserRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception; + @Async void sendAdministratorMetricsEnabled(PiwikInfo piwikInfo) throws Exception; + @Async void sendUserMetricsEnabled(PiwikInfo piwikInfo) throws Exception; /****USER REGISTRATION REQUEST EMAILS****/ + @Async void sendAdminRegistrationEmail(Repository repository, Authentication authentication) throws Exception; + @Async void sendUserRegistrationEmail(Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) throws Exception; + @Async void sendUserRegisterInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) throws Exception; /****SUCCESSFUL REGISTRATION RESULTS EMAILS****/ + @Async void sendUserRegistrationResultsSuccessEmail(String issuerEmail, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminRegistrationResultsSuccessEmail(String issuerEmail, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; /****FAILURE REGISTRATION RESULTS EMAILS****/ + @Async void sendUserRegistrationResultsFailureEmail(String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminRegistrationResultsFailureEmail(String issuerEmail, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; /****SUCCESSFUL UPDATE RESULTS EMAILS****/ + @Async void sendUserUpdateResultsSuccessEmail(String issuer, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminUpdateResultsSuccessEmail(String issuerEmail, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; /****FAILURE UPDATE RESULTS EMAILS****/ + @Async void sendUserUpdateResultsFailureEmail(String issuer, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminUpdateResultsFailureEmail(String issuerEmail, String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; /****VALIDATION OF CONTENT PROVIDER EMAILS****/ + @Async void sendUserValidationResults(String issuer,String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminValidationResults(String issuer,String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; /****GENERAL FAILURE OF VALIDATOR****/ + @Async void sendAdminGeneralFailure(String issuer,String jobId,RepositoryInterface repositoryInterface, Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminUpdateRepositoryInfoEmail(Repository repository, Authentication authentication) throws Exception; + @Async void sendUserUpdateRepositoryInfoEmail(Repository repository, Authentication authentication) throws Exception; + @Async void sendAdminUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) throws Exception; + @Async void sendUserUpdateInterfaceEmail(Repository repository, String comment, RepositoryInterface repositoryInterface, Authentication authentication) throws Exception; + @Async void sendSubmitJobForValidationEmail(Authentication authentication, JobForValidation jobForValidation) throws Exception; + @Async void sendUponJobCompletion(String repoId, String repoInterfaceId, int scoreUsage, 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 ae78561..14bced3 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java @@ -4,7 +4,6 @@ import eu.dnetlib.domain.data.PiwikInfo; import eu.dnetlib.domain.data.Repository; import eu.dnetlib.domain.data.RepositoryInterface; import eu.dnetlib.domain.functionality.validator.JobForValidation; -import eu.dnetlib.repo.manager.config.CascadingPropertyLoader; import eu.dnetlib.repo.manager.domain.ValidationServiceException; import eu.dnetlib.utils.MailLibrary; import org.apache.log4j.Logger; @@ -15,76 +14,36 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; - @Component("emailUtils") public class EmailUtilsImpl implements EmailUtils { - private static Logger LOGGER = Logger.getLogger(EmailUtilsImpl.class); - - private List specialRecipients = new ArrayList(); - private boolean override = false, logonly = false; - private String overrideEmail = null, from = null; + private final static Logger LOGGER = Logger.getLogger(EmailUtilsImpl.class); private final MailLibrary mailLibrary; - private final CascadingPropertyLoader pLoader; private final RepositoryService repositoryService; - @Value("${services.repo-manager.baseUrl}") + @Value("${services.repomanager.baseUrl}") private String baseUrl; - @Value("${services.repo-manager.adminEmail}") - private String adminEmail; - @Value("${services.repomanager.usagestats.adminEmail}") private String usageStatsAdminEmail; - @Value("${services.provide.adminEmail}") + @Value("${services.repomanager.provide.adminEmail}") private String provideAdminEmail; @Value("${validator.results.url}") private String valBaseUrl; @Autowired - EmailUtilsImpl(MailLibrary mailLibrary, CascadingPropertyLoader pLoader, - RepositoryService repositoryService) { + EmailUtilsImpl(MailLibrary mailLibrary, RepositoryService repositoryService) { this.mailLibrary = mailLibrary; - this.pLoader = pLoader; this.repositoryService = repositoryService; } - - @PostConstruct - public void init(){ - System.out.println("url -> " + this.baseUrl); - } - - - @Override - public void reportException(Exception exception) { - Writer writer = new StringWriter(); - PrintWriter printWriter = new PrintWriter(writer); - exception.printStackTrace(printWriter); - - List recipients = new ArrayList(); - - try { - recipients.add(this.adminEmail); - String message = "An exception has occurred:\n"+writer.toString(); - String subject = "Automatic Bug Report"; - this.sendMail(recipients, subject, message, false, null); - } catch (Exception e) { - LOGGER.error("Error sending error report", e); - } - } - @Override public void sendAdministratorRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception { @@ -106,7 +65,7 @@ public class EmailUtilsImpl implements EmailUtils { "Best,\n" + "The OpenAIRE team"; - this.sendMail(this.usageStatsAdminEmail, subject, message, false, null); + this.sendMail(this.usageStatsAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending request to enable metrics email to administrator: " + this.usageStatsAdminEmail, e); @@ -143,7 +102,7 @@ public class EmailUtilsImpl implements EmailUtils { "Best,\n" + "The OpenAIRE team"; - this.sendMail(piwikInfo.getRequestorEmail(), subject, message, false, null); + this.sendMail(piwikInfo.getRequestorEmail(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending request to enable metrics email to user: " + piwikInfo.getRequestorEmail(), e); @@ -170,7 +129,7 @@ public class EmailUtilsImpl implements EmailUtils { "Best,\n" + "The OpenAIRE team"; - this.sendMail(this.usageStatsAdminEmail, subject, message, false, null); + this.sendMail(this.usageStatsAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending metrics enabled notification email to administator: " + this.usageStatsAdminEmail, e); @@ -198,7 +157,7 @@ public class EmailUtilsImpl implements EmailUtils { "Best,\n" + "The OpenAIRE team"; - this.sendMail(piwikInfo.getRequestorEmail(), subject, message, false, null); + this.sendMail(piwikInfo.getRequestorEmail(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending metrics enabled notification email to user: " + piwikInfo.getRequestorEmail(), e); @@ -224,7 +183,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to the administrator", e); @@ -250,7 +209,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(repository.getRegisteredBy(), subject, message, false, null); + this.sendMail(repository.getRegisteredBy(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -285,7 +244,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration of interface notification email to the administrator", e); @@ -319,7 +278,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(repository.getRegisteredBy(), subject, message, false, null); + this.sendMail(repository.getRegisteredBy(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration of interface notification email to user: " + repository.getRegisteredBy(), e); @@ -352,7 +311,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(repository.getRegisteredBy(), subject, message, false, null); + this.sendMail(repository.getRegisteredBy(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -385,7 +344,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -417,7 +376,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(repository.getRegisteredBy(), subject, message, false, null); + this.sendMail(repository.getRegisteredBy(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -450,7 +409,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -481,7 +440,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(issuer, subject, message, false, null); + this.sendMail(issuer, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to the administrator", e); @@ -512,7 +471,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to the administrator", e); @@ -545,7 +504,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(issuer, subject, message, false, null); + this.sendMail(issuer, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -578,7 +537,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -601,7 +560,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(issuer, subject, message, false, null); + this.sendMail(issuer, subject, message); } catch (Exception e) { LOGGER.error("Error while sending validation submission notification email to user: " + issuer, e); @@ -624,7 +583,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending validation submission notification email to user: " + issuer, e); @@ -644,7 +603,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending validation submission notification email to user: " + issuer, e); @@ -666,7 +625,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to the administrator", e); @@ -690,7 +649,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(repository.getRegisteredBy(), subject, message, false, null); + this.sendMail(repository.getRegisteredBy(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -723,7 +682,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(this.provideAdminEmail, subject, message, false, null); + this.sendMail(this.provideAdminEmail, subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to the administrator", e); @@ -757,7 +716,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(repository.getRegisteredBy(), subject, message, false, null); + this.sendMail(repository.getRegisteredBy(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending registration notification email to user: " + repository.getRegisteredBy(), e); @@ -780,7 +739,7 @@ public class EmailUtilsImpl implements EmailUtils { "Regards,\n" + "the OpenAIRE technical team\n"; - this.sendMail(jobForValidation.getUserEmail(), subject, message, false, null); + this.sendMail(jobForValidation.getUserEmail(), subject, message); } catch (Exception e) { LOGGER.error("Error while sending validation submission notification email to user: " + jobForValidation.getUserEmail(), e); @@ -833,73 +792,17 @@ public class EmailUtilsImpl implements EmailUtils { } - - private void sendMail(String email, String subject, String message, boolean sendToSpecial, List repoAdminMails) throws Exception { - ArrayList to = new ArrayList(); - to.add(email); - this.sendMail(to,subject,message,sendToSpecial,repoAdminMails); + private void sendMail(String email, String subject, String message) throws Exception { + this.sendMail(Collections.singletonList(email), subject, message); } - public void sendMail(List recipients, String subject, String message, boolean sendToSpecial, List repoAdminMails) throws Exception { - + public void sendMail(List recipients, String subject, String message) throws Exception { try { - if (sendToSpecial) { - recipients.addAll(this.specialRecipients); - } - - if (repoAdminMails != null) - recipients.addAll(repoAdminMails); - - if (this.override) { - recipients.clear(); - recipients.add(overrideEmail); - } - if (!logonly) - mailLibrary.sendEmail(recipients.toArray(new String[]{}), subject, message); LOGGER.debug("Sending mail to Recipients: " + recipients + " Subject: " + subject + " Message: " + message); + mailLibrary.sendEmail(recipients.toArray(new String[]{}), subject, message); } catch (Exception e) { LOGGER.error("Error sending mail to Recipients: " + recipients + " Subject: " + subject + " Message: " + message, e); - throw new Exception(e); + throw e; } } - - private String getEmailProperty(String key) { - return pLoader.getProperties().getProperty(key); - } - - public void setSpecialRecipients(String specialRecipients) { - String[] recps = specialRecipients.split(","); - - for (String recp : recps) { - recp = recp.trim(); - - this.specialRecipients.add(recp); - } - } - - - public void setOverride(boolean override) { - this.override = override; - } - - public void setOverrideEmail(String overrideEmail) { - this.overrideEmail = overrideEmail; - } - - public String getFrom() { - return from; - } - - public void setFrom(String from) { - this.from = from; - } - - public boolean isLogonly() { - return logonly; - } - - public void setLogonly(boolean logonly) { - this.logonly = logonly; - } - } 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 4c3a995..986765d 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/PiWikServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/PiWikServiceImpl.java @@ -169,11 +169,10 @@ public class PiWikServiceImpl implements PiWikService { } catch (EmptyResultDataAccessException e) { LOGGER.error("Error while approving piwik site: ", e); - emailUtils.reportException(e); throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR); } catch (Exception e) { LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e); - emailUtils.reportException(e); + throw new RepositoryServiceException(e, RepositoryServiceException.ErrorCode.GENERAL_ERROR); } return new ResponseEntity<>("OK", HttpStatus.OK); } @@ -204,15 +203,13 @@ public class PiWikServiceImpl implements PiWikService { emailUtils.sendUserRequestToEnableMetrics(piwikInfo); } catch (UnsupportedEncodingException uee) { LOGGER.error("Error while creating piwikScript URL", uee); - emailUtils.reportException(uee); throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR); } catch (IOException ioe) { LOGGER.error("Error while creating piwik site", ioe); - emailUtils.reportException(ioe); throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR); } catch (Exception e) { LOGGER.error("Error while sending email to administrator or user about the request to enable metrics", e); - emailUtils.reportException(e); + throw new RepositoryServiceException(e, RepositoryServiceException.ErrorCode.GENERAL_ERROR); } return piwikInfo; } 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 1fdff3a..36192d2 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java @@ -36,7 +36,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.util.MimeType; import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; @@ -178,17 +177,11 @@ public class RepositoryServiceImpl implements RepositoryService { UriComponents uriComponents = searchDatasource(Integer.toString(Math.abs(page)), Integer.toString(Math.abs(size))); RequestFilter requestFilter = new RequestFilter(); - try { - for (String repoId : ids) { - requestFilter.setId(repoId); - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + for (String repoId : ids) { + requestFilter.setId(repoId); + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - repos.addAll(Converter.jsonToRepositoryList(new JSONObject(rs))); - } - } catch (JSONException e) { - LOGGER.debug("Exception on getRepositoriesOfUser", e); - emailUtils.reportException(e); - throw e; + repos.addAll(Converter.jsonToRepositoryList(new JSONObject(rs))); } for (Repository r : repos) @@ -264,23 +257,20 @@ public class RepositoryServiceImpl implements RepositoryService { requestFilter.setCountry(country); requestFilter.setCollectedfrom(filterKey); - try { - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); - while (jsonArray.length() > 0) { - resultSet.addAll(mapper.readValue(String.valueOf(jsonArray), - mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class))); - page += 1; - uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size)); - rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); - } - return resultSet; - } catch (Exception e) { - LOGGER.debug("Exception on getRepositoriesByCountry", e); - emailUtils.reportException(e); - throw e; + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); + while (jsonArray.length() > 0) { + +LOGGER.debug("json: " + jsonArray); + + resultSet.addAll(mapper.readValue(String.valueOf(jsonArray), + mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class))); + page += 1; + uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size)); + rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); } + return resultSet; } public List searchRegisteredRepositories(String country, String typology, String englishName, @@ -383,21 +373,14 @@ public class RepositoryServiceImpl implements RepositoryService { RequestFilter requestFilter = new RequestFilter(); requestFilter.setId(id); - try { - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); - if (jsonArray.length() == 0) - throw new ResourceNotFoundException(); - - repo = Converter.jsonToRepositorySnippetObject(jsonArray.getJSONObject(0)); - return repo; - } catch (JSONException e) { - LOGGER.debug("Exception on getRepositoryById", e); - emailUtils.reportException(e); - throw e; - } + if (jsonArray.length() == 0) + throw new ResourceNotFoundException(); + repo = Converter.jsonToRepositorySnippetObject(jsonArray.getJSONObject(0)); + return repo; } @Override @@ -409,21 +392,14 @@ public class RepositoryServiceImpl implements RepositoryService { RequestFilter requestFilter = new RequestFilter(); requestFilter.setId(id); - try { - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo"); - if (jsonArray.length() == 0) - throw new ResourceNotFoundException(); - - repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0)); - return updateRepositoryInfo(repo); - } catch (JSONException e) { - LOGGER.debug("Exception on getRepositoryById", e); - emailUtils.reportException(e); - throw e; - } + if (jsonArray.length() == 0) + throw new ResourceNotFoundException(); + repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0)); + return updateRepositoryInfo(repo); } @@ -437,31 +413,25 @@ public class RepositoryServiceImpl implements RepositoryService { List aggregationHistory = new ArrayList<>(); - try { - long start = System.currentTimeMillis(); - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - long end = System.currentTimeMillis(); + long start = System.currentTimeMillis(); + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + long end = System.currentTimeMillis(); - System.out.println("Aggregations request through rest template took " + (end - start) + "ms"); - JSONObject repository = new JSONObject(rs); + System.out.println("Aggregations request through rest template took " + (end - start) + "ms"); + JSONObject repository = new JSONObject(rs); - if (repository.getJSONArray("datasourceInfo").length() == 0) - return aggregationHistory; + if (repository.getJSONArray("datasourceInfo").length() == 0) + return aggregationHistory; - start = System.currentTimeMillis(); - aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0))); - end = System.currentTimeMillis(); + start = System.currentTimeMillis(); + aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0))); + end = System.currentTimeMillis(); - System.out.println("Getting aggregations history from json " + (end - start) + "ms"); - return aggregationHistory.size() == 0 ? aggregationHistory : aggregationHistory.stream() - .sorted(Comparator.comparing(AggregationDetails::getDate).reversed()) - .limit(size) - .collect(Collectors.toList()); - } catch (JSONException e) { - LOGGER.debug("Exception on getRepositoryAggregations", e); - emailUtils.reportException(e); - throw e; - } + System.out.println("Getting aggregations history from json " + (end - start) + "ms"); + return aggregationHistory.size() == 0 ? aggregationHistory : aggregationHistory.stream() + .sorted(Comparator.comparing(AggregationDetails::getDate).reversed()) + .limit(size) + .collect(Collectors.toList()); } @@ -474,21 +444,15 @@ public class RepositoryServiceImpl implements RepositoryService { List aggregationHistory = new ArrayList<>(); Map> aggregationByYear = new HashMap<>(); - try { - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - JSONObject repository = new JSONObject(rs); - if (repository.getJSONArray("datasourceInfo").length() == 0) - return aggregationByYear; + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + JSONObject repository = new JSONObject(rs); - aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0))); - return aggregationHistory.size() == 0 ? aggregationByYear : createYearMap(aggregationHistory); + if (repository.getJSONArray("datasourceInfo").length() == 0) + return aggregationByYear; - } catch (JSONException e) { - LOGGER.debug("Exception on getRepositoryAggregations", e); - emailUtils.reportException(e); - throw e; - } + aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0))); + return aggregationHistory.size() == 0 ? aggregationByYear : createYearMap(aggregationHistory); } private Map> createYearMap(List aggregationHistory) { @@ -512,17 +476,11 @@ public class RepositoryServiceImpl implements RepositoryService { RequestFilter requestFilter = new RequestFilter(); requestFilter.setOfficialname(name); - try { - String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); - List repos = Converter.jsonToRepositoryList(new JSONObject(rs)); - for (Repository r : repos) - updateRepositoryInfo(r); - return repos; - } catch (Exception e) { - LOGGER.debug("Exception on getRepositoriesByName", e); - emailUtils.reportException(e); - throw e; - } + String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class); + List repos = Converter.jsonToRepositoryList(new JSONObject(rs)); + for (Repository r : repos) + updateRepositoryInfo(r); + return repos; } @@ -534,20 +492,13 @@ public class RepositoryServiceImpl implements RepositoryService { .path("/{id}") .build().expand(id).encode(); - try { - String rs = restTemplate.getForObject(uriComponents.toUri(), String.class); - return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs)); - } catch (Exception e) { - LOGGER.debug("Exception on getRepositoryInterface", e); - emailUtils.reportException(e); - throw e; - } + String rs = restTemplate.getForObject(uriComponents.toUri(), String.class); + return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs)); } @Override - public Repository addRepository(String datatype, - Repository repository) throws Exception { + public Repository addRepository(String datatype, Repository repository) throws Exception { LOGGER.debug("storing " + datatype + " repository with id: " + repository.getId()); @@ -611,27 +562,23 @@ public class RepositoryServiceImpl implements RepositoryService { .build() .encode(); - try { - String json_repository = Converter.repositoryObjectToJson(repository); - LOGGER.debug("JSON to add(update) -> " + json_repository); + String json_repository = Converter.repositoryObjectToJson(repository); + LOGGER.debug("JSON to add(update) -> " + json_repository); - HttpEntity httpEntity = new HttpEntity(json_repository, httpHeaders); - ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class); + HttpEntity httpEntity = new HttpEntity(json_repository, httpHeaders); + ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class); - if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { + if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { + try { emailUtils.sendUserRegistrationEmail(repository, authentication); emailUtils.sendAdminRegistrationEmail(repository, authentication); - } else - LOGGER.debug(responseEntity.getBody().toString()); - - return repository; - } catch (Exception e) { - LOGGER.debug("Exception on updateRepository", e); - emailUtils.reportException(e); - throw e; - } - + } catch (Exception e) { + LOGGER.error("Error sending email", e); + } + } else + LOGGER.error("Error storing repository: " + responseEntity.getBody().toString()); + return repository; } @Override @@ -641,27 +588,25 @@ public class RepositoryServiceImpl implements RepositoryService { .build() .encode(); - try { - String json_repository = Converter.repositoryObjectToJson(repository); + String json_repository = Converter.repositoryObjectToJson(repository); - LOGGER.debug("JSON to update -> " + json_repository); + LOGGER.debug("JSON to update -> " + json_repository); - HttpEntity httpEntity = new HttpEntity(json_repository, httpHeaders); - ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity - , ResponseEntity.class); + HttpEntity httpEntity = new HttpEntity(json_repository, httpHeaders); + ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity + , ResponseEntity.class); - if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { + if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { + try { emailUtils.sendUserUpdateRepositoryInfoEmail(repository, authentication); emailUtils.sendAdminUpdateRepositoryInfoEmail(repository, authentication); - } else - LOGGER.debug(responseEntity.getBody().toString()); + } catch (Exception e) { + LOGGER.error("Error sending emails: " + e); + } + } else + LOGGER.debug(responseEntity.getBody().toString()); - return repository; - } catch (Exception e) { - LOGGER.debug("Exception on updateRepository", e); - emailUtils.reportException(e); - throw e; - } + return repository; } private void storeRepository(Repository repository, Authentication authentication) throws Exception { @@ -681,8 +626,12 @@ public class RepositoryServiceImpl implements RepositoryService { ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class); if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { - emailUtils.sendUserRegistrationEmail(repository, authentication); - emailUtils.sendAdminRegistrationEmail(repository, authentication); + try { + emailUtils.sendUserRegistrationEmail(repository, authentication); + emailUtils.sendAdminRegistrationEmail(repository, authentication); + } catch (Exception e) { + LOGGER.error("Error sending emails: " + e); + } } else { LOGGER.debug(responseEntity.getBody().toString()); } @@ -704,32 +653,29 @@ public class RepositoryServiceImpl implements RepositoryService { String repoId, String registeredBy, String comment, RepositoryInterface repositoryInterface) throws Exception { + Repository e = this.getRepositoryById(repoId); + repositoryInterface = createRepositoryInterface(e, repositoryInterface, datatype); + String json_interface = Converter.repositoryInterfaceObjectToJson(e, repositoryInterface); + + UriComponents uriComponents = UriComponentsBuilder + .fromHttpUrl(baseAddress + "/ds/api/add/") + .build() + .encode(); + + HttpEntity httpEntity = new HttpEntity<>(json_interface, httpHeaders); + + restTemplate.postForObject(uriComponents.toUri(), httpEntity, String.class); + try { - Repository e = this.getRepositoryById(repoId); - repositoryInterface = createRepositoryInterface(e, repositoryInterface, datatype); - String json_interface = Converter.repositoryInterfaceObjectToJson(e, repositoryInterface); - - UriComponents uriComponents = UriComponentsBuilder - .fromHttpUrl(baseAddress + "/ds/api/add/") - .build() - .encode(); - - HttpEntity httpEntity = new HttpEntity<>(json_interface, httpHeaders); - - restTemplate.postForObject(uriComponents.toUri(), httpEntity, String.class); - emailUtils.sendAdminRegisterInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication()); emailUtils.sendUserRegisterInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication()); - - submitInterfaceValidation(e, registeredBy, repositoryInterface, false); - - return repositoryInterface; - - } catch (Exception e) { - LOGGER.error("Exception on addRepositoryInterface", e); - emailUtils.reportException(e); - throw e; + } catch (Exception ex) { + LOGGER.error("Error sending emails: " + ex); } + + submitInterfaceValidation(e, registeredBy, repositoryInterface, false); + + return repositoryInterface; } @Override @@ -743,8 +689,12 @@ public class RepositoryServiceImpl implements RepositoryService { Repository repository = this.getRepositoryById(repoId); try { - emailUtils.sendAdminUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication()); - emailUtils.sendUserUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication()); + try { + emailUtils.sendAdminUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication()); + emailUtils.sendUserUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication()); + } catch (Exception e) { + LOGGER.error("Error sending emails: " + e); + } } catch (Exception e) { LOGGER.warn("Could not send emails", e); } @@ -834,15 +784,9 @@ public class RepositoryServiceImpl implements RepositoryService { .path("/{page}/{size}") .build().expand(page, size).encode(); - try { - RequestFilter requestFilter = new RequestFilter(); - requestFilter.setRegisteredby(userEmail); - return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(), requestFilter, String[].class)); - } catch (Exception e) { - LOGGER.debug("Exception on addRepositoryInterface", e); - emailUtils.reportException(e); - throw e; - } + RequestFilter requestFilter = new RequestFilter(); + requestFilter.setRegisteredby(userEmail); + return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(), requestFilter, String[].class)); } @Override @@ -959,7 +903,6 @@ public class RepositoryServiceImpl implements RepositoryService { } catch (Exception e) { LOGGER.error("Error while getting metrics info for repository: ", e); - emailUtils.reportException(e); throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR); } } @@ -1016,19 +959,14 @@ public class RepositoryServiceImpl implements RepositoryService { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); ResponseEntity resp; - try { - //communicate with endpoint - resp = template.exchange( - builder.build().encode().toUri(), - HttpMethod.GET, - null, - new ParameterizedTypeReference() { - }); - } catch (RestClientException e) { - LOGGER.debug("Exception on getMetricsNumbers", e); - emailUtils.reportException(e); - throw e; - } + + //communicate with endpoint + resp = template.exchange( + builder.build().encode().toUri(), + HttpMethod.GET, + null, + new ParameterizedTypeReference() { + }); return resp.getBody(); } 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 a99a198..c7b0a0a 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java @@ -2,7 +2,6 @@ package eu.dnetlib.repo.manager.service; import eu.dnetlib.usagestats.sushilite.domain.ReportItem; import eu.dnetlib.usagestats.sushilite.domain.ReportResponseWrapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; @@ -10,7 +9,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; -import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -24,9 +22,6 @@ public class SushiliteServiceImpl implements SushiliteService { @Value("${services.repomanager.usagestats.sushiliteEndpoint}") private String usagestatsSushiliteEndpoint; - @Autowired - private EmailUtils emailUtils; - private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(SushiliteServiceImpl.class); @@ -63,19 +58,14 @@ public class SushiliteServiceImpl implements SushiliteService { template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); ResponseEntity resp; - try { - //communicate with endpoint - resp = template.exchange( - builder.build().encode().toUri(), - HttpMethod.GET, - null, - new ParameterizedTypeReference() { - }); - } catch (RestClientException e) { - LOGGER.debug("Exception on getReportResults" , e); - emailUtils.reportException(e); - throw e; - } + + //communicate with endpoint + resp = template.exchange( + builder.build().encode().toUri(), + HttpMethod.GET, + null, + new ParameterizedTypeReference() { + }); // check remote api's response System.out.println("sushi responded status " + resp.getStatusCode()); 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 f929437..d67e0a3 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/ValidatorServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/ValidatorServiceImpl.java @@ -131,7 +131,11 @@ public class ValidatorServiceImpl implements ValidatorService { public JobForValidation submitJobForValidation(JobForValidation jobForValidation) throws ValidatorServiceException { LOGGER.debug("Submit job for validation with id : " + jobForValidation.getDatasourceId()); try { - emailUtils.sendSubmitJobForValidationEmail(SecurityContextHolder.getContext().getAuthentication(),jobForValidation); + try { + emailUtils.sendSubmitJobForValidationEmail(SecurityContextHolder.getContext().getAuthentication(), jobForValidation); + } catch (Exception e) { + LOGGER.error("Error sending email ", e); + } ///////////////////////////////////////////////////////////////////////////////////////// // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly // ///////////////////////////////////////////////////////////////////////////////////////// @@ -144,13 +148,10 @@ public class ValidatorServiceImpl implements ValidatorService { ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // this.getValidationService().submitValidationJob(jobForValidation); - } catch (ValidatorServiceException e) { - LOGGER.debug("Exception on submitJobForValidation" , e); - emailUtils.reportException(e); - throw e; } catch (Exception e) { - LOGGER.error(e); + throw new ValidatorServiceException(e); } + return jobForValidation; } @@ -200,13 +201,16 @@ public class ValidatorServiceImpl implements ValidatorService { @Override public List getSetsOfRepository(String url) { LOGGER.debug("Getting sets of repository with url : " + url); + + List sets = null; + try { - return OaiTools.getSetsOfRepo(url); + sets = OaiTools.getSetsOfRepo(url); } catch (Exception e) { - LOGGER.debug("Exception on getSetsOfRepository" , e); - emailUtils.reportException(e); + LOGGER.error("Exception on getSetsOfRepository" , e); } - return null; + + return sets; } @Override @@ -216,7 +220,6 @@ public class ValidatorServiceImpl implements ValidatorService { return OaiTools.identifyRepository(url); } catch (Exception e) { LOGGER.error("Error while identifying repository with url: " + url, e); - emailUtils.reportException(e); return false; } } @@ -236,7 +239,6 @@ public class ValidatorServiceImpl implements ValidatorService { return ruleSet; } catch (Exception e) { LOGGER.error("Error getting ruleset", e); - emailUtils.reportException(e); return null; } } @@ -284,7 +286,6 @@ public class ValidatorServiceImpl implements ValidatorService { return interfaceInformation; } catch (Exception e) { LOGGER.error("Error getting interface information with url: " + baseUrl, e); - emailUtils.reportException(e); throw new ValidationServiceException("login.generalError", ValidationServiceException.ErrorCode.GENERAL_ERROR); } } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesUpdater.java b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesUpdater.java index 94c58ca..76c0b1f 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesUpdater.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesUpdater.java @@ -9,7 +9,8 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.common.exceptions.UnauthorizedClientException; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; +//import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.stereotype.Service; @@ -28,11 +29,11 @@ public class AuthoritiesUpdater extends HttpSessionSecurityContextRepository { public void update(String email, Collection authorities) { if (sessions != null) { - Map map = sessions. + Map map = sessions. findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, email); if (map != null) { logger.debug(map.values().toArray().length); - for (ExpiringSession session : map.values()) { + for (Session session : map.values()) { logger.debug(session.getId()); if (!session.isExpired()) { SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT_KEY); 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 d714b8f..15f1707 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 @@ -21,6 +21,11 @@ public interface AuthorizationService { */ boolean isMemberOf(String id); + /** + * @param id repository interface Id to check. + * @return Checks if a user is a member of a repository interface. + */ + boolean isMemberOfInterface(String id); /** * Returns a list of admins of the resource. 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 768d3ad..10d724a 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 @@ -53,7 +53,16 @@ public class AuthorizationServiceImpl implements AuthorizationService { public boolean isMemberOf(String repoId) { String repoRole = roleMappingService.convertRepoIdToEncodedAuthorityId(repoId); return SecurityContextHolder.getContext().getAuthentication().getAuthorities() - .parallelStream().anyMatch(authority -> authority.toString().equals(repoRole)); + .stream().anyMatch(authority -> authority.toString().equals(repoRole)); + } + + @Override + public boolean isMemberOfInterface(String interfaceId) { + + //TODO blame Konstantinos Spyrou. He forced my hand... + String repoId = interfaceId.split("::")[1] + "::" + interfaceId.split("::")[2]; + + return isMemberOf(repoId); } @Override diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 7390b5e..d243c62 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -6,83 +6,20 @@ container.hostname = estella.athenarc.gr provider.endpoint=http://estella.athenarc.gr:8480/uoa-repository-manager-service -#container.hostname = validator.mincyt.research-infrastructures.eu -container.port = 8080 -#container.context = - -# BASIC SETTINGS -services.validator.mode.user = ldap -services.validator.mail.override = false -services.validator.mode.repo = dms -services.validator.baseUrl = http://${container.hostname}:${container.port}/${container.context} -services.validator.dnetWorkflow = true -services.validator.deploy.environment = openaire-beta -#services.validator.deploy.environment = mincyt -services.validator.registration.files.download = true -services.validator.autoRestoreOnStartup = false -services.validator.mode.standalone = false -services.validator.mail.override = false -services.validator.adminEmail = antleb@di.uoa.gr -services.validator.admins.master = antleb@di.uoa.gr -services.validator.admins.secondary = ant.lebesis@gmail.com -services.validator.adminBaseUrl = ../validator-admin -services.validator.webBaseUrl = http://${container.hostname}:${container.port}/validator -services.validator.registrationsReport.email = ant.lebesis@gmail.com -services.repo-manager.repository.testing.mode = false - # EMAIL SETTINGS -services.validator.mail.host = smtp.gmail.com -services.validator.mail.port = 465 -services.validator.mail.username = test.openaire@gmail.com -services.validator.mail.password = ^($*@$)*!$ -services.validator.mail.authenticate = true -services.validator.mail.mode = ssl -ervices.validator.mail.fromAddress = no-reply@mpagasas.openaire.eu -services.validator.mail.override = false -services.validator.mail.overrideEmail = nikonas@di.uoa.gr -services.validator.mail.specialRecipients = antleb@di.uoa.gr - - -# VALIDATOR DB -services.validator.db.driverClassName = org.postgresql.Driver -#services.validator.db.url = jdbc:postgresql://194.177.192.119:5432/validator -services.validator.db.url = jdbc:postgresql://88.197.53.70:5432/validator -services.validator.db.username = dnet -services.validator.db.password = dnetPwd +services.repomanager.mail.host = smtp.gmail.com +services.repomanager.mail.port = 465 +services.repomanager.mail.username = test.openaire@gmail.com +services.repomanager.mail.password = ^($*@$)*!$ +services.repomanager.mail.authenticate = true +services.repomanager.mail.debug = false +services.repomanager.mail.mode = ssl +services.repomanager.mail.from = test.openaire@gmail.com +services.repomanager.mail.replyTo = test.openaire@gmail.com # IS -#ISLookUpService.url = http://node1.t.openaire.research-infrastructures.eu:8280/is/services/isLookUp -#ISRegistryService.url = http://node1.t.openaire.research-infrastructures.eu:8280/is/services/isRegistry -#ISSNService.url = http://node1.t.openaire.research-infrastructures.eu:8280/is/services/isSN - -#ISLookUpService.url = http://skalny.icm.edu.pl:8280/is/services/isLookUp -#ISRegistryService.url = http://skalny.icm.edu.pl:8280/is/services/isRegistry -#ISSNService.url = skalny.icm.edu.pl:8280/is/services/isSN - -#ISLookUpService.url = http://node0.t.openaire.research-infrastructures.eu:8080/is/services/isLookUp -#ISRegistryService.url = http://node0.t.openaire.research-infrastructures.eu:8080/is/services/isRegistry -#ISSNService.url = http://node0.t.openaire.research-infrastructures.eu:8080/is/services/isSN - -#ISLookUpService.url = http://node6.t.openaire.research-infrastructures.eu:8980/dnet/services/isLookUp -#ISRegistryService.url = http://node6.t.openaire.research-infrastructures.eu:8980/dnet/services/isRegistry -#ISSNService.url = http://node6.t.openaire.research-infrastructures.eu:8980/dnet/services/isSN - -#ISLookUpService.url = http://node6.t.openaire.research-infrastructures.eu:8280/is/services/isLookUp -#ISRegistryService.url = http://node6.t.openaire.research-infrastructures.eu:8280/is/services/isRegistry -#ISSNService.url = http://node6.t.openaire.research-infrastructures.eu:8280/is/services/isSN - -#ISLookUpService.url = http://aggregator.mincyt.research-infrastructures.eu:8080/is/services/isLookUp -#ISRegistryService.url = http://aggregator.mincyt.research-infrastructures.eu:8080/is/services/isRegistry -#ISSNService.url = http://aggregator.mincyt.research-infrastructures.eu:8080/is/services/isSN - -#ISLookUpService.url = http://node0.d.hudl.research-infrastructures.eu:8080/is/services/isLookUp -#ISRegistryService.url = http://node0.d.hudl.research-infrastructures.eu:8080/is/services/isRegistry -#ISSNService.url = http://node0.d.hudl.research-infrastructures.eu:8080/is/is/services/isSN - ISLookUpService.url = https://dev-openaire.d4science.org:443/is/services/isLookUp -ISRegistryService.url = https://dev-openaire.d4science.org:443/is/services/isRegistry -ISSNService.url = https://dev-openaire.d4science.org:443/is/services/isSN -ValidatorService.url=http://estella.athenarc.gr:8080/validator-service/services/validatorWebService +ValidatorService.url=http://88.197.53.69:8080/uoa-validator-service/services/validatorWebService # LDAP #services.validator.ldap.address = 88.197.53.113 @@ -91,61 +28,56 @@ ValidatorService.url=http://estella.athenarc.gr:8080/validator-service/services/ #services.validator.ldap.username = cn=admin,dc=openaire,dc=eu #services.validator.ldap.password = serenata #services.validator.ldap.usersDN = ou=users,dc=openaire,dc=eu - -services.users.ldap.address = 194.177.192.119 -services.users.ldap.port = 389 -services.users.ldap.username = cn=admin,dc=openaire,dc=eu -services.users.ldap.password = serenata -services.users.ldap.usersDN = ou=users,dc=openaire,dc=eu - -services.validator.ldap.address = 194.177.192.119 -services.validator.ldap.port = 389 -services.validator.ldap.username = cn=admin,dc=openaire,dc=eu -services.validator.ldap.password = serenata -services.validator.ldap.usersDN = ou=users,dc=openaire,dc=eu +# +#services.users.ldap.address = 194.177.192.119 +#services.users.ldap.port = 389 +#services.users.ldap.username = cn=admin,dc=openaire,dc=eu +#services.users.ldap.password = serenata +#services.users.ldap.usersDN = ou=users,dc=openaire,dc=eu +# +#services.validator.ldap.address = 194.177.192.119 +#services.validator.ldap.port = 389 +#services.validator.ldap.username = cn=admin,dc=openaire,dc=eu +#services.validator.ldap.password = serenata +#services.validator.ldap.usersDN = ou=users,dc=openaire,dc=eu #AAI-REDIS -redis.host = estella.athenarc.gr +redis.host = localhost redis.port = 6379 -redis.password = redis123 +redis.password = 2106875370 -oidc.dev.home = http://localhost:8480/uoa-repository-manager-service/openid_connect_login -webapp.dev.front = http://localhost:4200/dashboard +oidc.dev.home = http://88.197.53.69/api/openid_connect_login +webapp.dev.front = http://88.197.53.69/join -repomanager.db.driverClassName=org.postgresql.Driver -repomanager.db.url=jdbc:postgresql://194.177.192.119:5432/repomanager -repomanager.db.username=dnet -repomanager.db.password=dnetPwd -infrastructure.name=integration +services.repomanager.db.driverClassName=org.postgresql.Driver +services.repomanager.db.url=jdbc:postgresql://localhost:5432/repomanager +services.repomanager.db.username=dnet +services.repomanager.db.password=dnetPwd +#infrastructure.name=integration + +#transport.soap.baseAddress=http://${container.hostname}:${container.port}/${container.context} +#transport.soap.force.local.address=false +#services.validator.mail.host=smtp.gmail.com +#services.validator.mail.port=465 +#services.validator.mail.fromAddress=no-reply@openaire.eu +#services.validator.mail.replyToAddress=no-reply@openaire.eu +#services.validator.mail.username=test.openaire@gmail.com +#services.validator.mail.password=^($*@$)*!$ +#services.validator.mail.authenticate=true +#services.validator.mail.override=false +#services.validator.mail.logonly=false +#services.validator.mail.mode=ssl +#services.validator.mail.debug=false +#services.validator.mail.overrideEmail=antleb@di.uoa.gr +#services.validator.mail.specialRecipients=antleb@di.uoa.gr +#services.validator.repoRegistration.override=antleb@di.uoa.gr -transport.soap.baseAddress=http://${container.hostname}:${container.port}/${container.context} -transport.soap.force.local.address=false -services.validator.mail.host=smtp.gmail.com -services.validator.mail.port=465 -services.validator.mail.fromAddress=no-reply@openaire.eu -services.validator.mail.replyToAddress=no-reply@openaire.eu -services.validator.mail.username=test.openaire@gmail.com -services.validator.mail.password=^($*@$)*!$ -services.validator.mail.authenticate=true -services.validator.mail.override=false -services.validator.mail.logonly=false -services.validator.mail.mode=ssl -services.validator.mail.debug=false -services.validator.mail.overrideEmail=antleb@di.uoa.gr -services.validator.mail.specialRecipients=antleb@di.uoa.gr -services.validator.repoRegistration.override=antleb@di.uoa.gr -oidc.issuer=https://aai.openaire.eu/oidc/ -oidc.id=767422b9-5461-4807-a80a-f9a2072d3a7d -oidc.secret=AMQtGlbTXNjwjhF0st28LmM6V0XypMdaVS7tJmGuYFlmH36iIv4t7tVqYuLYrNPkhnZ_GPUJvhymBhFupdgb6aU search.api.baseAddress=https://beta.services.openaire.eu/search/v2/api search.api.usagestats=https://services.openaire.eu/usagestats search.api.usageEvents=http://beta.lbs.openaire.eu:8080/ajax/summary api.baseAddress=http://beta.services.openaire.eu/openaire -services.repo-manager.baseUrl=http://${container.hostname}:${container.port}/${container.context} -services.repo-manager.adminEmail=antleb@di.uoa.gr -services.repo-manager.repository.testing.mode=false -services.repo-manager.deploy.environment=development +services.repomanager.baseUrl=http://${container.hostname}:${container.port}/${container.context} services.repomanager.usageStatisticsDiagramsBaseURL=https://beta.openaire.eu/stats3/ services.repomanager.usageStatisticsNumbersBaseURL=https://beta.services.openaire.eu/usagestats/datasources/ services.repomanager.usagestats.adminEmail=antleb@di.uoa.gr @@ -153,15 +85,29 @@ services.repomanager.usagestats.sushiliteEndpoint=http://beta.services.openaire. services.repomanager.analyticsURL=https://analytics.openaire.eu/addsite.php? aai.mode=develop + #uoa-repository-manager-service #oidc.dev.home=http://88.197.53.69:8080/uoa-repository-manager-service/openid_connect_login #webapp.dev.front=http://88.197.53.69/landing + services.repo-manager.adminEmail=antleb@di.uoa.gr services.repomanager.usagestats.adminEmail=antleb@di.uoa.gr -services.provide.adminEmail=antleb@di.uoa.gr +services.repomanager.provide.adminEmail=antleb@di.uoa.gr validator.results.url=https://beta.provide.openaire.eu/compatibility/browseHistory/ topic_types.url=https://beta.services.openaire.eu/provision/mvc/vocabularies/dnet:topic_types.json services.broker.url=http://broker1-dev-dnet.d4science.org services.broker.port=8080 services.broker.api=api/ services.broker.openaire=openaireBroker + +oidc.url.base=https://aai.openaire.eu +oidc.issuer=${oidc.url.base}/oidc/ + +aai.registry.url=${oidc.url.base}/registry/ +aai.registry.coid=2 +aai.registry.production=false +aai.registry.authentication.username=provide_openaire +aai.registry.authentication.password=u8WfYv2R^f#y7G98 + +oidc.id=767422b9-5461-4807-a80a-f9a2072d3a7d +oidc.secret=AMQtGlbTXNjwjhF0st28LmM6V0XypMdaVS7tJmGuYFlmH36iIv4t7tVqYuLYrNPkhnZ_GPUJvhymBhFupdgb6aU \ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml new file mode 100644 index 0000000..8229e3c --- /dev/null +++ b/src/main/resources/log4j2.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/main/webapp/WEB-INF/applicationContext.xml b/src/main/webapp/WEB-INF/applicationContext.xml index f6cc74e..b744c56 100644 --- a/src/main/webapp/WEB-INF/applicationContext.xml +++ b/src/main/webapp/WEB-INF/applicationContext.xml @@ -21,21 +21,6 @@ - - - - - - - - - - - - - - -