Compare commits

...

8 Commits

54 changed files with 819 additions and 935 deletions

30
README.md Normal file
View File

@ -0,0 +1,30 @@
# UOA Monitor Service
This service provides method in order to create templates and profiles for Monitor Dashboards.
Also includes notifications, admin-tools and stateless authorization.
## Configuration
- Check [Notification Service](https://code-repo.d4science.org/MaDgIK/uoa-notification-service)
- Check [Admin Tools Library](https://code-repo.d4science.org/MaDgIK/uoa-admin-tools-library)
### Mongo Configuration
monitor-service.mongodb.host # Required - Host of mongo server - Default: localhost
monitor-service.mongodb.database # Required - Database name
monitor-service.mongodb.username # Optional - Username if needed
monitor-service.mongodb.password # Optional - Password if needed
monitor-service.mongodb.port # Required - Mongo server port - Default: 27017
## Usage as dependency
<dependency>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-monitor-service</artifactId>
<version>2.0.0</version>
<classifier>library</classifier>
</dependency>
## Run
Check [Spring boot Documentation](https://code-repo.d4science.org/MaDgIK/Documentation/wiki/Spring-boot) (need Login)

61
pom.xml
View File

@ -1,20 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-spring-boot-parent</artifactId>
<version>2.0.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>uoa-monitor-service</artifactId>
<version>1.0.4-SNAPSHOT</version>
<version>2.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>uoa-monitor-service</name>
<scm>
<developerConnection>scm:git:gitea@code-repo.d4science.org:MaDgIK/uoa-monitor-service.git</developerConnection>
</scm>
<parent>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-spring-boot-parent</artifactId>
<version>1.0.0</version>
</parent>
<tag>HEAD</tag>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
@ -26,59 +25,30 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency> <!-- this dependency includes dependency to uoa-authorization-library -->
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-admin-tools-library</artifactId>
<version>1.0.13</version>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-notification-service</artifactId>
<version>1.0.7</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger-version}</version>
</dependency>
<!--swagger official ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger-version}</version>
<version>2.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-version}</version>
<configuration>
<mainClass>eu.dnetlib.uoamonitorservice.application.UoaMonitorServiceApplication</mainClass>
<executable>true</executable>
</configuration>
<executions>
<execution>
<id>default-war</id>
<phase>package</phase>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -94,20 +64,15 @@
<classifier>library</classifier>
<excludes>
<exclude>**/eu/dnetlib/uoamonitorservice/application/**</exclude>
<exclude>**/eu/dnetlib/uoamonitorservice/configuration/SwaggerConfig.class</exclude>
<exclude>**/eu/dnetlib/uoamonitorservice/controllers/MonitorServiceCheckDeployController.class</exclude>
</excludes>
<classesDirectory />
<outputDirectory />
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<finalName>uoa-monitor-service</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -2,27 +2,14 @@ package eu.dnetlib.uoamonitorservice;
import eu.dnetlib.uoaadmintoolslibrary.UoaAdminToolsLibraryConfiguration;
import eu.dnetlib.uoamonitorservice.configuration.GlobalVars;
import eu.dnetlib.uoamonitorservice.configuration.properties.APIProperties;
import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableConfigurationProperties({ MongoConfig.class, GlobalVars.class, APIProperties.class})
@ComponentScan(basePackages = { "eu.dnetlib.uoamonitorservice" })
@EnableConfigurationProperties({MongoConfig.class, GlobalVars.class})
@ComponentScan(basePackages = {"eu.dnetlib.uoamonitorservice"})
@Import({UoaAdminToolsLibraryConfiguration.class})
public class UoaMonitorServiceConfiguration extends WebMvcConfigurerAdapter {
private final Logger log = LogManager.getLogger(this.getClass());
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
public class UoaMonitorServiceConfiguration { }

View File

@ -1,8 +1,7 @@
package eu.dnetlib.uoamonitorservice.application;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
//import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {

View File

@ -1,6 +1,6 @@
package eu.dnetlib.uoamonitorservice.application;
import eu.dnetlib.uoaauthorizationlibrary.configuration.AuthorizationConfiguration;
import eu.dnetlib.uoaauthorizationlibrary.SecurityConfiguration;
import eu.dnetlib.uoanotificationservice.configuration.NotificationConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -19,7 +19,7 @@ import org.springframework.context.annotation.PropertySources;
})
@Import({
NotificationConfiguration.class,
AuthorizationConfiguration.class
SecurityConfiguration.class,
})
public class UoaMonitorServiceApplication {
public static void main(String[] args) {

View File

@ -4,7 +4,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Date;
@ConfigurationProperties("monitorservice.globalVars")
@ConfigurationProperties("monitor-service.global-vars")
public class GlobalVars {
public static Date date = new Date();
private Date buildDate;

View File

@ -1,118 +0,0 @@
package eu.dnetlib.uoamonitorservice.configuration;
import eu.dnetlib.uoamonitorservice.configuration.properties.APIProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Collections;
import java.util.List;
/**
* Swagger configuration class
*/
@Configuration
@Profile({"swagger"})
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
private final APIProperties apiProperties;
@Autowired
public SwaggerConfig(APIProperties apiProperties) {
this.apiProperties = apiProperties;
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("eu.dnetlib.uoamonitorservice.controllers"))
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket createRestApiLibrary() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("Library")
.select()
.apis(RequestHandlerSelectors.basePackage("eu.dnetlib.uoaadmintoolslibrary.controllers"))
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket createRestApiAuthorizationLibrary() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("Authorization Library")
.select()
.apis(RequestHandlerSelectors.basePackage("eu.dnetlib.uoaauthorizationlibrary.controllers"))
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket createRestApiNotificationLibrary() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("Notification Service")
.select()
.apis(RequestHandlerSelectors.basePackage("eu.dnetlib.uoanotificationservice.controllers"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(this.apiProperties.getTitle())
.description(this.apiProperties.getDescription())
.version(this.apiProperties.getVersion())
.build();
}
private List<Parameter> globalParameterList() {
Parameter authTokenHeader = new ParameterBuilder()
.name("Session") // name of the header
.modelRef(new ModelRef("string")) // data-type of the header
.required(false)
.parameterType("header")
.description("Session ID")
.build();
return Collections.singletonList(authTokenHeader);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/v2/api-docs", "/v2/api-docs");
registry.addRedirectViewController("/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
registry.addRedirectViewController("/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
registry.addRedirectViewController("/swagger-resources", "/swagger-resources");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html**").addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}

View File

@ -1,45 +1,50 @@
package eu.dnetlib.uoamonitorservice.configuration.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Collections;
@Configuration
@EnableMongoRepositories(basePackages = {"eu.dnetlib.uoamonitorservice.dao", "eu.dnetlib.uoaadmintoolslibrary.dao"})
@EnableMongoAuditing
public class MongoConnection {
@Autowired
private MongoConfig mongoConfig;
private final MongoConfig mongoConfig;
@Bean
@Primary
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(getMongoClient(), mongoConfig.getDatabase());
@Autowired
public MongoConnection(MongoConfig mongoConfig) {
this.mongoConfig = mongoConfig;
}
@Bean(name = "mongoTemplate")
@Primary
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(mongoDbFactory());
return new MongoTemplate(getMongoClient(), mongoConfig.getDatabase());
}
private MongoClient getMongoClient() {
if(mongoConfig.getUsername() != null && mongoConfig.getPassword() != null){
return new MongoClient(Collections.singletonList(
new ServerAddress(mongoConfig.getHost(), mongoConfig.getPort())),
Collections.singletonList(MongoCredential.createCredential(mongoConfig.getUsername(), mongoConfig.getDatabase(), mongoConfig.getPassword().toCharArray())));
} else {
return new MongoClient(Collections.singletonList(new ServerAddress(mongoConfig.getHost(), mongoConfig.getPort())));
MongoClientSettings.Builder builder = MongoClientSettings.builder()
.applyToClusterSettings(b -> b.hosts(Collections.singletonList(new ServerAddress(mongoConfig.getHost(), mongoConfig.getPort()))));
if(mongoConfig.getUsername() != null && mongoConfig.getPassword() != null) {
MongoCredential credential = MongoCredential.createCredential(
mongoConfig.getUsername(),
mongoConfig.getDatabase(),
mongoConfig.getPassword().toCharArray()
);
builder.credential(credential);
}
return MongoClients.create(builder.build());
}
}

View File

@ -1,38 +0,0 @@
package eu.dnetlib.uoamonitorservice.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("api")
public class APIProperties {
private String title;
private String description;
private String version;
public APIProperties() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}

View File

@ -2,14 +2,14 @@ package eu.dnetlib.uoamonitorservice.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("monitorservice.mongodb")
@ConfigurationProperties("monitor-service.mongodb")
public class MongoConfig {
private String host;
private String host = "localhost";
private String database;
private String username;
private String password;
private int port;
private int port = 27017;
public String getHost() {

View File

@ -11,13 +11,13 @@ import eu.dnetlib.uoamonitorservice.service.TopicService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class CategoryController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -34,9 +34,9 @@ public class CategoryController {
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/save", method = RequestMethod.POST)
public CategoryFull saveCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestBody CategoryFull categoryFull) {
public ResponseEntity<CategoryFull> saveCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestBody CategoryFull categoryFull) {
log.debug("save category");
log.debug("Alias: " + categoryFull.getAlias() + " - Id: " + categoryFull.getId() + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId);
Stakeholder stakeholder = stakeholderService.findByPath(stakeholderId);
@ -44,48 +44,48 @@ public class CategoryController {
if(categoryFull.getId() != null) {
this.categoryService.findByPath(topic, categoryFull.getId());
}
return this.categoryService.save(stakeholder, topic, new Category(categoryFull));
return ResponseEntity.ok(this.categoryService.save(stakeholder, topic, new Category(categoryFull)));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/delete", method = RequestMethod.DELETE)
public boolean deleteCategory(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<Boolean> deleteCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@RequestParam(required = false) String children) {
@RequestParam(required = false, name = "children") String children) {
log.debug("delete category");
log.debug("Id: " + categoryId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
this.categoryService.delete(stakeholder.getType(), category, true);
return true;
return ResponseEntity.ok(true);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/reorder", method = RequestMethod.POST)
public List<CategoryFull> reorderCategories(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<List<CategoryFull>> reorderCategories(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestBody List<String> categories) {
log.debug("reorder categories");
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId);
Stakeholder stakeholder = stakeholderService.findByPath(stakeholderId);
Topic topic = topicService.findByPath(stakeholder, topicId);
return this.topicService.reorderCategories(stakeholder, topic, categories).getCategories();
return ResponseEntity.ok(this.topicService.reorderCategories(stakeholder, topic, categories).getCategories());
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/change-visibility", method = RequestMethod.POST)
public CategoryFull changeCategoryVisibility(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<CategoryFull> changeCategoryVisibility(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false") Boolean propagate) {
@RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false", name = "propagate") Boolean propagate) {
log.debug("change category visibility: " + visibility + " - toggle propagate: " + propagate);
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Topic topic = this.topicService.findByPath(stakeholderService, stakeholderId, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
return this.categoryService.changeVisibility(stakeholder.getType(), stakeholder.getAlias(), category, visibility, propagate);
return ResponseEntity.ok(this.categoryService.changeVisibility(stakeholder, category, visibility, propagate));
}
}

View File

@ -1,13 +1,13 @@
package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoaadmintoolslibrary.emailSender.EmailSender;
import eu.dnetlib.uoaadmintoolslibrary.entities.email.Email;
import eu.dnetlib.uoaadmintoolslibrary.entities.email.EmailRecaptcha;
import eu.dnetlib.uoaadmintoolslibrary.handlers.InvalidReCaptchaException;
import eu.dnetlib.uoaadmintoolslibrary.recaptcha.VerifyRecaptcha;
import eu.dnetlib.uoaadmintoolslibrary.exceptions.InvalidReCaptchaException;
import eu.dnetlib.uoaadmintoolslibrary.services.EmailService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
@ -16,29 +16,25 @@ import java.util.Map;
import java.util.Optional;
@RestController
@CrossOrigin(origins = "*")
public class EmailController {
private final Logger log = LogManager.getLogger(this.getClass());
private final EmailSender emailSender;
private final VerifyRecaptcha verifyRecaptcha;
private final EmailService service;
@Autowired
public EmailController(EmailSender emailSender, VerifyRecaptcha verifyRecaptcha) {
this.emailSender = emailSender;
this.verifyRecaptcha = verifyRecaptcha;
public EmailController(EmailService service) {
this.service = service;
}
@RequestMapping(value = "/contact", method = RequestMethod.POST)
public Boolean contact(@RequestBody EmailRecaptcha form) throws InvalidReCaptchaException {
verifyRecaptcha.processResponse(form.getRecaptcha());
public ResponseEntity<Boolean> contact(@RequestBody EmailRecaptcha form) throws InvalidReCaptchaException {
this.service.processResponse(form.getRecaptcha());
Email email = form.getEmail();
return emailSender.send(email.getRecipients(), email.getSubject(), email.getBody(), false);
return ResponseEntity.ok(this.service.send(email.getRecipients(), email.getSubject(), email.getBody(), false));
}
@RequestMapping(value = "/sendMail", method = RequestMethod.POST)
public Map<String, ArrayList<String>> sendEmail(@RequestBody Email email,
@RequestParam(required = false) Optional<Boolean> optional) {
public ResponseEntity<Map<String, ArrayList<String>>> sendEmail(@RequestBody Email email,
@RequestParam(required = false, name = "optional") Optional<Boolean> optional) {
String successString = "success";
String failureString = "failure";
Map<String, ArrayList<String>> mailResults = new HashMap<>();
@ -46,7 +42,7 @@ public class EmailController {
for (String userMail : email.getRecipients()) {
ArrayList<String> sendTo = new ArrayList<>();
sendTo.add(userMail);
boolean success = emailSender.send(sendTo, email.getSubject(), email.getBody(), bcc);
boolean success = this.service.send(sendTo, email.getSubject(), email.getBody(), bcc);
if (success) {
if (!mailResults.containsKey(successString)) {
mailResults.put(successString, new ArrayList<>());
@ -59,8 +55,7 @@ public class EmailController {
mailResults.get(failureString).add(userMail);
}
}
return mailResults;
return ResponseEntity.ok(mailResults);
}
}
}

View File

@ -9,6 +9,7 @@ import eu.dnetlib.uoamonitorservice.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@ -16,7 +17,6 @@ import java.io.UnsupportedEncodingException;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class IndicatorController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -40,11 +40,11 @@ public class IndicatorController {
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/save-bulk", method = RequestMethod.POST)
public StakeholderFull saveBulkIndicators(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@RequestBody List<SectionFull> sections) throws UnsupportedEncodingException {
public ResponseEntity<StakeholderFull> saveBulkIndicators(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@RequestBody List<SectionFull> sections) throws UnsupportedEncodingException {
log.debug("save bulk indicators");
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
@ -52,12 +52,12 @@ public class IndicatorController {
Category category = this.categoryService.findByPath(topic, categoryId);
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
this.sectionService.saveBulk(stakeholder, subCategory, sections);
return this.stakeholderService.getFullStakeholder(stakeholder);
return ResponseEntity.ok(this.stakeholderService.getFullStakeholder(stakeholder));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/save", method = RequestMethod.POST)
public Indicator saveIndicator(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<Indicator> saveIndicator(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@ -73,18 +73,18 @@ public class IndicatorController {
if(indicator.getId() != null) {
this.indicatorService.findByPath(section, indicator.getId());
}
return this.indicatorService.save(stakeholder, section, indicator);
return ResponseEntity.ok(this.indicatorService.save(stakeholder, section, indicator));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/delete", method = RequestMethod.DELETE)
public boolean deleteIndicator(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<Boolean> deleteIndicator(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@PathVariable("sectionId") String sectionId,
@PathVariable("indicatorId") String indicatorId,
@RequestParam(required = false) String children) {
@RequestParam(required = false, name = "children") String children) {
log.debug("delete indicator");
log.debug("Id: " + indicatorId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId + " - Section: " + sectionId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
@ -94,13 +94,13 @@ public class IndicatorController {
Section section = this.sectionService.findByPath(subCategory, sectionId);
Indicator indicator = this.indicatorService.findByPath(section, indicatorId);
this.indicatorService.delete(stakeholder.getType(), indicator, true);
return true;
return ResponseEntity.ok(true);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/reorder", method = RequestMethod.POST)
public List<Indicator> reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<List<Indicator>> reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@ -112,12 +112,12 @@ public class IndicatorController {
Category category = this.categoryService.findByPath(topic, categoryId);
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
Section section = this.sectionService.findByPath(subCategory, sectionId);
return this.sectionService.reorderIndicators(stakeholder, section, indicators).getIndicators();
return ResponseEntity.ok(this.sectionService.reorderIndicators(stakeholder, section, indicators).getIndicators());
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/change-visibility", method = RequestMethod.POST)
public Indicator changeIndicatorVisibility(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<Indicator> changeIndicatorVisibility(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@ -127,11 +127,11 @@ public class IndicatorController {
log.debug("change indicator visibility: " + visibility);
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId + " - Section: " + sectionId + " - Indicator: " + indicatorId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Topic topic = this.topicService.findByPath(stakeholderService, stakeholderId, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
Section section = this.sectionService.findByPath(subCategory, sectionId);
Indicator indicator = this.indicatorService.findByPath(section, indicatorId);
return this.indicatorService.changeVisibility(stakeholder.getType(), stakeholder.getAlias(), indicator, visibility);
return ResponseEntity.ok(this.indicatorService.changeVisibility(stakeholder, indicator, visibility));
}
}

View File

@ -6,47 +6,38 @@ import eu.dnetlib.uoaadmintoolslibrary.services.PageService;
import eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
@RestController
@RequestMapping(value={"/monitor", "/funder", "/project", "/ri", "/organization"})
@CrossOrigin(origins = "*")
@RequestMapping(value={"/monitor", "/funder", "/project", "/ri", "/organization", "country", "researcher", "datasource", "publisher", "journal"})
public class MonitorController {
private final Logger log = LogManager.getLogger(this.getClass());
@Autowired
private PortalService portalService;
private final PortalService portalService;
@Autowired
private PageService pageService;
public MonitorController(PortalService portalService) {
this.portalService = portalService;
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public PortalResponse updatePortal(@RequestBody Portal portal) {
String old_pid = portalService.getPortalById(portal.getId()).getPid();
String new_pid = portal.getPid();
PortalResponse portalResponse = portalService.updatePortal(portal);
if (!old_pid.equals(new_pid)) {
pageService.updatePid(old_pid, new_pid, portal.getType());
}
return portalResponse;
public ResponseEntity<PortalResponse> updatePortal(@RequestBody Portal portal) {
return ResponseEntity.ok(portalService.updatePortal(portal));
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public PortalResponse insertPortal(@RequestBody Portal portal) {
PortalResponse portalResponse = portalService.insertPortal(portal);
return portalResponse;
public ResponseEntity<PortalResponse> insertPortal(@RequestBody Portal portal) {
return ResponseEntity.ok(portalService.insertPortal(portal));
}
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public Boolean deletePortals(@RequestBody List<String> portals) {
portals.forEach(id -> portalService.deletePortal(id));
return true;
public ResponseEntity<Boolean> deletePortals(@RequestBody List<String> portals) {
portals.forEach(portalService::deletePortal);
return ResponseEntity.ok(true);
}
}

View File

@ -3,8 +3,8 @@ package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoamonitorservice.service.MonitorDeployService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/monitor-library")
public class MonitorLibraryCheckDeployController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -23,15 +22,15 @@ public class MonitorLibraryCheckDeployController {
this.service = service;
}
@RequestMapping(value = {"", "/health_check"}, method = RequestMethod.GET)
public String hello() {
@RequestMapping(value = {"", "/", "/health_check"}, method = RequestMethod.GET)
public ResponseEntity<String> hello() {
log.debug("Hello from uoa-monitor-service library!");
return "Hello from uoa-monitor-service library!";
return ResponseEntity.ok("Hello from uoa-monitor-service library!");
}
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/health_check/advanced", method = RequestMethod.GET)
public Map<String, String> checkEverything() {
return this.service.checkEverything();
public ResponseEntity<Map<String, String>> checkEverything() {
return ResponseEntity.ok(this.service.getProperties());
}
}

View File

@ -3,8 +3,8 @@ package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoamonitorservice.service.MonitorDeployService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*")
public class MonitorServiceCheckDeployController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -22,15 +21,15 @@ public class MonitorServiceCheckDeployController {
this.service = service;
}
@RequestMapping(value = {"", "/health_check"}, method = RequestMethod.GET)
public String hello() {
@RequestMapping(value = {"", "/", "/health_check"}, method = RequestMethod.GET)
public ResponseEntity<String> hello() {
log.debug("Hello from uoa-monitor-service!");
return "Hello from uoa-monitor-service!";
return ResponseEntity.ok("Hello from uoa-monitor-service!");
}
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/health_check/advanced", method = RequestMethod.GET)
public Map<String, String> checkEverything() {
return this.service.checkEverything();
public ResponseEntity<Map<String, String>> checkEverything() {
return ResponseEntity.ok(this.service.getProperties());
}
}

View File

@ -9,13 +9,13 @@ import eu.dnetlib.uoamonitorservice.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class SectionController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -37,12 +37,12 @@ public class SectionController {
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/save/{index}", method = RequestMethod.POST)
public SectionFull saveSection(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@PathVariable("index") String index,
@RequestBody SectionFull sectionFull) {
public ResponseEntity<SectionFull> saveSection(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@PathVariable("index") String index,
@RequestBody SectionFull sectionFull) {
log.debug("save section");
log.debug("Name: " + sectionFull.getTitle() + " - Id: " + sectionFull.getId() + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
@ -52,17 +52,17 @@ public class SectionController {
if(sectionFull.getId() != null) {
this.sectionService.findByPath(subCategory, sectionFull.getId());
}
return this.sectionService.save(stakeholder, subCategory, new Section(sectionFull), Integer.parseInt(index));
return ResponseEntity.ok(this.sectionService.save(stakeholder, subCategory, new Section(sectionFull), Integer.parseInt(index)));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/delete", method = RequestMethod.DELETE)
public boolean deleteSection(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<Boolean> deleteSection(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@PathVariable("sectionId") String sectionId,
@RequestParam(required = false) String children) {
@RequestParam(required = false, name = "children") String children) {
log.debug("delete section");
log.debug("Id: " + sectionId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
@ -71,12 +71,12 @@ public class SectionController {
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
Section section = this.sectionService.findByPath(subCategory, sectionId);
this.sectionService.delete(stakeholder.getType(), section, true);
return true;
return ResponseEntity.ok(true);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/moveIndicator", method = RequestMethod.POST)
public SubCategoryFull moveIndicator(@PathVariable("stakeholderId") String stakeholderId,
public ResponseEntity<SubCategoryFull> moveIndicator(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@ -87,6 +87,6 @@ public class SectionController {
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
return this.subCategoryService.moveIndicator(stakeholder, subCategory, moveIndicator);
return ResponseEntity.ok(this.subCategoryService.moveIndicator(stakeholder, subCategory, moveIndicator));
}
}

View File

@ -2,11 +2,9 @@ package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
import eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
import eu.dnetlib.uoamonitorservice.dto.BuildStakeholder;
import eu.dnetlib.uoamonitorservice.dto.ManageStakeholders;
import eu.dnetlib.uoamonitorservice.dto.StakeholderFull;
import eu.dnetlib.uoamonitorservice.dto.UpdateUmbrella;
import eu.dnetlib.uoamonitorservice.dto.*;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.primitives.Umbrella;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import eu.dnetlib.uoamonitorservice.service.CommonService;
@ -14,13 +12,13 @@ import eu.dnetlib.uoamonitorservice.service.StakeholderService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class StakeholderController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -37,73 +35,75 @@ public class StakeholderController {
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/stakeholder/alias", method = RequestMethod.GET)
public List<String> getAllReservedStakeholderAlias(@RequestParam(required = false) String type) {
public ResponseEntity<List<String>> getAllReservedStakeholderAlias(@RequestParam(required = false, name = "type") String type) {
List<String> stakeholderAlias = this.stakeholderService.getAllAliases(type);
if(type == null ) {
stakeholderAlias.add("all");
stakeholderAlias.add("default");
stakeholderAlias.add("alias");
}
return stakeholderAlias;
return ResponseEntity.ok(stakeholderAlias);
}
@PreAuthorize("hasAnyAuthority(" +
"@AuthorizationService.PORTAL_ADMIN, " +
"@AuthorizationService.curator(#buildStakeholder.stakeholder.getType()))")
@RequestMapping(value = "/build-stakeholder", method = RequestMethod.POST)
public Stakeholder buildStakeholder(@RequestBody BuildStakeholder buildStakeholder) {
Stakeholder stakeholder = buildStakeholder.getStakeholder();
log.debug("build stakeholder");
log.debug("Alias: " + stakeholder.getAlias());
Portal portal = portalService.getPortal(stakeholder.getAlias());
if (portal == null) {
portal = new Portal();
portal.setPid(stakeholder.getAlias());
portal.setName(stakeholder.getName());
portal.setType(stakeholder.getType());
portalService.insertPortal(portal);
public ResponseEntity<?> buildStakeholder(@RequestBody BuildStakeholder buildStakeholder) {
log.debug("build stakeholders");
List<Stakeholder> stakeholders = this.stakeholderService.buildStakeholders(buildStakeholder);
log.debug("Alias: " + stakeholders.stream().map(Common::getAlias).toString());
stakeholders.forEach(stakeholder -> {
Portal portal = portalService.getPortal(stakeholder.getAlias());
if (portal == null) {
portal = new Portal();
portal.setPid(stakeholder.getAlias());
portal.setName(stakeholder.getName());
portal.setType(stakeholder.getType());
portalService.insertPortal(portal);
}
});
if(stakeholders.size() == 1) {
return ResponseEntity.ok(stakeholders.get(0));
} else {
return ResponseEntity.ok(stakeholders);
}
stakeholder.setStandalone(buildStakeholder.isStandalone());
if (buildStakeholder.isUmbrella()) {
stakeholder.setUmbrella(new Umbrella<>());
}
return this.stakeholderService.buildStakeholder(stakeholder, buildStakeholder.getCopyId());
}
@PreAuthorize("hasAnyAuthority(" + "@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/stakeholder/all", method = RequestMethod.GET)
public List<Stakeholder> getAllStakeholders(@RequestParam(required = false) String type) {
return this.stakeholderService.getAll(type);
public ResponseEntity<List<Stakeholder>> getAllStakeholders(@RequestParam(required = false, name = "type") String type) {
return ResponseEntity.ok(this.stakeholderService.getAll(type));
}
@RequestMapping(value = "/stakeholder", method = RequestMethod.GET)
public List<Stakeholder> getVisibleStakeholders(@RequestParam(required = false) String type,
@RequestParam(required = false) String defaultId) {
return stakeholderService.getVisibleStakeholders(type, defaultId);
public ResponseEntity<List<Stakeholder>> getVisibleStakeholders(@RequestParam(required = false, name = "type") String type,
@RequestParam(required = false, name = "defaultId") String defaultId) {
return ResponseEntity.ok(stakeholderService.getVisibleStakeholders(type, defaultId));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/my-stakeholder", method = RequestMethod.GET)
public ManageStakeholders getManagedStakeholders(@RequestParam(required = false) String type) {
return stakeholderService.getManageStakeholders(type);
public ResponseEntity<ManageStakeholders> getManagedStakeholders(@RequestParam(required = false, name = "type") String type) {
return ResponseEntity.ok(stakeholderService.getManageStakeholders(type));
}
@RequestMapping(value = "/stakeholder/{alias:.+}", method = RequestMethod.GET)
public StakeholderFull getStakeholder(@PathVariable("alias") String alias) {
public ResponseEntity<StakeholderFull> getStakeholder(@PathVariable("alias") String alias) {
StakeholderFull stakeholder = this.stakeholderService.getFullStakeholder(this.stakeholderService.findByAlias(alias));
if (stakeholder == null) {
this.commonService.unauthorized("Get stakeholder: You are not authorized to access stakeholder with alias: " + alias);
}
return stakeholder;
return ResponseEntity.ok(stakeholder);
}
@RequestMapping(value = "/stakeholder/{parent:.+}/{type}/{child:.+}", method = RequestMethod.GET)
public StakeholderFull getStakeholderWithParent(@PathVariable("parent") String parent, @PathVariable("type") String type, @PathVariable("child") String child) {
public ResponseEntity<StakeholderFull> getStakeholderWithParent(@PathVariable("parent") String parent, @PathVariable("type") String type, @PathVariable("child") String child) {
StakeholderFull stakeholder = this.stakeholderService.getFullStakeholderWithParents(this.stakeholderService.findByAlias(child), type, parent);
if (stakeholder == null) {
this.commonService.unauthorized("Get stakeholder: You are not authorized to access stakeholder with alias: " + child);
}
return stakeholder;
return ResponseEntity.ok(stakeholder);
}
@ -113,10 +113,10 @@ public class StakeholderController {
+ "@AuthorizationService.manager(#stakeholder.getType(), #stakeholder.getAlias()) "
+ ")")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Stakeholder saveStakeholder(@RequestBody Stakeholder stakeholder) {
public ResponseEntity<Stakeholder> saveStakeholder(@RequestBody Stakeholder stakeholder) {
log.debug("save stakeholder");
log.debug("Alias: " + stakeholder.getAlias() + " - Id: " + stakeholder.getId());
return this.stakeholderService.save(stakeholder);
return ResponseEntity.ok(this.stakeholderService.save(stakeholder));
}
@PreAuthorize("hasAnyAuthority("
@ -125,40 +125,40 @@ public class StakeholderController {
+ "@AuthorizationService.manager(#stakeholder.getType(), #stakeholder.getAlias()) "
+ ")")
@RequestMapping(value = "/save/full", method = RequestMethod.POST)
public StakeholderFull saveStakeholderFull(@RequestBody StakeholderFull stakeholder) {
public ResponseEntity<StakeholderFull> saveStakeholderFull(@RequestBody StakeholderFull stakeholder) {
log.debug("save stakeholder");
log.debug("Alias: " + stakeholder.getAlias() + " - Id: " + stakeholder.getId());
return this.stakeholderService.getFullStakeholder(this.stakeholderService.save(new Stakeholder(stakeholder, this.stakeholderService)));
return ResponseEntity.ok(this.stakeholderService.getFullStakeholder(this.stakeholderService.save(new Stakeholder(stakeholder, this.stakeholderService))));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/delete", method = RequestMethod.DELETE)
public boolean deleteStakeholder(@PathVariable("stakeholderId") String id) {
public ResponseEntity<Boolean> deleteStakeholder(@PathVariable("stakeholderId") String id) {
log.debug("delete stakeholder");
log.debug("Id: " + id);
Portal portal = portalService.getPortal(this.stakeholderService.delete(id));
if (portal != null) {
portalService.deletePortal(portal.getId());
}
return true;
return ResponseEntity.ok(true);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/change-visibility", method = RequestMethod.POST)
public StakeholderFull changeStakeholderVisibility(@PathVariable("stakeholderId") String stakeholderId,
@RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false") Boolean propagate) {
public ResponseEntity<StakeholderFull> changeStakeholderVisibility(@PathVariable("stakeholderId") String stakeholderId,
@RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false", name = "propagate") Boolean propagate) {
log.debug("change stakeholder visibility: " + visibility + " - toggle propagate: " + propagate);
log.debug("Stakeholder: " + stakeholderId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
return this.stakeholderService.changeVisibility(stakeholder, visibility, propagate);
return ResponseEntity.ok(this.stakeholderService.changeVisibility(stakeholder, visibility, propagate));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/umbrella", method = RequestMethod.POST)
public Umbrella<Stakeholder> updateUmbrella(@PathVariable("stakeholderId") String stakeholderId, @RequestBody UpdateUmbrella update) {
public ResponseEntity<Umbrella<Stakeholder>> updateUmbrella(@PathVariable("stakeholderId") String stakeholderId, @RequestBody UpdateUmbrella update) {
log.debug("update stakeholder umbrella");
log.debug("Stakeholder: " + stakeholderId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
return this.stakeholderService.updateUmbrella(stakeholder, update);
return ResponseEntity.ok(this.stakeholderService.updateUmbrella(stakeholder, update));
}
}

View File

@ -13,13 +13,13 @@ import eu.dnetlib.uoamonitorservice.service.TopicService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class SubCategoryController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -38,28 +38,28 @@ public class SubCategoryController {
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/save", method = RequestMethod.POST)
public SubCategoryFull saveSubCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@RequestBody SubCategoryFull subcategoryFull) {
public ResponseEntity<SubCategoryFull> saveSubCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@RequestBody SubCategoryFull subcategoryFull) {
log.debug("save subcategory");
log.debug("Alias: " + subcategoryFull.getAlias() + " - Id: " + subcategoryFull.getId() + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
if(subcategoryFull.getId() != null) {
if (subcategoryFull.getId() != null) {
this.subCategoryService.findByPath(category, subcategoryFull.getId());
}
return this.subCategoryService.save(stakeholder, category, new SubCategory(subcategoryFull));
return ResponseEntity.ok(this.subCategoryService.save(stakeholder, category, new SubCategory(subcategoryFull)));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/delete", method = RequestMethod.DELETE)
public boolean deleteSubCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@RequestParam(required = false) String children) {
public ResponseEntity<Boolean> deleteSubCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@RequestParam(required = false, name = "children") String children) {
log.debug("delete subcategory");
log.debug("Id: " + subcategoryId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
@ -67,37 +67,37 @@ public class SubCategoryController {
Category category = this.categoryService.findByPath(topic, categoryId);
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
this.subCategoryService.delete(stakeholder.getType(), subCategory, true);
return true;
return ResponseEntity.ok(true);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/reorder", method = RequestMethod.POST)
public List<SubCategoryFull> reorderSubCategories(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@RequestBody List<String> subCategories) {
public ResponseEntity<List<SubCategoryFull>> reorderSubCategories(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@RequestBody List<String> subCategories) {
log.debug("reorder subCategories");
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
return this.categoryService.reorderSubCategories(stakeholder, category, subCategories).getSubCategories();
return ResponseEntity.ok(this.categoryService.reorderSubCategories(stakeholder, category, subCategories).getSubCategories());
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/change-visibility", method = RequestMethod.POST)
public SubCategoryFull changeSubCategoryVisibility(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@RequestParam("visibility") Visibility visibility,
@RequestParam(defaultValue = "false") Boolean propagate) {
public ResponseEntity<SubCategoryFull> changeSubCategoryVisibility(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@RequestParam("visibility") Visibility visibility,
@RequestParam(defaultValue = "false", name = "propagate") Boolean propagate) {
log.debug("change subCategory visibility: " + visibility + " - toggle propagate: " + propagate);
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
Topic topic = this.topicService.findByPath(stakeholderService, stakeholderId, topicId);
Category category = this.categoryService.findByPath(topic, categoryId);
SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
return this.subCategoryService.changeVisibility(stakeholder.getType(), stakeholder.getAlias(), subCategory, visibility, propagate);
return ResponseEntity.ok(this.subCategoryService.changeVisibility(stakeholder, subCategory, visibility, propagate));
}
}

View File

@ -3,19 +3,20 @@ package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoamonitorservice.dto.TopicFull;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.entities.Topic;
import eu.dnetlib.uoamonitorservice.handlers.BadRequestException;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import eu.dnetlib.uoamonitorservice.service.StakeholderService;
import eu.dnetlib.uoamonitorservice.service.TopicService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class TopicController {
private final Logger log = LogManager.getLogger(this.getClass());
@ -30,49 +31,49 @@ public class TopicController {
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/save", method = RequestMethod.POST)
public TopicFull saveTopic(@PathVariable("stakeholderId") String stakeholderId, @RequestBody TopicFull topicFull) {
public ResponseEntity<TopicFull> saveTopic(@PathVariable("stakeholderId") String stakeholderId, @RequestBody TopicFull topicFull) {
log.debug("save topic");
log.debug("Alias: " + topicFull.getAlias() + " - Id: " + topicFull.getId() + " - Stakeholder: " + stakeholderId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
if(topicFull.getId() != null) {
if (topicFull.getId() != null) {
this.topicService.findByPath(stakeholder, topicFull.getId());
}
return this.topicService.save(stakeholder, new Topic(topicFull));
return ResponseEntity.ok(this.topicService.save(stakeholder, new Topic(topicFull)));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/delete", method = RequestMethod.DELETE)
public boolean deleteTopic(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestParam(required = false) String children) {
public ResponseEntity<Boolean> deleteTopic(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestParam(required = false, name = "children") String children) {
log.debug("delete topic");
log.debug("Id: " + topicId + " - Stakeholder: " + stakeholderId);
Stakeholder stakeholder = stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
this.topicService.delete(stakeholder.getType(), topic, true);
return true;
return ResponseEntity.ok(true);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/reorder", method = RequestMethod.POST)
public List<TopicFull> reorderTopics(@PathVariable("stakeholderId") String stakeholderId,
@RequestBody List<String> topics) {
public ResponseEntity<List<TopicFull>> reorderTopics(@PathVariable("stakeholderId") String stakeholderId,
@RequestBody List<String> topics) {
log.debug("reorder topics");
log.debug("Stakeholder: " + stakeholderId);
Stakeholder stakeholder = stakeholderService.findByPath(stakeholderId);
return this.stakeholderService.reorderTopics(stakeholder, topics).getTopics();
return ResponseEntity.ok(this.stakeholderService.reorderTopics(stakeholder, topics).getTopics());
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/change-visibility", method = RequestMethod.POST)
public TopicFull changeTopicVisibility(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false") Boolean propagate) {
public ResponseEntity<TopicFull> changeTopicVisibility(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false", name = "propagate") Boolean propagate) {
log.debug("change topic visibility: " + visibility + " - toggle propagate: " + propagate);
log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId);
Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholder, topicId);
return this.topicService.changeVisibility(stakeholder.getType(), stakeholder.getAlias(), topic, visibility, propagate);
Stakeholder stakeholder = stakeholderService.findByPath(stakeholderId);
Topic topic = this.topicService.findByPath(stakeholderService, stakeholderId, topicId);
return ResponseEntity.ok(this.topicService.changeVisibility(stakeholder, topic, visibility, propagate));
}
}

View File

@ -4,19 +4,15 @@ import eu.dnetlib.uoamonitorservice.entities.Category;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Repository
public interface CategoryDAO extends MongoRepository<Category, String> {
List<Category> findAll();
List<Category> findByDefaultId(String DefaultId);
<T> List<Category> findBySubCategoriesContaining(List<T> subCategories);
List<Category> findBySubCategoriesContaining(String subCategory);
Optional<Category> findById(String Id);
void delete(String Id);
Category save(Category category);
default List<Category> findBySubCategory(String subCategory) {
return findBySubCategoriesContaining(Collections.singletonList(subCategory));
}
}

View File

@ -9,13 +9,5 @@ import java.util.Optional;
@Repository
public interface IndicatorDAO extends MongoRepository<Indicator, String> {
List<Indicator> findAll();
List<Indicator> findByDefaultId(String DefaultId);
Optional<Indicator> findById(String Id);
void delete(String Id);
Indicator save(Indicator indicator);
//List<Indicator> saveAll(List<Indicator> indicators);
}

View File

@ -4,18 +4,16 @@ import eu.dnetlib.uoamonitorservice.entities.Section;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Repository
public interface SectionDAO extends MongoRepository<Section, String> {
List<Section> findAll();
List<Section> findByDefaultId(String DefaultId);
List<Section> findByIndicatorsContaining(String id);
<T> List<Section> findByIndicatorsContaining(List<T> indicators);
Optional<Section> findById(String Id);
void delete(String Id);
Section save(Section indicator);
default List<Section> findByIndicator(String indicator) {
return findByIndicatorsContaining(Collections.singletonList(indicator));
}
}

View File

@ -5,6 +5,7 @@ import eu.dnetlib.uoamonitorservice.primitives.StakeholderType;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@ -13,8 +14,6 @@ public interface StakeholderDAO extends MongoRepository<Stakeholder, String> {
/**
* All Stakeholders
*/
List<Stakeholder> findAll();
List<Stakeholder> findByDefaultId(String id);
List<Stakeholder> findByType(StakeholderType Type);
@ -182,17 +181,11 @@ public interface StakeholderDAO extends MongoRepository<Stakeholder, String> {
/**
* Other method
*/
List<Stakeholder> findByDefaultIdAndCopyIsTrue(String defaultId);
List<Stakeholder> findByTopicsContaining(String topic);
Optional<Stakeholder> findById(String id);
Optional<Stakeholder> findByAlias(String alias);
<T> List<Stakeholder> findByTopicsContaining(List<T> topics);
void delete(String Id);
Stakeholder save(Stakeholder stakeholder);
default List<Stakeholder> findByTopic(String topic) {
return this.findByTopicsContaining(Collections.singletonList(topic));
}
}

View File

@ -4,19 +4,21 @@ import eu.dnetlib.uoamonitorservice.entities.SubCategory;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Repository
public interface SubCategoryDAO extends MongoRepository<SubCategory, String> {
List<SubCategory> findAll();
List<SubCategory> findByDefaultId(String defaultId);
List<SubCategory> findByNumbersContaining(String id);
List<SubCategory> findByChartsContaining(String id);
<T> List<SubCategory> findByNumbersContaining(List<T> numbers);
Optional<SubCategory> findById(String Id);
default List<SubCategory> findByNumber(String number) {
return findByNumbersContaining(Collections.singletonList(number));
}
void delete(String Id);
<T> List<SubCategory> findByChartsContaining(List<T> charts);
SubCategory save(SubCategory subCategory);
default List<SubCategory> findByChart(String chart) {
return findByChartsContaining(Collections.singletonList(chart));
}
}

View File

@ -4,19 +4,15 @@ import eu.dnetlib.uoamonitorservice.entities.Topic;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Repository
public interface TopicDAO extends MongoRepository<Topic, String> {
List<Topic> findAll();
List<Topic> findByDefaultId(String DefaultId);
<T> List<Topic> findByCategoriesContaining(List<T> categories);
List<Topic> findByCategoriesContaining(String category);
Optional<Topic> findById(String Id);
void delete(String Id);
Topic save(Topic topic);
default List<Topic> findByCategory(String category) {
return findByCategoriesContaining(Collections.singletonList(category));
}
}

View File

@ -2,11 +2,15 @@ package eu.dnetlib.uoamonitorservice.dto;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import java.util.List;
import java.util.Map;
public class BuildStakeholder {
private Stakeholder stakeholder;
private String copyId;
private boolean umbrella = false;
private boolean standalone = true;
private List<Map<String, String>> indexFields;
public BuildStakeholder() {
}
@ -42,4 +46,17 @@ public class BuildStakeholder {
public void setStandalone(boolean standalone) {
this.standalone = standalone;
}
public List<Map<String, String>> getIndexFields() {
return indexFields;
}
public void setIndexFields(List<Map<String, String>> indexFields) {
this.indexFields = indexFields;
}
public boolean isMultiBuild() {
return this.indexFields != null && !this.indexFields.isEmpty();
}
}

View File

@ -3,7 +3,6 @@ package eu.dnetlib.uoamonitorservice.dto;
import eu.dnetlib.uoamonitorservice.entities.Indicator;
import eu.dnetlib.uoamonitorservice.entities.Section;
import eu.dnetlib.uoamonitorservice.generics.SectionGeneric;
import io.swagger.models.auth.In;
import java.util.List;
import java.util.Objects;

View File

@ -20,6 +20,7 @@ public class StakeholderFull extends StakeholderGeneric<TopicFull, Stakeholder>
topics.removeIf(Objects::isNull);
this.topics = topics;
this.setUmbrella(umbrella);
this.setOverride(!stakeholder.getOverrides().isEmpty());
}
public List<Stakeholder> getOtherParents() {

View File

@ -3,7 +3,6 @@ package eu.dnetlib.uoamonitorservice.entities;
import eu.dnetlib.uoamonitorservice.dto.CategoryFull;
import eu.dnetlib.uoamonitorservice.generics.CategoryGeneric;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.generics.TopicGeneric;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;

View File

@ -15,17 +15,13 @@ public class Indicator extends Common {
private List<String> tags; // this field is not used anywhere now
private List<IndicatorPath> indicatorPaths;
public Indicator() {}
public Indicator() {
super();
}
public Indicator(Indicator indicator) {
id = indicator.getId();
defaultId = indicator.getDefaultId();
name = indicator.getName();
description = indicator.getDescription();
super(indicator);
additionalDescription = indicator.getAdditionalDescription();
creationDate = indicator.getCreationDate();
updateDate = indicator.getUpdateDate();
visibility = indicator.getVisibility();
indicatorPaths = indicator.getIndicatorPaths();
tags = indicator.getTags();
setType(indicator.getType());

View File

@ -1,15 +1,11 @@
package eu.dnetlib.uoamonitorservice.entities;
import eu.dnetlib.uoamonitorservice.dto.StakeholderFull;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.generics.StakeholderGeneric;
import eu.dnetlib.uoamonitorservice.primitives.Umbrella;
import eu.dnetlib.uoamonitorservice.handlers.BadRequestException;
import eu.dnetlib.uoamonitorservice.service.StakeholderService;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Objects;
import java.util.stream.Collectors;
@Document
public class Stakeholder extends StakeholderGeneric<String, String> {
@ -37,4 +33,13 @@ public class Stakeholder extends StakeholderGeneric<String, String> {
public void removeTopic(String id) {
this.topics.remove(id);
}
public Stakeholder validate() {
if(this.getIndex_id() == null || this.getIndex_id().isEmpty()) {
throw new BadRequestException("index_id cannot be null or empty");
} else if(this.getIndex_name() == null || this.getIndex_name().isEmpty()) {
throw new BadRequestException("index_name cannot be null or empty");
}
return this;
}
}

View File

@ -40,12 +40,7 @@ public class Topic extends TopicGeneric<String> {
}
public Topic override(Topic topic, Topic old) {
topic = (Topic) super.override(topic, old);
if(this.getIcon() != null && !this.getIcon().equals(topic.getIcon()) &&
(old.getIcon() == null || old.getIcon().equals(topic.getIcon()))) {
topic.setIcon(this.getIcon());
}
return topic;
return (Topic) super.override(topic, old);
}
public void addCategory(String id) {

View File

@ -1,38 +1,18 @@
package eu.dnetlib.uoamonitorservice.generics;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;
import java.util.List;
@Document
public class CategoryGeneric<T> extends Common {
protected boolean isOverview;
protected List<T> subCategories;
public CategoryGeneric() {}
public CategoryGeneric(CategoryGeneric category) {
id = category.getId();
name = category.getName();
alias = category.getAlias();
description = category.getDescription();
setVisibility(category.getVisibility());
creationDate = category.getCreationDate();
updateDate = category.getUpdateDate();
defaultId = category.getDefaultId();
isOverview = category.getIsOverview();
super(category);
subCategories = new ArrayList<>();
}
public boolean getIsOverview() {
return isOverview;
}
public void setIsOverview(boolean isOverview) {
this.isOverview = isOverview;
}
public List<T> getSubCategories() {
return subCategories;
}

View File

@ -1,12 +1,18 @@
package eu.dnetlib.uoamonitorservice.generics;
import com.fasterxml.jackson.annotation.JsonProperty;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import eu.dnetlib.uoamonitorservice.utils.GenericAccessor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.annotation.Transient;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
public class Common {
@Id
@ -20,7 +26,25 @@ public class Common {
protected String name;
protected String description;
protected String alias;
protected Visibility visibility = Visibility.PRIVATE;
protected String icon;
protected Visibility visibility;
@Transient
protected boolean override;
protected Common() {}
protected Common(Common common) {
this.id = common.getId();
this.creationDate = common.getCreationDate();
this.updateDate = common.getUpdateDate();
this.defaultId = common.getDefaultId();
this.name = common.getName();
this.description = common.getDescription();
this.alias = common.getAlias();
this.icon = common.getIcon();
this.setVisibility(common.getVisibility());
this.override = common.isOverride();
}
public void update(Common common) {
this.id = common.getId();
@ -38,6 +62,10 @@ public class Common {
(old.getDescription() == null || old.getDescription().equals(common.getDescription()))) {
common.setDescription(this.getDescription());
}
if(this.getIcon() != null && !this.getIcon().equals(common.getIcon()) &&
(old.getIcon() == null || old.getIcon().equals(common.getIcon()))) {
common.setIcon(this.getIcon());
}
return common;
}
@ -97,6 +125,14 @@ public class Common {
this.alias = alias;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Visibility getVisibility() {
return visibility;
}
@ -104,4 +140,20 @@ public class Common {
public void setVisibility(Visibility visibility) {
this.visibility = visibility;
}
public void override(Stakeholder stakeholder) {
Map<String, Object> override = stakeholder.getOverride(this.id);
this.override = !override.isEmpty();
override.forEach((field, value) -> {
GenericAccessor.setField(this, field, value);
});
}
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
}

View File

@ -15,13 +15,10 @@ public class SectionGeneric<T> extends Common {
}
public SectionGeneric(SectionGeneric section) {
id = section.getId();
super(section);
title = section.getTitle();
defaultId = section.getDefaultId();
stakeholderAlias = section.getStakeholderAlias();
setType(section.getType());
creationDate = section.getCreationDate();
updateDate = section.getUpdateDate();
indicators = new ArrayList<>();
}

View File

@ -5,10 +5,7 @@ import eu.dnetlib.uoamonitorservice.primitives.Locale;
import eu.dnetlib.uoamonitorservice.primitives.StakeholderType;
import eu.dnetlib.uoamonitorservice.primitives.Umbrella;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.*;
public class StakeholderGeneric<T, S> extends Common {
protected StakeholderType type;
@ -25,12 +22,13 @@ public class StakeholderGeneric<T, S> extends Common {
protected Boolean copy;
protected List<T> topics = new ArrayList<>();
protected Umbrella<S> umbrella;
protected Map<String, Map<String, Object>> overrides;
public StakeholderGeneric() {
}
public StakeholderGeneric(StakeholderGeneric stakeholder) {
id = stakeholder.getId();
super(stakeholder);
setType(stakeholder.getType());
projectUpdateDate = stakeholder.getProjectUpdateDate();
index_id = stakeholder.getIndex_id();
@ -39,17 +37,13 @@ public class StakeholderGeneric<T, S> extends Common {
statsProfile = stakeholder.getStatsProfile();
logoUrl = stakeholder.getLogoUrl();
isUpload = stakeholder.getIsUpload();
name = stakeholder.getName();
alias = stakeholder.getAlias();
description = stakeholder.getDescription();
defaultId = stakeholder.getDefaultId();
setLocale(stakeholder.getLocale());
setVisibility(stakeholder.getVisibility());
this.funderType = stakeholder.getFunderType();
this.copy = stakeholder.isCopy();
this.standalone = stakeholder.isStandalone();
creationDate = stakeholder.getCreationDate();
updateDate = stakeholder.getUpdateDate();
funderType = stakeholder.getFunderType();
copy = stakeholder.isCopy();
if(!copy) {
this.overrides = new HashMap<>();
}
standalone = stakeholder.isStandalone();
}
public String getType() {
@ -159,6 +153,14 @@ public class StakeholderGeneric<T, S> extends Common {
return copy;
}
public boolean isReference() {
return !this.copy && this.defaultId != null;
}
public boolean isDefault() {
return !this.copy && this.defaultId == null;
}
public void setCopy(boolean copy) {
this.copy = copy;
}
@ -171,6 +173,15 @@ public class StakeholderGeneric<T, S> extends Common {
this.topics = topics;
}
@JsonIgnore
public Map<String, Map<String, Object>> getOverrides() {
return overrides;
}
public void setOverrides(Map<String, Map<String, Object>> overrides) {
this.overrides = overrides;
}
public Umbrella<S> getUmbrella() {
return umbrella;
}
@ -183,4 +194,25 @@ public class StakeholderGeneric<T, S> extends Common {
public void setUmbrella(Umbrella<S> umbrella) {
this.umbrella =umbrella;
}
public Map<String, Object> getOverride(String id) {
if(this.overrides == null) {
this.overrides = new HashMap<>();
}
return this.overrides.getOrDefault(id, new HashMap<>());
}
public <V> void setOverride(String id, String field, V value) {
if(!this.copy && this.defaultId != null) {
Map<String, Object> override = this.getOverride(id);
override.put(field, value);
this.overrides.put(id, override);
}
}
public void removeOverride(String id) {
if(this.overrides != null) {
this.overrides.remove(id);
}
}
}

View File

@ -9,14 +9,7 @@ public class SubCategoryGeneric<T> extends Common {
public SubCategoryGeneric() {}
public SubCategoryGeneric(SubCategoryGeneric subCategory) {
id = subCategory.getId();
name = subCategory.getName();
alias = subCategory.getAlias();
description = subCategory.getDescription();
setVisibility(subCategory.getVisibility());
creationDate = subCategory.getCreationDate();
updateDate = subCategory.getUpdateDate();
defaultId = subCategory.getDefaultId();
super(subCategory);
numbers = new ArrayList<>();
charts = new ArrayList<>();
}

View File

@ -4,34 +4,16 @@ import java.util.ArrayList;
import java.util.List;
public class TopicGeneric<T> extends Common {
protected String icon;
protected List<T> categories;
public TopicGeneric() {
}
public TopicGeneric(TopicGeneric topic) {
id = topic.getId();
name = topic.getName();
alias = topic.getAlias();
description = topic.getDescription();
icon = topic.getIcon();
setVisibility(topic.getVisibility());
creationDate = topic.getCreationDate();
updateDate = topic.getUpdateDate();
defaultId = topic.getDefaultId();
super(topic);
categories = new ArrayList<>();
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public List<T> getCategories() {
return categories;
}

View File

@ -1,11 +1,11 @@
package eu.dnetlib.uoamonitorservice.handlers;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.HttpException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message){
super(message);
public class BadRequestException extends HttpException {
public BadRequestException(String message) {
super(message, HttpStatus.BAD_REQUEST);
}
}

View File

@ -1,11 +0,0 @@
package eu.dnetlib.uoamonitorservice.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(String message){
super(message);
}
}

View File

@ -1,50 +0,0 @@
package eu.dnetlib.uoamonitorservice.handlers;
import eu.dnetlib.uoaadmintoolslibrary.responses.ExceptionResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
@ControllerAdvice
@RestController
public class ExceptionsHandler {
private final Logger log = LogManager.getLogger(this.getClass());
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<ExceptionResponse> entityNotFoundException(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("Not found Exception");
response.setErrorMessage("Entity not found Exception");
response.setErrors(ex.getMessage());
response.setStatus(HttpStatus.NOT_FOUND);
log.error("entityNotFoundException exception : "+ ex.getMessage());
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ExceptionResponse> conflictException(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("Not found Exception");
response.setErrorMessage("Conflict Exception");
response.setErrors(ex.getMessage());
response.setStatus(HttpStatus.BAD_REQUEST);
log.error("conflictException exception : "+ ex.getMessage());
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(PathNotValidException.class)
public ResponseEntity<ExceptionResponse> pathNotValidException(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("Not found Exception");
response.setErrorMessage("Path not valid Exception");
response.setErrors(ex.getMessage());
response.setStatus(HttpStatus.NOT_FOUND);
log.error("pathNotValidException exception : "+ ex.getMessage());
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.NOT_FOUND);
}
}

View File

@ -1,11 +1,10 @@
package eu.dnetlib.uoamonitorservice.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class PathNotValidException extends RuntimeException {
public PathNotValidException(String message){
public class PathNotValidException extends NotFoundException {
public PathNotValidException(String message) {
super(message);
}
}

View File

@ -1,14 +1,15 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
import eu.dnetlib.uoamonitorservice.dao.CategoryDAO;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.dao.TopicDAO;
import eu.dnetlib.uoamonitorservice.dto.CategoryFull;
import eu.dnetlib.uoamonitorservice.dto.TopicFull;
import eu.dnetlib.uoamonitorservice.entities.Category;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.entities.Topic;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import org.springframework.beans.factory.annotation.Autowired;
@ -38,29 +39,30 @@ public class CategoryService {
}
public Category find(String id) {
return dao.findById(id).orElseThrow(() -> new EntityNotFoundException("Category with id: " + id + " not found"));
return dao.findById(id).orElseThrow(() -> new NotFoundException("Category with id: " + id + " not found"));
}
public Category findByPath(Topic topic, String categoryId) {
if (!topic.getCategories().contains(categoryId)) {
throw new PathNotValidException("Category with id: " + categoryId + " not found in Topic: " + topic.getId());
}
return this.dao.findById(categoryId).orElseThrow(() -> new EntityNotFoundException("Category with id: " + categoryId + " not found"));
return this.dao.findById(categoryId).orElseThrow(() -> new NotFoundException("Category with id: " + categoryId + " not found"));
}
public CategoryFull getFullCategory(String type, String alias, Category category) {
if (commonService.hasVisibilityAuthority(type, alias, category)) {
public CategoryFull getFullCategory(Stakeholder stakeholder, Category category) {
category.override(stakeholder);
if (commonService.hasVisibilityAuthority(stakeholder.getType(), stakeholder.getAlias(), category)) {
return new CategoryFull(category, category.getSubCategories().stream()
.map(subCategoryId -> this.subCategoryService.getFullSubCategory(type, alias, subCategoryId))
.map(subCategoryId -> this.subCategoryService.getFullSubCategory(stakeholder, subCategoryId))
.collect(Collectors.toList()));
} else {
return null;
}
}
public CategoryFull getFullCategory(String type, String alias, String categoryId) {
public CategoryFull getFullCategory(Stakeholder stakeholder, String categoryId) {
Category category = this.find(categoryId);
return this.getFullCategory(type, alias, category);
return this.getFullCategory(stakeholder, category);
}
public String build(String id) {
@ -80,12 +82,9 @@ public class CategoryService {
}
public Category save(Category category) {
if(category.getId() != null) {
if (category.getId() != null) {
category.setSubCategories(this.find(category.getId()).getSubCategories());
} else {
category.setCreationDate(new Date());
}
category.setUpdateDate(new Date());
category.getSubCategories().forEach(this.subCategoryService::find);
return this.dao.save(category);
}
@ -107,7 +106,7 @@ public class CategoryService {
if (this.commonService.hasCreateAuthority(stakeholder.getType())) {
category = this.save(category);
this.createChildren(topic, category);
if(createOverview) {
if (createOverview) {
this.subCategoryService.save(stakeholder, category, category.createOverview());
}
this.addCategory(topic, category.getId());
@ -115,12 +114,12 @@ public class CategoryService {
this.commonService.unauthorized("You are not authorized to create a category in stakeholder with id: " + stakeholder.getId());
}
}
return this.getFullCategory(stakeholder.getType(), stakeholder.getAlias(), category);
return this.getFullCategory(stakeholder, category);
}
public void createChildren(Topic defaultTopic, Category category) {
this.topicDAO.findByDefaultId(defaultTopic.getId()).forEach(topic -> {
this.stakeholderDAO.findByTopicsContaining(topic.getId()).forEach(stakeholder -> {
this.stakeholderDAO.findByTopic(topic.getId()).forEach(stakeholder -> {
this.save(stakeholder, topic, category.copy(), false);
});
});
@ -133,15 +132,14 @@ public class CategoryService {
}
public CategoryFull reorderSubCategories(Stakeholder stakeholder, Category category, List<String> subcategories) {
if(this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
subcategories.forEach(this.subCategoryService::find);
if (category.getSubCategories().size() == subcategories.size() && new HashSet<>(category.getSubCategories()).containsAll(subcategories)) {
category.setSubCategories(subcategories);
category.setUpdateDate(new Date());
this.reorderChildren(stakeholder, category, subcategories);
return this.getFullCategory(stakeholder.getType(), stakeholder.getAlias(), this.dao.save(category));
return this.getFullCategory(stakeholder, this.dao.save(category));
} else {
throw new EntityNotFoundException("Some subCategories dont exist in the category with id " + category.getId());
throw new NotFoundException("Some subCategories dont exist in the category with id " + category.getId());
}
} else {
this.commonService.unauthorized("You are not authorized to reorder subCategories in category with id: " + category.getId());
@ -151,7 +149,7 @@ public class CategoryService {
public void reorderChildren(Stakeholder defaultStakeholder, Category defaultCategory, List<String> defaultSubCategories) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.dao.findByDefaultId(defaultCategory.getId()).stream().map(category -> this.getFullCategory(stakeholder.getType(), stakeholder.getAlias(), category)).forEach(category -> {
this.dao.findByDefaultId(defaultCategory.getId()).stream().map(category -> this.getFullCategory(stakeholder, category)).forEach(category -> {
this.reorderSubCategories(stakeholder, new Category(category),
this.commonService.reorder(defaultSubCategories, category.getSubCategories().stream().map(subCategory -> (Common) subCategory).collect(Collectors.toList())));
});
@ -182,27 +180,27 @@ public class CategoryService {
public void addCategory(Topic topic, String id) {
topic.addCategory(id);
topic.setUpdateDate(new Date());
this.topicDAO.save(topic);
}
public void removeCategory(String id) {
this.topicDAO.findByCategoriesContaining(id).forEach(topic -> {
this.topicDAO.findByCategory(id).forEach(topic -> {
topic.removeCategory(id);
topic.setUpdateDate(new Date());
this.topicDAO.save(topic);
});
}
public CategoryFull changeVisibility(String type, String alias, CategoryFull category, Visibility visibility, Boolean propagate) {
if (this.commonService.hasEditAuthority(type, alias)) {
category.setVisibility(visibility);
public CategoryFull changeVisibility(Stakeholder stakeholder, CategoryFull category, Visibility visibility, Boolean propagate) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
Stakeholder saved = this.commonService.changeVisibility(stakeholder, category, visibility, stakeholderDAO);
if (propagate) {
category.setSubCategories(category.getSubCategories().stream()
.map(subCategory -> this.subCategoryService.changeVisibility(type, alias, subCategory, visibility, true))
.map(subCategory -> this.subCategoryService.changeVisibility(saved, subCategory, visibility, true))
.collect(Collectors.toList()));
}
category.update(this.save(new Category(category)));
if(!stakeholder.isReference()) {
category.update(this.save(new Category(category)));
}
return category;
} else {
this.commonService.unauthorized("Change category visibility: You are not authorized to update category with id: " + category.getId());
@ -210,8 +208,23 @@ public class CategoryService {
return null;
}
public CategoryFull changeVisibility(String type, String alias, Category category, Visibility visibility, Boolean propagate) {
CategoryFull categoryFull = this.getFullCategory(type, alias, category);
return this.changeVisibility(type, alias, categoryFull, visibility, propagate);
public CategoryFull changeVisibility(Stakeholder stakeholder, Category category, Visibility visibility, Boolean propagate) {
CategoryFull categoryFull = this.getFullCategory(stakeholder, category);
return this.changeVisibility(stakeholder, categoryFull, visibility, propagate);
}
public CategoryFull restoreDefault(Stakeholder stakeholder, Category category) {
if(!stakeholder.isReference()) {
stakeholder.removeOverride(category.getId());
return this.getFullCategory(stakeholderDAO.save(stakeholder), category);
} else if(!stakeholder.isDefault()) {
String id = category.getId();
List<String> subCategories = category.getSubCategories();
category = this.find(category.getDefaultId()).copy();
category.setId(id);
category.setSubCategories(subCategories);
return this.getFullCategory(stakeholder, this.save(category));
}
return this.getFullCategory(stakeholder, category);
}
}

View File

@ -1,17 +1,16 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.UnauthorizedException;
import eu.dnetlib.uoaauthorizationlibrary.security.AuthorizationService;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.ForbiddenException;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.UnauthorizedException;
import eu.dnetlib.uoaauthorizationlibrary.authorization.security.AuthorizationService;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
@Service
@ -55,6 +54,14 @@ public class CommonService {
}
}
public void unauthorized(String message) {
if(authorizationService.getAaiId() != null) {
throw new ForbiddenException(message);
} else {
throw new UnauthorizedException(message);
}
}
public List<String> reorder(List<String> defaultIds, List<Common> commons) {
Map<String, Integer> map = new HashMap<>();
for(int i = 0; i < commons.size(); i++) {
@ -71,11 +78,14 @@ public class CommonService {
return ids;
}
public void unauthorized(String message) {
if(authorizationService.getAaiId() != null) {
throw new ForbiddenException(message);
} else {
throw new UnauthorizedException(message);
public Stakeholder changeVisibility(Stakeholder stakeholder, Common common, Visibility visibility, StakeholderDAO stakeholderDAO) {
if (!common.getVisibility().equals(visibility)) {
common.setVisibility(visibility);
if (stakeholder.isReference()) {
stakeholder.setOverride(common.getId(), "visibility", visibility);
stakeholder = stakeholderDAO.save(stakeholder);
}
}
return stakeholder;
}
}

View File

@ -1,11 +1,11 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
import eu.dnetlib.uoamonitorservice.dao.*;
import eu.dnetlib.uoamonitorservice.entities.Indicator;
import eu.dnetlib.uoamonitorservice.entities.Section;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.entities.SubCategory;
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import org.springframework.beans.factory.annotation.Autowired;
@ -26,7 +26,7 @@ public class IndicatorService {
private final CommonService commonService;
@Autowired
public IndicatorService(StakeholderDAO stakeholderDAO, TopicDAO topicDAO, CategoryDAO categoryDAO,SubCategoryDAO subCategoryDAO,
public IndicatorService(StakeholderDAO stakeholderDAO, TopicDAO topicDAO, CategoryDAO categoryDAO, SubCategoryDAO subCategoryDAO,
SectionDAO sectionDAO, IndicatorDAO dao, CommonService commonService) {
this.stakeholderDAO = stakeholderDAO;
this.topicDAO = topicDAO;
@ -38,19 +38,20 @@ public class IndicatorService {
}
public Indicator find(String id) {
return dao.findById(id).orElseThrow(() -> new EntityNotFoundException("Indicator with id: " + id + " not found"));
return dao.findById(id).orElseThrow(() -> new NotFoundException("Indicator with id: " + id + " not found"));
}
public Indicator findByPath(Section section, String indicatorId) {
if (!section.getIndicators().contains(indicatorId)) {
throw new PathNotValidException("Indicator with id: " + indicatorId + " not found in Section: " + section.getId());
}
return this.dao.findById(indicatorId).orElseThrow(() -> new EntityNotFoundException("Indicator with id: " + indicatorId + " not found"));
return this.dao.findById(indicatorId).orElseThrow(() -> new NotFoundException("Indicator with id: " + indicatorId + " not found"));
}
public Indicator getIndicator(String type, String alias, String id) {
public Indicator getIndicator(Stakeholder stakeholder, String id) {
Indicator indicator = this.find(id);
if(this.commonService.hasVisibilityAuthority(type, alias, indicator)) {
indicator.override(stakeholder);
if (this.commonService.hasVisibilityAuthority(stakeholder.getType(), stakeholder.getAlias(), indicator)) {
return indicator;
} else {
return null;
@ -68,15 +69,11 @@ public class IndicatorService {
}
public Indicator save(Indicator indicator) {
if(indicator.getId() == null) {
indicator.setCreationDate(new Date());
}
indicator.setUpdateDate(new Date());
return this.dao.save(indicator);
}
public Indicator save(Stakeholder stakeholder, Section section, Indicator indicator) {
if(indicator.getId() != null) {
if (indicator.getId() != null) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
this.updateChildren(indicator);
indicator = this.save(indicator);
@ -97,12 +94,12 @@ public class IndicatorService {
public void createChildren(Section defaultSection, Indicator indicator) {
this.sectionDAO.findByDefaultId(defaultSection.getId()).forEach(section -> {
List<SubCategory> subCategories = this.subCategoryDAO.findByNumbersContaining(section.getId());
subCategories.addAll(this.subCategoryDAO.findByChartsContaining(section.getId()));
List<SubCategory> subCategories = this.subCategoryDAO.findByNumber(section.getId());
subCategories.addAll(this.subCategoryDAO.findByChart(section.getId()));
subCategories.forEach(subCategory -> {
this.categoryDAO.findBySubCategoriesContaining(subCategory.getId()).forEach(category -> {
this.topicDAO.findByCategoriesContaining(category.getId()).forEach(topic -> {
this.stakeholderDAO.findByTopicsContaining(topic.getId()).forEach(stakeholder -> {
this.categoryDAO.findBySubCategory(subCategory.getId()).forEach(category -> {
this.topicDAO.findByCategory(category.getId()).forEach(topic -> {
this.stakeholderDAO.findByTopic(topic.getId()).forEach(stakeholder -> {
this.save(stakeholder, section, indicator.copy());
});
});
@ -118,11 +115,11 @@ public class IndicatorService {
}
public void delete(String type, Indicator indicator, boolean remove) {
if(this.commonService.hasDeleteAuthority(type)) {
if (this.commonService.hasDeleteAuthority(type)) {
this.dao.findByDefaultId(indicator.getId()).forEach(child -> {
this.delete(type, child.getId(), remove);
});
if(remove) {
if (remove) {
this.removeIndicator(indicator.getId());
}
this.dao.delete(indicator);
@ -139,22 +136,23 @@ public class IndicatorService {
public void addIndicator(Section section, String id) {
section.addIndicator(id);
section.setUpdateDate(new Date());
this.sectionDAO.save(section);
}
public void removeIndicator(String id) {
this.sectionDAO.findByIndicatorsContaining(id).forEach(section -> {
this.sectionDAO.findByIndicator(id).forEach(section -> {
section.removeIndicator(id);
section.setUpdateDate(new Date());
this.sectionDAO.save(section);
});
}
public Indicator changeVisibility(String type, String alias, Indicator indicator, Visibility visibility) {
if(this.commonService.hasEditAuthority(type, alias)) {
indicator.setVisibility(visibility);
return this.save(indicator);
public Indicator changeVisibility(Stakeholder stakeholder, Indicator indicator, Visibility visibility) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
stakeholder = this.commonService.changeVisibility(stakeholder, indicator, visibility, stakeholderDAO);
if(!stakeholder.isReference()) {
indicator = this.save(indicator);
}
return indicator;
} else {
this.commonService.unauthorized("Change section visibility: You are not authorized to update section with id: " + indicator.getId());
}

View File

@ -1,11 +1,10 @@
package eu.dnetlib.uoamonitorservice.service;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
import eu.dnetlib.uoamonitorservice.configuration.GlobalVars;
import eu.dnetlib.uoamonitorservice.configuration.mongo.MongoConnection;
import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
import jakarta.annotation.PostConstruct;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
@ -26,27 +25,32 @@ public class MonitorDeployService {
this.globalVars = globalVars;
}
public Map<String, String> checkEverything() {
Map<String, String> response = new HashMap<>();
@PostConstruct
public void checkProperties() {
if(mongoConfig.getHost() == null || mongoConfig.getHost().isEmpty()) {
throw new RuntimeException("monitor-service.mongodb.host is missing!");
} else if(mongoConfig.getDatabase() == null || mongoConfig.getDatabase().isEmpty()) {
throw new RuntimeException("monitor-service.mongodb.database is missing!");
}
}
public Map<String, String> getProperties() {
Map<String, String> response = new HashMap<>();
MongoTemplate mt = mongoConnection.getMongoTemplate();
DBObject ping = new BasicDBObject("ping", "1");
Document ping = new Document("ping", 1);
try {
CommandResult answer = mt.getDb().command(ping);
response.put("Mongo try: error", answer.getErrorMessage());
Document answer = mt.executeCommand(ping);
response.put("Mongo try: error", String.valueOf(answer.getDouble("ok") == 1.0));
} catch (Exception e) {
response.put("Mongo catch: error", e.getMessage());
}
response.put("monitor-service.mongodb.database", mongoConfig.getDatabase());
response.put("monitor-service.mongodb.host", mongoConfig.getHost());
response.put("monitor-service.mongodb.port", mongoConfig.getPort() + "");
response.put("monitor-service.mongodb.username", mongoConfig.getUsername() == null ? null : "[unexposed value]");
response.put("monitor-service.mongodb.password", mongoConfig.getPassword() == null ? null : "[unexposed value]");
response.put("monitorservice.mongodb.database", mongoConfig.getDatabase());
response.put("monitorservice.mongodb.host", mongoConfig.getHost());
response.put("monitorservice.mongodb.port", mongoConfig.getPort() + "");
response.put("monitorservice.mongodb.username", mongoConfig.getUsername() == null ? null : "[unexposed value]");
response.put("monitorservice.mongodb.password", mongoConfig.getPassword() == null ? null : "[unexposed value]");
if (globalVars.date != null) {
response.put("Date of deploy", globalVars.date.toString());
}
response.put("Date of deploy", GlobalVars.date.toString());
if (globalVars.getBuildDate() != null) {
response.put("Date of build", globalVars.getBuildDate());
}

View File

@ -1,12 +1,12 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
import eu.dnetlib.uoamonitorservice.dao.*;
import eu.dnetlib.uoamonitorservice.dto.SectionFull;
import eu.dnetlib.uoamonitorservice.entities.Section;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.entities.SubCategory;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import org.springframework.beans.factory.annotation.Autowired;
@ -41,25 +41,26 @@ public class SectionService {
}
public Section find(String id) {
return dao.findById(id).orElseThrow(() -> new EntityNotFoundException("Section with id: " + id + " not found"));
return dao.findById(id).orElseThrow(() -> new NotFoundException("Section with id: " + id + " not found"));
}
public Section findByPath(SubCategory subCategory, String sectionId) {
if (!subCategory.getNumbers().contains(sectionId) && !subCategory.getCharts().contains(sectionId)) {
throw new PathNotValidException("Section with id: " + sectionId + " not found in SubCategory: " + subCategory.getId());
}
return this.dao.findById(sectionId).orElseThrow(() -> new EntityNotFoundException("Section with id: " + sectionId + " not found"));
return this.dao.findById(sectionId).orElseThrow(() -> new NotFoundException("Section with id: " + sectionId + " not found"));
}
public SectionFull getFullSection(String type, String alias, Section section) {
public SectionFull getFullSection(Stakeholder stakeholder, Section section) {
section.override(stakeholder);
return new SectionFull(section, section.getIndicators().stream()
.map(indicatorId -> this.indicatorService.getIndicator(type, alias, indicatorId))
.map(indicatorId -> this.indicatorService.getIndicator(stakeholder, indicatorId))
.collect(Collectors.toList()));
}
public SectionFull getFullSection(String type, String alias, String id) {
public SectionFull getFullSection(Stakeholder stakeholder, String id) {
Section section = this.find(id);
return this.getFullSection(type, alias, section);
return this.getFullSection(stakeholder, section);
}
public SectionFull saveFull(SectionFull sectionFull) {
@ -86,10 +87,7 @@ public class SectionService {
public Section save(Section section) {
if (section.getId() != null) {
section.setIndicators(this.find(section.getId()).getIndicators());
} else {
section.setCreationDate(new Date());
}
section.setUpdateDate(new Date());
section.getIndicators().forEach(this.indicatorService::find);
return this.dao.save(section);
}
@ -125,28 +123,28 @@ public class SectionService {
this.commonService.unauthorized("You are not authorized to create a section in stakeholder with id: " + stakeholder.getId());
}
}
return this.getFullSection(stakeholder.getType(), stakeholder.getAlias(), section);
return this.getFullSection(stakeholder, section);
}
public void createChildren(SubCategory defaultSubCategory, Section section, int index) {
this.subCategoryDAO.findByDefaultId(defaultSubCategory.getId()).forEach(subCategory -> {
this.categoryDAO.findBySubCategoriesContaining(subCategory.getId()).forEach(category -> {
this.topicDAO.findByCategoriesContaining(category.getId()).forEach(topic -> {
this.stakeholderDAO.findByTopicsContaining(topic.getId()).forEach(stakeholder -> {
this.save(stakeholder, subCategory, section.copy(), index);
});
});
});
});
section.getIndicators().forEach(indicator -> {
this.indicatorService.createChildren(section, this.indicatorService.find(indicator));
});
this.subCategoryDAO.findByDefaultId(defaultSubCategory.getId()).forEach(subCategory ->
this.categoryDAO.findBySubCategory(subCategory.getId()).forEach(category ->
this.topicDAO.findByCategory(category.getId()).forEach(topic ->
this.stakeholderDAO.findByTopic(topic.getId()).forEach(stakeholder ->
this.save(stakeholder, subCategory, section.copy(), index)
)
)
)
);
section.getIndicators().forEach(indicator ->
this.indicatorService.createChildren(section, this.indicatorService.find(indicator))
);
}
public void updateChildren(Section section) {
this.dao.findByDefaultId(section.getId()).forEach(child -> {
this.save(section.override(child, this.find(section.getId())));
});
this.dao.findByDefaultId(section.getId()).forEach(child ->
this.save(section.override(child, this.find(section.getId())))
);
}
public SectionFull reorderIndicators(Stakeholder stakeholder, Section section, List<String> indicators) {
@ -158,13 +156,12 @@ public class SectionService {
indicators.forEach(this.indicatorService::find);
if (section.getIndicators().size() == indicators.size() && new HashSet<>(section.getIndicators()).containsAll(indicators)) {
section.setIndicators(indicators);
section.setUpdateDate(new Date());
if(reorderChildren) {
if (reorderChildren) {
this.reorderChildren(stakeholder, section, indicators);
}
return this.getFullSection(stakeholder.getType(), stakeholder.getAlias(), this.dao.save(section));
return this.getFullSection(stakeholder, this.dao.save(section));
} else {
throw new EntityNotFoundException("Some indicators dont exist in the section with id " + section.getId());
throw new NotFoundException("Some indicators dont exist in the section with id " + section.getId());
}
} else {
this.commonService.unauthorized("You are not authorized to reorder indicators in section with id: " + section.getId());
@ -173,22 +170,21 @@ public class SectionService {
}
public void reorderChildren(Stakeholder defaultStakeholder, Section defaultSection, List<String> defaultIndicators) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.dao.findByDefaultId(defaultSection.getId()).stream().map(section -> this.getFullSection(stakeholder.getType(), stakeholder.getAlias(), section)).forEach(section -> {
this.reorderIndicators(stakeholder, new Section(section),
this.commonService.reorder(defaultIndicators, section.getIndicators().stream().map(indicator -> (Common) indicator).collect(Collectors.toList())));
});
});
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder ->
this.dao.findByDefaultId(defaultSection.getId()).stream().map(section -> this.getFullSection(stakeholder, section)).forEach(section ->
this.reorderIndicators(stakeholder, new Section(section), this.commonService.reorder(defaultIndicators, section.getIndicators().stream().map(indicator -> (Common) indicator).collect(Collectors.toList())))
)
);
}
public void delete(String type, Section section, boolean remove) {
if (this.commonService.hasDeleteAuthority(type)) {
this.dao.findByDefaultId(section.getId()).forEach(child -> {
this.delete(type, child.getId(), remove);
});
section.getIndicators().forEach(indicatorId -> {
this.indicatorService.delete(type, indicatorId, false);
});
this.dao.findByDefaultId(section.getId()).forEach(child ->
this.delete(type, child.getId(), remove)
);
section.getIndicators().forEach(indicatorId ->
this.indicatorService.delete(type, indicatorId, false)
);
if (remove) {
this.removeSection(section.getId());
}
@ -213,29 +209,28 @@ public class SectionService {
} else {
subCategory.addChart(id, index);
}
subCategory.setUpdateDate(new Date());
this.subCategoryDAO.save(subCategory);
}
public void removeSection(String id) {
this.subCategoryDAO.findByNumbersContaining(id).forEach(subCategory -> {
this.subCategoryDAO.findByNumber(id).forEach(subCategory -> {
subCategory.removeNumber(id);
subCategory.setUpdateDate(new Date());
this.subCategoryDAO.save(subCategory);
});
this.subCategoryDAO.findByChartsContaining(id).forEach(subCategory -> {
this.subCategoryDAO.findByChart(id).forEach(subCategory -> {
subCategory.removeChart(id);
subCategory.setUpdateDate(new Date());
this.subCategoryDAO.save(subCategory);
});
}
public SectionFull changeVisibility(String type, String alias, SectionFull section, Visibility visibility) {
if (this.commonService.hasEditAuthority(type, alias)) {
public SectionFull changeVisibility(Stakeholder stakeholder, SectionFull section, Visibility visibility) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
section.setIndicators(section.getIndicators().stream()
.map(indicator -> this.indicatorService.changeVisibility(type, alias, indicator, visibility))
.map(indicator -> this.indicatorService.changeVisibility(stakeholder, indicator, visibility))
.collect(Collectors.toList()));
section.update(this.save(new Section(section)));
if(!stakeholder.isReference()) {
section.update(this.save(new Section(section)));
}
return section;
} else {
this.commonService.unauthorized("Change section visibility: You are not authorized to update section with id: " + section.getId());

View File

@ -1,19 +1,16 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.dto.ManageStakeholders;
import eu.dnetlib.uoamonitorservice.dto.StakeholderFull;
import eu.dnetlib.uoamonitorservice.dto.TopicFull;
import eu.dnetlib.uoamonitorservice.dto.UpdateUmbrella;
import eu.dnetlib.uoamonitorservice.dto.*;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.handlers.BadRequestException;
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
import eu.dnetlib.uoamonitorservice.primitives.Action;
import eu.dnetlib.uoamonitorservice.primitives.StakeholderType;
import eu.dnetlib.uoamonitorservice.primitives.Umbrella;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import eu.dnetlib.uoamonitorservice.utils.GenericAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
@ -40,7 +37,7 @@ public class StakeholderService {
}
public Stakeholder findByAlias(String alias) {
return this.dao.findByAlias(alias).orElseThrow(() -> new EntityNotFoundException("Stakeholder with alias: " + alias + " not found"));
return this.dao.findByAlias(alias).orElseThrow(() -> new NotFoundException("Stakeholder with alias: " + alias + " not found"));
}
public List<Stakeholder> findByDefaultId(String id) {
@ -51,7 +48,7 @@ public class StakeholderService {
if (stakeholderId.equals("-1")) {
return null;
}
return dao.findById(stakeholderId).orElseThrow(() -> new EntityNotFoundException("Stakeholder with id: " + stakeholderId + " not found"));
return dao.findById(stakeholderId).orElseThrow(() -> new NotFoundException("Stakeholder with id: " + stakeholderId + " not found"));
}
public List<String> getAllAliases(String type) {
@ -89,13 +86,13 @@ public class StakeholderService {
public StakeholderFull getFullStakeholder(Stakeholder stakeholder) {
List<TopicFull> topics = stakeholder.getTopics().stream()
.map(topicId -> topicService.getFullTopic(stakeholder.getType(), stakeholder.getAlias(), topicId))
.map(topicId -> topicService.getFullTopic(stakeholder, topicId))
.collect(Collectors.toList());
if (!stakeholder.isCopy() && stakeholder.getDefaultId() != null) {
if (stakeholder.isReference()) {
Stakeholder defaultStakeholder = this.findByPath(stakeholder.getDefaultId());
if (defaultStakeholder != null) {
topics = defaultStakeholder.getTopics().stream()
.map(topicId -> topicService.getFullTopic(stakeholder.getType(), stakeholder.getAlias(), topicId))
.map(topicId -> topicService.getFullTopic(stakeholder, topicId))
.collect(Collectors.toList());
}
}
@ -119,12 +116,66 @@ public class StakeholderService {
StakeholderFull stakeholderFull = this.getFullStakeholder(stakeholder);
if (stakeholderFull != null) {
stakeholderFull.setParent(this.getActiveParent(parent, type, stakeholder.getId())
.orElseThrow(() -> new EntityNotFoundException("Stakeholder with alias: " + stakeholder.getAlias() + " not found in stakeholder " + parent)));
.orElseThrow(() -> new NotFoundException("Stakeholder with alias: " + stakeholder.getAlias() + " not found in stakeholder " + parent)));
stakeholderFull.setOtherParents(this.getOtherParents(parent, type, stakeholder.getId()));
}
return stakeholderFull;
}
public Stakeholder generateAlias(Stakeholder stakeholder) {
return this.generateAlias(stakeholder, null);
}
public Stakeholder generateAlias(Stakeholder stakeholder, String field) {
String alias = stakeholder.getAlias();
if(field != null) {
try {
// Convert to lower case
alias = Objects.requireNonNull(GenericAccessor.getField(stakeholder, field)).toString().toLowerCase();
// Replace all invalid characters with a hyphen
alias = Objects.requireNonNull(alias).replaceAll("[^a-z0-9-]", "-");
// Replace multiple consecutive hyphens with a single hyphen
alias = Objects.requireNonNull(alias).replaceAll("-+", "-");
// Remove leading or trailing hyphens
alias = Objects.requireNonNull(alias).replaceAll("^-+|-+$", "-");
} catch (NullPointerException e) {
throw new BadRequestException("Cannot generate alias with field " + field + " for stakeholder: " + stakeholder.getName());
}
}
if(alias == null) {
throw new BadRequestException("Cannot generate alias for stakeholder: " + stakeholder.getName());
}
int duplicates = 1;
while(this.dao.findByAlias(alias).isPresent()) {
alias = alias + duplicates;
duplicates++;
}
stakeholder.setAlias(alias);
return stakeholder;
}
public List<Stakeholder> buildStakeholders(BuildStakeholder buildStakeholder) {
List<Stakeholder> stakeholders = new ArrayList<>();
if(buildStakeholder.isMultiBuild()) {
stakeholders = buildStakeholder.getIndexFields().stream().map( fields -> {
Stakeholder stakeholder = new Stakeholder(buildStakeholder.getStakeholder());
stakeholder.setIndex_id(fields.get(stakeholder.getIndex_id()));
stakeholder.setIndex_name(fields.get(stakeholder.getIndex_name()));
stakeholder.setIndex_shortName(fields.get(stakeholder.getIndex_shortName()));
stakeholder.setName(stakeholder.getIndex_name());
stakeholder = generateAlias(stakeholder, stakeholder.getAlias());
return stakeholder;
}).toList();
} else {
stakeholders.add(buildStakeholder.getStakeholder());
}
stakeholders.forEach(stakeholder -> stakeholder.setStandalone(buildStakeholder.isStandalone()));
if (buildStakeholder.isUmbrella()) {
stakeholders.forEach(stakeholder -> stakeholder.setUmbrella(new Umbrella<>()));
}
return stakeholders.stream().map(stakeholder -> this.buildStakeholder(stakeholder, buildStakeholder.getCopyId())).toList();
}
public Stakeholder buildStakeholder(Stakeholder stakeholder, String copyId) {
if (stakeholder.getDefaultId() == null) {
stakeholder.setCopy(false);
@ -135,6 +186,7 @@ public class StakeholderService {
stakeholder.setTopics(copyFrom.getTopics().stream().map(this.topicService::copy).collect(Collectors.toList()));
}
} else {
stakeholder = generateAlias(stakeholder);
stakeholder.setTopics(new ArrayList<>());
if (stakeholder.isCopy()) {
Stakeholder defaultStakeholder = this.findByPath(stakeholder.getDefaultId());
@ -149,10 +201,13 @@ public class StakeholderService {
public Stakeholder save(Stakeholder stakeholder) {
if (stakeholder.getId() != null) {
Stakeholder old = this.findByPath(stakeholder.getId());
if(stakeholder.getOverrides() == null) {
stakeholder.setOverrides(old.getOverrides());
}
stakeholder.setUmbrella(old.getUmbrella());
stakeholder.setStandalone(old.isStandalone());
stakeholder.setDefaultId(old.getDefaultId());
if (!stakeholder.isCopy() && stakeholder.getDefaultId() != null) {
if (stakeholder.isReference()) {
stakeholder.getTopics().forEach(topic -> {
this.topicService.delete(stakeholder.getType(), topic, false);
});
@ -163,14 +218,12 @@ public class StakeholderService {
if (defaultStakeholder != null) {
stakeholder.setTopics(defaultStakeholder.getTopics().stream().map(this.topicService::build).collect(Collectors.toList()));
}
stakeholder.setOverrides(new HashMap<>());
}
stakeholder.getTopics().forEach(this.topicService::find);
}
} else {
stakeholder.setCreationDate(new Date());
}
stakeholder.setUpdateDate(new Date());
return this.dao.save(stakeholder);
return this.dao.save(stakeholder.validate());
}
public StakeholderFull reorderTopics(Stakeholder stakeholder, List<String> topics) {
@ -178,11 +231,10 @@ public class StakeholderService {
topics.forEach(this.topicService::find);
if (stakeholder.getTopics().size() == topics.size() && new HashSet<>(stakeholder.getTopics()).containsAll(topics)) {
stakeholder.setTopics(topics);
stakeholder.setUpdateDate(new Date());
this.reorderChildren(stakeholder, topics);
return this.getFullStakeholder(this.dao.save(stakeholder));
} else {
throw new EntityNotFoundException("Some topics dont exist in the stakeholder with id " + stakeholder.getId());
throw new NotFoundException("Some topics dont exist in the stakeholder with id " + stakeholder.getId());
}
} else {
this.commonService.unauthorized("You are not authorized to reorder topics in stakeholder with id: " + stakeholder.getId());
@ -213,7 +265,7 @@ public class StakeholderService {
stakeholder.getTopics().forEach(topicId -> {
this.topicService.delete(stakeholder.getType(), topicId, false);
});
this.dao.delete(id);
this.dao.deleteById(id);
return stakeholder.getAlias();
} else {
this.commonService.unauthorized("Delete stakeholder: You are not authorized to delete stakeholder with id: " + id);
@ -223,14 +275,14 @@ public class StakeholderService {
public StakeholderFull changeVisibility(StakeholderFull stakeholder, Visibility visibility, Boolean propagate) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
stakeholder.setVisibility(visibility);
Stakeholder toSave = new Stakeholder(stakeholder, this);
if (propagate) {
stakeholder.setTopics(stakeholder.getTopics().stream().
map(topic -> this.topicService.changeVisibility(stakeholder.getType(), stakeholder.getAlias(), topic, visibility, true))
map(topic -> this.topicService.changeVisibility(toSave, topic, visibility, true))
.collect(Collectors.toList()));
}
stakeholder.setVisibility(visibility);
stakeholder.update(this.save(new Stakeholder(stakeholder, this)));
return stakeholder;
return getFullStakeholder(this.save(toSave));
} else {
this.commonService.unauthorized("Change stakeholder visibility: You are not authorized to update stakeholder with id: " + stakeholder.getId());
}
@ -271,10 +323,9 @@ public class StakeholderService {
public Umbrella<Stakeholder> addType(String id, StakeholderType type) {
Stakeholder stakeholder = this.findByPath(id);
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new EntityNotFoundException("Umbrella not found in the stakeholder with id " + id));
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new NotFoundException("Umbrella not found in the stakeholder with id " + id));
if (umbrella.addType(type)) {
stakeholder.setUmbrella(umbrella);
stakeholder.setUpdateDate(new Date());
return this.getFullStakeholder(this.dao.save(stakeholder)).getUmbrella();
}
throw new BadRequestException("Cannot add type: " + type + " to stakeholder with id " + id);
@ -282,10 +333,9 @@ public class StakeholderService {
public Umbrella<Stakeholder> removeType(String id, StakeholderType type) {
Stakeholder stakeholder = this.findByPath(id);
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new EntityNotFoundException("Umbrella not found in the stakeholder with id " + id));
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new NotFoundException("Umbrella not found in the stakeholder with id " + id));
if (umbrella.removeType(type)) {
stakeholder.setUmbrella(umbrella);
stakeholder.setUpdateDate(new Date());
return this.getFullStakeholder(this.dao.save(stakeholder)).getUmbrella();
}
throw new BadRequestException("Cannot add type: " + type + " to stakeholder with id " + id);
@ -293,11 +343,10 @@ public class StakeholderService {
public Umbrella<Stakeholder> addChild(String id, StakeholderType type, String childId) {
Stakeholder stakeholder = this.findByPath(id);
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new EntityNotFoundException("Umbrella not found in the stakeholder with id " + id));
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new NotFoundException("Umbrella not found in the stakeholder with id " + id));
Stakeholder child = this.findByPath(childId);
if (child.getType().equals(type.name()) && umbrella.addChild(type, childId)) {
stakeholder.setUmbrella(umbrella);
stakeholder.setUpdateDate(new Date());
return this.getFullStakeholder(this.dao.save(stakeholder)).getUmbrella();
}
throw new BadRequestException("Cannot add child: " + childId + " to stakeholder with id " + id);
@ -305,11 +354,10 @@ public class StakeholderService {
public Umbrella<Stakeholder> removeChild(String id, StakeholderType type, String childId) {
Stakeholder stakeholder = this.findByPath(id);
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new EntityNotFoundException("Umbrella not found in the stakeholder with id " + id));
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new NotFoundException("Umbrella not found in the stakeholder with id " + id));
Stakeholder child = this.findByPath(childId);
if (child.getType().equals(type.name()) && umbrella.removeChild(type, childId)) {
stakeholder.setUmbrella(umbrella);
stakeholder.setUpdateDate(new Date());
return this.getFullStakeholder(this.dao.save(stakeholder)).getUmbrella();
}
throw new BadRequestException("Cannot remove child: " + childId + " to stakeholder with id " + id);
@ -317,10 +365,9 @@ public class StakeholderService {
public Umbrella<Stakeholder> updateTypes(String id, List<StakeholderType> types) {
Stakeholder stakeholder = this.findByPath(id);
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new EntityNotFoundException("Umbrella not found in the stakeholder with id " + id));
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new NotFoundException("Umbrella not found in the stakeholder with id " + id));
if (stakeholder.getUmbrella().update(types)) {
stakeholder.setUmbrella(umbrella);
stakeholder.setUpdateDate(new Date());
return this.getFullStakeholder(this.dao.save(stakeholder)).getUmbrella();
}
throw new BadRequestException("Cannot update types in umbrella of stakeholder with id " + id);
@ -328,10 +375,9 @@ public class StakeholderService {
public Umbrella<Stakeholder> updateChildren(String id, StakeholderType type, List<String> children) {
Stakeholder stakeholder = this.findByPath(id);
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new EntityNotFoundException("Umbrella not found in the stakeholder with id " + id));
Umbrella<String> umbrella = stakeholder.getUmbrellaOptional().orElseThrow(() -> new NotFoundException("Umbrella not found in the stakeholder with id " + id));
if (stakeholder.getUmbrella().update(type, children)) {
stakeholder.setUmbrella(umbrella);
stakeholder.setUpdateDate(new Date());
return this.getFullStakeholder(this.dao.save(stakeholder)).getUmbrella();
}
throw new BadRequestException("Cannot update children of " + type + " in umbrella of stakeholder with id " + id);

View File

@ -1,5 +1,6 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
import eu.dnetlib.uoamonitorservice.dao.CategoryDAO;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.dao.SubCategoryDAO;
@ -10,7 +11,6 @@ import eu.dnetlib.uoamonitorservice.dto.SectionInfo;
import eu.dnetlib.uoamonitorservice.dto.SubCategoryFull;
import eu.dnetlib.uoamonitorservice.entities.*;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import org.springframework.beans.factory.annotation.Autowired;
@ -43,32 +43,33 @@ public class SubCategoryService {
}
public SubCategory find(String id) {
return dao.findById(id).orElseThrow(() -> new EntityNotFoundException("SubCategory with id: " + id + " not found"));
return dao.findById(id).orElseThrow(() -> new NotFoundException("SubCategory with id: " + id + " not found"));
}
public SubCategory findByPath(Category category, String subcategoryId) {
if (!category.getSubCategories().contains(subcategoryId)) {
throw new PathNotValidException("SubCategory with id: " + subcategoryId + " not found in Category: " + category.getId());
}
return this.dao.findById(subcategoryId).orElseThrow(() -> new EntityNotFoundException("SubCategory with id: " + subcategoryId + " not found"));
return this.dao.findById(subcategoryId).orElseThrow(() -> new NotFoundException("SubCategory with id: " + subcategoryId + " not found"));
}
public SubCategoryFull getFullSubCategory(String type, String alias, SubCategory subCategory) {
if(commonService.hasVisibilityAuthority(type, alias, subCategory)) {
public SubCategoryFull getFullSubCategory(Stakeholder stakeholder, SubCategory subCategory) {
subCategory.override(stakeholder);
if(commonService.hasVisibilityAuthority(stakeholder.getType(), stakeholder.getAlias(), subCategory)) {
return new SubCategoryFull(subCategory, subCategory.getNumbers().stream()
.map(sectionId -> this.sectionService.getFullSection(type, alias, sectionId))
.map(sectionId -> this.sectionService.getFullSection(stakeholder, sectionId))
.collect(Collectors.toList()),
subCategory.getCharts().stream()
.map(sectionId -> this.sectionService.getFullSection(type, alias, sectionId))
.map(sectionId -> this.sectionService.getFullSection(stakeholder, sectionId))
.collect(Collectors.toList()));
} else {
return null;
}
}
public SubCategoryFull getFullSubCategory(String type, String alias, String subCategoryId) {
public SubCategoryFull getFullSubCategory(Stakeholder stakeholder, String subCategoryId) {
SubCategory subCategory = this.find(subCategoryId);
return this.getFullSubCategory(type, alias, subCategory);
return this.getFullSubCategory(stakeholder, subCategory);
}
public String build(String id) {
@ -93,10 +94,7 @@ public class SubCategoryService {
SubCategory old = this.find(subCategory.getId());
subCategory.setNumbers(old.getNumbers());
subCategory.setCharts(old.getCharts());
} else {
subCategory.setCreationDate(new Date());
}
subCategory.setUpdateDate(new Date());
subCategory.getNumbers().forEach(this.sectionService::find);
subCategory.getCharts().forEach(this.sectionService::find);
return this.dao.save(subCategory);
@ -122,13 +120,13 @@ public class SubCategoryService {
this.commonService.unauthorized("You are not authorized to create a subCategory in stakeholder with id: " + stakeholder.getId());
}
}
return this.getFullSubCategory(stakeholder.getType(), stakeholder.getAlias(), subCategory);
return this.getFullSubCategory(stakeholder, subCategory);
}
public void createChildren(Category defaultCategory, SubCategory subCategory) {
this.categoryDAO.findByDefaultId(defaultCategory.getId()).forEach(category -> {
this.topicDAO.findByCategoriesContaining(category.getId()).forEach(topic -> {
this.stakeholderDAO.findByTopicsContaining(topic.getId()).forEach(stakeholder -> {
this.topicDAO.findByCategory(category.getId()).forEach(topic -> {
this.stakeholderDAO.findByTopic(topic.getId()).forEach(stakeholder -> {
this.save(stakeholder, category, subCategory.copy());
});
});
@ -150,7 +148,7 @@ public class SubCategoryService {
this.sectionService.reorderIndicators(stakeholder, from, moveIndicator.getFrom().getIndicators(), false);
this.sectionService.reorderIndicators(stakeholder, to, moveIndicator.getTo().getIndicators(), false);
this.moveIndicatorChildren(stakeholder, subCategory, moveIndicator);
return this.getFullSubCategory(stakeholder.getType(), stakeholder.getAlias(), subCategory);
return this.getFullSubCategory(stakeholder, subCategory);
} else {
this.commonService.unauthorized("You are not authorized to move indicators in subCategory with id: " + subCategory.getId());
}
@ -160,8 +158,8 @@ public class SubCategoryService {
public void moveIndicatorChildren(Stakeholder defaultStakeholder, SubCategory defaultSubCategory, MoveIndicator moveIndicator) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.dao.findByDefaultId(defaultSubCategory.getId()).stream()
.map(subCategory -> this.getFullSubCategory(stakeholder.getType(), stakeholder. getAlias(), subCategory))
.collect(Collectors.toList()).forEach(subCategory -> {
.map(subCategory -> this.getFullSubCategory(stakeholder, subCategory))
.toList().forEach(subCategory -> {
SectionFull from = subCategory.getSectionByDefaultId(moveIndicator.getFrom().getId()).orElse(null);
SectionFull to = subCategory.getSectionByDefaultId(moveIndicator.getTo().getId()).orElse(null);
if(from != null && to != null) {
@ -184,11 +182,10 @@ public class SubCategoryService {
numbers.forEach(this.sectionService::find);
if (subCategory.getNumbers().size() == numbers.size() && new HashSet<>(subCategory.getNumbers()).containsAll(numbers)) {
subCategory.setNumbers(numbers);
subCategory.setUpdateDate(new Date());
this.reorderChildrenNumbers(stakeholder, subCategory, numbers);
return this.getFullSubCategory(stakeholder.getType(), stakeholder.getAlias(), this.dao.save(subCategory));
return this.getFullSubCategory(stakeholder, this.dao.save(subCategory));
} else {
throw new EntityNotFoundException("Some sections dont exist in the subCategory with id " + subCategory.getId());
throw new NotFoundException("Some sections dont exist in the subCategory with id " + subCategory.getId());
}
} else {
this.commonService.unauthorized("You are not authorized to reorder sections in subCategory with id: " + subCategory.getId());
@ -202,9 +199,9 @@ public class SubCategoryService {
if (subCategory.getCharts().size() == charts.size() && new HashSet<>(subCategory.getCharts()).containsAll(charts)) {
subCategory.setCharts(charts);
this.reorderChildrenCharts(stakeholder, subCategory, charts);
return this.getFullSubCategory(stakeholder.getType(), stakeholder.getAlias(), this.dao.save(subCategory));
return this.getFullSubCategory(stakeholder, this.dao.save(subCategory));
} else {
throw new EntityNotFoundException("Some sections dont exist in the subCategory with id " + subCategory.getId());
throw new NotFoundException("Some sections dont exist in the subCategory with id " + subCategory.getId());
}
} else {
this.commonService.unauthorized("You are not authorized to reorder sections in subCategory with id: " + subCategory.getId());
@ -214,7 +211,7 @@ public class SubCategoryService {
public void reorderChildrenNumbers(Stakeholder defaultStakeholder, SubCategory defaultSubCategory, List<String> defaultSections) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.dao.findByDefaultId(defaultSubCategory.getId()).stream().map(subCategory -> this.getFullSubCategory(stakeholder.getType(), stakeholder.getAlias(), subCategory)).forEach(subCategory -> {
this.dao.findByDefaultId(defaultSubCategory.getId()).stream().map(subCategory -> this.getFullSubCategory(stakeholder, subCategory)).forEach(subCategory -> {
this.reorderNumbers(stakeholder, new SubCategory(subCategory),
this.commonService.reorder(defaultSections, subCategory.getNumbers().stream().map(section -> (Common) section).collect(Collectors.toList())));
});
@ -223,7 +220,7 @@ public class SubCategoryService {
public void reorderChildrenCharts(Stakeholder defaultStakeholder, SubCategory defaultSubCategory, List<String> defaultSections) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.dao.findByDefaultId(defaultSubCategory.getId()).stream().map(subCategory -> this.getFullSubCategory(stakeholder.getType(), stakeholder.getAlias(), subCategory)).forEach(subCategory -> {
this.dao.findByDefaultId(defaultSubCategory.getId()).stream().map(subCategory -> this.getFullSubCategory(stakeholder, subCategory)).forEach(subCategory -> {
this.reorderCharts(stakeholder, new SubCategory(subCategory),
this.commonService.reorder(defaultSections, subCategory.getCharts().stream().map(section -> (Common) section).collect(Collectors.toList())));
});
@ -258,30 +255,31 @@ public class SubCategoryService {
public void addSubCategory(Category category, String id) {
category.addSubCategory(id);
category.setUpdateDate(new Date());
this.categoryDAO.save(category);
}
public void removeSubCategory(String id) {
this.categoryDAO.findBySubCategoriesContaining(id).forEach(category -> {
this.categoryDAO.findBySubCategory(id).forEach(category -> {
category.removeSubCategory(id);
category.setUpdateDate(new Date());
this.categoryDAO.save(category);
});
}
public SubCategoryFull changeVisibility(String type, String alias, SubCategoryFull subCategory, Visibility visibility, Boolean propagate) {
if(this.commonService.hasEditAuthority(type, alias)) {
subCategory.setVisibility(visibility);
public SubCategoryFull changeVisibility(Stakeholder stakeholder, SubCategoryFull subCategory, Visibility visibility, Boolean propagate) {
if(this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
Stakeholder saved = this.commonService.changeVisibility(stakeholder, subCategory, visibility, stakeholderDAO);
if(propagate) {
subCategory.setNumbers(subCategory.getNumbers().stream()
.map(section -> this.sectionService.changeVisibility(type, alias, section, visibility))
.map(section -> this.sectionService.changeVisibility(saved, section, visibility))
.collect(Collectors.toList()));
subCategory.setCharts(subCategory.getCharts().stream()
.map(section -> this.sectionService.changeVisibility(type, alias, section, visibility))
.map(section -> this.sectionService.changeVisibility(saved, section, visibility))
.collect(Collectors.toList()));
}
subCategory.update(this.save(new SubCategory(subCategory)));
if(!stakeholder.isReference()) {
subCategory.update(this.save(new SubCategory(subCategory)));
}
return subCategory;
} else {
this.commonService.unauthorized("Change subCategory visibility: You are not authorized to update subCategory with id: " + subCategory.getId());
@ -289,8 +287,8 @@ public class SubCategoryService {
return null;
}
public SubCategoryFull changeVisibility(String type, String alias, SubCategory subCategory, Visibility visibility, Boolean propagate) {
SubCategoryFull subCategoryFull = this.getFullSubCategory(type, alias, subCategory);
return this.changeVisibility(type, alias, subCategoryFull, visibility, propagate);
public SubCategoryFull changeVisibility(Stakeholder stakeholder, SubCategory subCategory, Visibility visibility, Boolean propagate) {
SubCategoryFull subCategoryFull = this.getFullSubCategory(stakeholder, subCategory);
return this.changeVisibility(stakeholder, subCategoryFull, visibility, propagate);
}
}

View File

@ -1,12 +1,12 @@
package eu.dnetlib.uoamonitorservice.service;
import eu.dnetlib.uoaauthorizationlibrary.authorization.exceptions.http.NotFoundException;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.dao.TopicDAO;
import eu.dnetlib.uoamonitorservice.dto.TopicFull;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import eu.dnetlib.uoamonitorservice.entities.Topic;
import eu.dnetlib.uoamonitorservice.generics.Common;
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
import eu.dnetlib.uoamonitorservice.primitives.Visibility;
import org.springframework.beans.factory.annotation.Autowired;
@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
@ -35,29 +36,38 @@ public class TopicService {
}
public Topic find(String id) {
return dao.findById(id).orElseThrow(() -> new EntityNotFoundException("Topic with id: " + id + " not found"));
return dao.findById(id).orElseThrow(() -> new NotFoundException("Topic with id: " + id + " not found"));
}
public Topic findByPath(StakeholderService service, String stakeholderId, String topicId) {
Stakeholder stakeholder = service.findByPath(stakeholderId);
if(stakeholder.isReference()) {
stakeholder = service.findByPath(stakeholder.getDefaultId());
}
return findByPath(stakeholder, topicId);
}
public Topic findByPath(Stakeholder stakeholder, String topicId) {
if (!stakeholder.getTopics().contains(topicId)) {
throw new PathNotValidException("Topic with id: " + topicId + " not found in Stakeholder: " + stakeholder.getId());
}
return this.dao.findById(topicId).orElseThrow(() -> new EntityNotFoundException("Topic with id: " + topicId + " not found"));
return this.dao.findById(topicId).orElseThrow(() -> new NotFoundException("Topic with id: " + topicId + " not found"));
}
public TopicFull getFullTopic(String type, String alias, Topic topic) {
if (commonService.hasVisibilityAuthority(type, alias, topic)) {
public TopicFull getFullTopic(Stakeholder stakeholder, Topic topic) {
topic.override(stakeholder);
if (commonService.hasVisibilityAuthority(stakeholder.getType(), stakeholder.getAlias(), topic)) {
return new TopicFull(topic, topic.getCategories().stream()
.map(categoryId -> this.categoryService.getFullCategory(type, alias, categoryId))
.map(categoryId -> this.categoryService.getFullCategory(stakeholder, categoryId))
.collect(Collectors.toList()));
} else {
return null;
}
}
public TopicFull getFullTopic(String type, String alias, String id) {
public TopicFull getFullTopic(Stakeholder stakeholder, String id) {
Topic topic = this.find(id);
return this.getFullTopic(type, alias, topic);
return this.getFullTopic(stakeholder, topic);
}
public String build(String id) {
@ -76,19 +86,16 @@ public class TopicService {
}
public Topic save(Topic topic) {
if(topic.getId() != null) {
if (topic.getId() != null) {
topic.setCategories(this.find(topic.getId()).getCategories());
} else {
topic.setCreationDate(new Date());
}
topic.setUpdateDate(new Date());
topic.getCategories().forEach(this.categoryService::find);
return this.dao.save(topic);
}
public TopicFull save(Stakeholder stakeholder, Topic topic) {
if(topic.getId() != null) {
if(this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
if (topic.getId() != null) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
topic.setCategories(this.find(topic.getId()).getCategories());
this.updateChildren(topic);
topic = this.save(topic);
@ -96,7 +103,7 @@ public class TopicService {
this.commonService.unauthorized("You are not authorized to update stakeholder with id: " + stakeholder.getId());
}
} else {
if(this.commonService.hasCreateAuthority(stakeholder.getType())) {
if (this.commonService.hasCreateAuthority(stakeholder.getType())) {
topic = this.save(topic);
this.createChildren(stakeholder, topic);
this.addTopic(stakeholder, topic.getId());
@ -104,13 +111,13 @@ public class TopicService {
this.commonService.unauthorized("You are not authorized to create a topic in stakeholder with id: " + stakeholder.getId());
}
}
return this.getFullTopic(stakeholder.getType(), stakeholder.getAlias(), topic);
return this.getFullTopic(stakeholder, topic);
}
public void createChildren(Stakeholder defaultStakeholder, Topic topic) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.save(stakeholder, topic.copy());
});
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.save(stakeholder, topic.copy());
});
}
public void updateChildren(Topic topic) {
@ -120,15 +127,14 @@ public class TopicService {
}
public TopicFull reorderCategories(Stakeholder stakeholder, Topic topic, List<String> categories) {
if(this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
categories.forEach(this.categoryService::find);
if (topic.getCategories().size() == categories.size() && new HashSet<>(topic.getCategories()).containsAll(categories)) {
topic.setCategories(categories);
this.reorderChildren(stakeholder, topic, categories);
topic.setUpdateDate(new Date());
return this.getFullTopic(stakeholder.getType(), stakeholder.getAlias(), this.dao.save(topic));
return this.getFullTopic(stakeholder, this.dao.save(topic));
} else {
throw new EntityNotFoundException("Some categories dont exist in the topic with id " + topic.getId());
throw new NotFoundException("Some categories dont exist in the topic with id " + topic.getId());
}
} else {
this.commonService.unauthorized("You are not authorized to reorder categories in topic with id: " + topic.getId());
@ -138,7 +144,7 @@ public class TopicService {
public void reorderChildren(Stakeholder defaultStakeholder, Topic defaultTopic, List<String> defaultCategories) {
this.stakeholderDAO.findByDefaultIdAndCopyIsTrue(defaultStakeholder.getId()).forEach(stakeholder -> {
this.dao.findByDefaultId(defaultTopic.getId()).stream().map(topic -> this.getFullTopic(stakeholder.getType(), stakeholder.getAlias(), topic)).forEach(topic -> {
this.dao.findByDefaultId(defaultTopic.getId()).stream().map(topic -> this.getFullTopic(stakeholder, topic)).forEach(topic -> {
this.reorderCategories(stakeholder, new Topic(topic),
this.commonService.reorder(defaultCategories, topic.getCategories().stream().map(category -> (Common) category).collect(Collectors.toList())));
});
@ -169,27 +175,28 @@ public class TopicService {
public void addTopic(Stakeholder stakeholder, String id) {
stakeholder.addTopic(id);
stakeholder.setUpdateDate(new Date());
this.stakeholderDAO.save(stakeholder);
}
public void removeTopic(String id) {
this.stakeholderDAO.findByTopicsContaining(id).forEach(stakeholder -> {
this.stakeholderDAO.findByTopic(id).forEach(stakeholder -> {
stakeholder.removeTopic(id);
stakeholder.setUpdateDate(new Date());
this.stakeholderDAO.save(stakeholder);
});
}
public TopicFull changeVisibility(String type, String alias, TopicFull topic, Visibility visibility, Boolean propagate) {
if (this.commonService.hasEditAuthority(type, alias)) {
topic.setVisibility(visibility);
public TopicFull changeVisibility(Stakeholder stakeholder, TopicFull topic, Visibility visibility, Boolean propagate) {
if (this.commonService.hasEditAuthority(stakeholder.getType(), stakeholder.getAlias())) {
Stakeholder saved = this.commonService.changeVisibility(stakeholder, topic, visibility, stakeholderDAO);
if (propagate) {
topic.setCategories(topic.getCategories().stream()
.map(category -> this.categoryService.changeVisibility(type, alias, category, visibility, true))
.map(category -> this.categoryService.changeVisibility(saved, category, visibility, true))
.collect(Collectors.toList()));
}
topic.update(this.save(new Topic(topic)));
if(!stakeholder.isReference()) {
topic.update(this.save(new Topic(topic)));
}
return topic;
} else {
this.commonService.unauthorized("Change topic visibility: You are not authorized to update topic with id: " + topic.getId());
@ -197,8 +204,23 @@ public class TopicService {
return null;
}
public TopicFull changeVisibility(String type, String alias, Topic topic, Visibility visibility, Boolean propagate) {
TopicFull topicFull = this.getFullTopic(type, alias, topic);
return this.changeVisibility(type, alias, topicFull, visibility, propagate);
public TopicFull changeVisibility(Stakeholder stakeholder, Topic topic, Visibility visibility, Boolean propagate) {
TopicFull topicFull = this.getFullTopic(stakeholder, topic);
return this.changeVisibility(stakeholder, topicFull, visibility, propagate);
}
public TopicFull restoreDefault(Stakeholder stakeholder, Topic topic) {
if(!stakeholder.isReference()) {
stakeholder.removeOverride(topic.getId());
return this.getFullTopic(stakeholderDAO.save(stakeholder), topic);
} else if(!stakeholder.isDefault()) {
String id = topic.getId();
List<String> categories = topic.getCategories();
topic = this.find(topic.getDefaultId()).copy();
topic.setId(id);
topic.setCategories(categories);
return this.getFullTopic(stakeholder, this.save(topic));
}
return this.getFullTopic(stakeholder, topic);
}
}

View File

@ -0,0 +1,59 @@
package eu.dnetlib.uoamonitorservice.utils;
import java.lang.reflect.Field;
public class GenericAccessor {
public static <T> void setField(Object obj, String fieldName, T value) {
try {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true); // Allows access to private fields
if (field.getType().isEnum()) {
if (value instanceof String stringValue) {
Enum<?> enumValue = getEnumValue(field.getType(), stringValue);
field.set(obj, enumValue);
} else if (field.getType().isAssignableFrom(value.getClass())) {
// Directly assign if types match
field.set(obj, value);
} else {
throw new IllegalArgumentException("Incompatible types: cannot assign " + value.getClass().getName() +
" to " + field.getType().getName());
}
} else {
// Handle other field types normally
field.set(obj, value);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
System.err.println("Error setting field: " + e.getMessage());
}
}
public static Object getField(Object obj, String fieldName) {
try {
Field field = findField(obj.getClass(), fieldName); // Updated to search in superclasses
field.setAccessible(true); // Allows access to private fields
return field.get(obj);
} catch (NoSuchFieldException | IllegalAccessException e) {
System.err.println("Error getting field: " + e.getMessage());
return null;
}
}
private static Field findField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
Class<?> currentClass = clazz;
while (currentClass != null) {
try {
return currentClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
currentClass = currentClass.getSuperclass();
}
}
throw new NoSuchFieldException("Field '" + fieldName + "' not found in class hierarchy of " + clazz.getName());
}
// Safely get the Enum value using generics
@SuppressWarnings("unchecked")
private static <E extends Enum<E>> E getEnumValue(Class<?> enumClass, String value) {
return Enum.valueOf((Class<E>) enumClass, value);
}
}

View File

@ -1,24 +1,2 @@
#mongodb
#beta
#spring.data.mongodb.host=beta.services.openaire.eu
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=openairemonitor
#production
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=openairemonitor
#spring.data.mongodb.authentication-database=openairemonitor
#spring.data.mongodb.username=dnet8480
#spring.data.mongodb.password=...
#dev
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=openaire_monitor
#static properties
api.title = Uoa Monitor Service Documentation Swagger
api.description = Uoa Monitor Service is a service which serves and saves dynamic content and indicators (numbers & charts)
api.version = ${project.version}
# temp until refactoring the code in admin tools library
spring.main.allow-circular-references=true

View File

@ -1,27 +1,10 @@
#dev
monitorservice.host = smtp.gmail.com
monitorservice.port = 587
monitorservice.auth = true
monitorservice.from = openaire.test@gmail.com
monitorservice.username = openaire.test@gmail.com
monitorservice.password = ...
monitorservice.mongodb.host=localhost
monitorservice.mongodb.port=27017
monitorservice.mongodb.database=openaire_monitor3
monitorservice.globalVars.buildDate=@timestamp@
monitorservice.globalVars.version=@version@
## API Documentation Properties
api.title = Uoa Monitor Service
api.description = Uoa Monitor Service is a service which serves and saves dynamic content and indicators (numbers & charts)
api.version = ${project.version}
monitor-service.global-vars.buildDate=@timestamp@
monitor-service.global-vars.version=@version@
#beta
#monitorservice.userInfoUrl = https://beta.services.openaire.eu/uoa-user-management/api/users/getUserInfo?accessToken=
#monitorservice.originServer = .openaire.eu
#monitorservice.host = bwnmail.icm.edu.pl
#monitorservice.port = 25
#monitorservice.auth = false
#monitorservice.username = no-reply@openaire.eu
#monitorservice.from = no-reply@beta.openaire.eu
#monitorservice.password = ...
#production
#monitorservice.userInfoUrl = https://services.openaire.eu/uoa-user-management/api/users/getUserInfo?accessToken=
#monitorservice.originServer = .openaire.eu