diff --git a/pom.xml b/pom.xml
index 52759cb..834ad4f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -61,10 +61,6 @@
eu.dnetlib.uoamonitorservice.application.UoaMonitorServiceApplication
true
-
-
-
-
@@ -73,12 +69,6 @@
repackage
-
-
-
-
-
-
diff --git a/scripts/2020-10-22.js b/scripts/2020-10-22.js
new file mode 100644
index 0000000..2f06f0d
--- /dev/null
+++ b/scripts/2020-10-22.js
@@ -0,0 +1,245 @@
+function upperCaseEnumValues() {
+ stakeholders = db.stakeholder.find().map(function (stakeholders) {
+ return stakeholders;
+ });
+ for(var i=0; i"+content+"
",
+ "isActive" : true
+ }
+ );
+
+ print("div help text for divId 'footer' added for "+portalType +" (id: "+ portal._id + " - pid: " + portal.pid + " - footer divId id: "+footerDivIdID + ")");
+ }
+}
+
+use monitordb;
+
+addHomePageInPortalType("funder");
+addFooterDivIdForPortalType("funder");
+addFooterHelpTextForPortalType("funder");
+addHomePageInPortalType("ri");
+addFooterDivIdForPortalType("ri");
+addFooterHelpTextForPortalType("ri");
+addHomePageInPortalType("organization");
+addFooterDivIdForPortalType("organization");
+addFooterHelpTextForPortalType("organization");
diff --git a/scripts/2023-05-30.js b/scripts/2023-05-30.js
new file mode 100644
index 0000000..4b5a508
--- /dev/null
+++ b/scripts/2023-05-30.js
@@ -0,0 +1,182 @@
+function statsProfileOfIndicatorsAsVariable() {
+ print("statsProfileOfIndicatorsAsVariable");
+
+ numOfNumbers = 0;
+ numOfCharts = 0;
+ numOfNonMonitorProfiles = 0;
+ numOfMonitorProfiles = 0;
+ numOfNoProfiles = 0;
+ differentProfiles = new Set();
+
+ // indicators = db.indicator.find({"type": "chart"}).map(function (indicator) {
+ // indicators = db.indicator.find({"type": "number"}).map(function (indicator) {
+ indicators = db.indicator.find().map(function (indicator) {
+ return indicator;
+ });
+
+ print(indicators.length);
+
+ for (var i = 0; i < indicators.length; i++) {
+ indicator = indicators[i];
+
+ indicatorPaths = indicator.indicatorPaths;
+ if(indicatorPaths) {
+ for (var j = 0; j < indicatorPaths.length; j++) {
+ indicatorPath = indicatorPaths[j];
+ chartObjectStr = "";
+ // if(indicator.type == "chart") {
+ chartObjectStr = indicatorPath.chartObject;
+ // chartObject = JSON.parse(chartObjectStr);
+ if(indicator.type == "chart") {
+ numOfCharts++;
+ } else {
+ numOfNumbers++;
+ }
+
+ // if(i==0) {
+ // if(chartObject.chartDescription != null && chartObject.chartDescription.queries != null) {
+ // print(chartObject.chartDescription.queries.length);
+ // for(var z = 0; z < chartObject.chartDescription.queries.length; z++) {
+ // query = chartObject.chartDescription.queries[z].query;
+ // print(query.profile);
+ // query.profile = "((__statsProfile__))";
+ // }
+ // }
+ // indicatorPath.chartObject = JSON.stringify(chartObject);
+
+ if(chartObjectStr != null) {
+ var included = chartObjectStr.includes('"profile":"monitor"');
+ if (!included) {
+ numOfNonMonitorProfiles++;
+ print("Indicator with id: " + indicator._id + " has not monitor profile.");
+ } else {
+ numOfMonitorProfiles++;
+ }
+
+ splitted = chartObjectStr.split('"profile":"');
+ if (splitted.length == 1) {
+ numOfNoProfiles++;
+ }
+ for (var z = 1; z < splitted.length; z = z + 2) {
+ prof = splitted[z].split('"')[0];
+ differentProfiles.add(prof);
+ }
+
+ chartObjectStr = chartObjectStr.split('"profile":"monitor"').join('"profile":"((__profile__))"');
+ chartObjectStr = chartObjectStr.split('"profile":"OpenAIRE All-inclusive"').join('"profile":"((__profile__))"');
+ chartObjectStr = chartObjectStr.split('"profile":"OpenAIRE Monitor"').join('"profile":"((__profile__))"');
+ indicatorPath.chartObject = chartObjectStr;
+ } else {
+ print("Indicator with id: " + indicator._id + " has no chartObject");
+ }
+ }
+ }
+
+ // save indicator
+ db.indicator.save(indicator);
+ }
+ print("\n");
+ print("numOfNumbers: "+numOfNumbers);
+ print("numOfCharts: "+numOfCharts);
+ print("numOfMonitorProfiles: "+numOfMonitorProfiles);
+ print("numOfNonMonitorProfiles: "+numOfNonMonitorProfiles);
+ print("numOfNoProfiles: "+numOfNoProfiles);
+ print("Different profiles are: ");
+ for (var item of differentProfiles) {
+ print(item);
+ }
+}
+
+function addFundingLevelInFilters(filter) {
+ if(filter.groupFilters && filter.groupFilters.length > 0) {
+ var index = filter.groupFilters.findIndex(filter => filter.field.includes('project'));
+ if(index !== -1) {
+ print('before: ' + JSON.stringify(filter));
+ var prefix = filter.groupFilters[index].field.substring(0, filter.groupFilters[index].field.indexOf('project'));
+ if(!filter.groupFilters.find(filter => filter.field === prefix + "project.funding level 1")) {
+ filter.groupFilters.push({
+ "field": prefix + "project.funding level 1",
+ "type": "contains",
+ "values": [
+ '((__index_shortName__))'
+ ]
+ });
+ print('after: ' + JSON.stringify(filter));
+ } else {
+ print('Already added');
+ }
+ }
+ return filter;
+ }
+}
+
+function addFundingStreamInDefaultMSCA() {
+ print("addFundingStreamInDefaultMSCA")
+
+ var stakeholder = db.stakeholder.findOne({"alias": "default-fl1"});
+ if(stakeholder) {
+ stakeholder.topics.forEach((topic) => {
+ var topicObj = db.topic.findOne({"_id": ObjectId(topic)});
+ topicObj.categories.forEach((category) => {
+ var categoryObj = db.category.findOne({"_id": ObjectId(category)});
+ categoryObj.subCategories.forEach((subCategory) => {
+ var subCategoryObj = db.subCategory.findOne({"_id": ObjectId(subCategory)});
+ subCategoryObj.numbers.forEach((number) => {
+ var section = db.section.findOne({"_id": ObjectId(number)});
+ section.indicators.forEach((indicator) => {
+ var indicatorObject = db.indicator.findOne({"_id": ObjectId(indicator)});
+ if(indicatorObject.indicatorPaths[0].parameters) {
+ indicatorObject.indicatorPaths[0].parameters['index_shortName'] = stakeholder.index_shortName.toLowerCase();
+ if(indicatorObject.indicatorPaths[0] && indicatorObject.indicatorPaths[0].chartObject) {
+ var json = JSON.parse(indicatorObject.indicatorPaths[0].chartObject);
+ if(json.series && json.series.length > 0) {
+ json.series.forEach(query => {
+ if(query.query && query.query.filters && query.query.filters.length > 0) {
+ query.query.filters.forEach(filter => {
+ filter = addFundingLevelInFilters(filter);
+ });
+ }
+ });
+ indicatorObject.indicatorPaths[0].chartObject = JSON.stringify(json);
+ db.indicator.save(indicatorObject);
+ }
+ }
+ }
+ });
+ });
+ subCategoryObj.charts.forEach((chart) => {
+ var section = db.section.findOne({"_id": ObjectId(chart)});
+ section.indicators.forEach((indicator) => {
+ var indicatorObject = db.indicator.findOne({"_id": ObjectId(indicator)});
+ if(indicatorObject.indicatorPaths[0].parameters) {
+ indicatorObject.indicatorPaths[0].parameters['index_shortName'] = stakeholder.index_shortName.toLowerCase();
+ if (indicatorObject.indicatorPaths[0] && indicatorObject.indicatorPaths[0].chartObject) {
+ var json = JSON.parse(indicatorObject.indicatorPaths[0].chartObject);
+ if (json.chartDescription && json.chartDescription.queries && json.chartDescription.queries.length > 0) {
+ json.chartDescription.queries.forEach(query => {
+ if (query.query && query.query.filters && query.query.filters.length > 0) {
+ query.query.filters.forEach(filter => {
+ filter = addFundingLevelInFilters(filter);
+ });
+ }
+ });
+ indicatorObject.indicatorPaths[0].chartObject = JSON.stringify(json);
+ db.indicator.save(indicatorObject);
+ }
+ }
+ }
+ });
+ });
+ });
+
+ });
+ });
+ } else {
+ print("Profile doesn't exist")
+ }
+}
+
+use monitordb;
+
+statsProfileOfIndicatorsAsVariable();
+addFundingStreamInDefaultMSCA();
diff --git a/scripts/2024-02-27.js b/scripts/2024-02-27.js
new file mode 100644
index 0000000..5f84810
--- /dev/null
+++ b/scripts/2024-02-27.js
@@ -0,0 +1,16 @@
+function deleteIndexParameters() {
+ var indicators = db.indicator.find();
+ indicators.forEach(indicator => {
+ indicator.indicatorPaths.forEach(path => {
+ if(path.parameters) {
+ delete path.parameters['index_id'];
+ delete path.parameters['index_name'];
+ delete path.parameters['index_shortName'];
+ }
+ db.indicator.save(indicator);
+ });
+ })
+}
+
+use irish-prod;
+deleteIndexParameters();
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/SwaggerConfig.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/SwaggerConfig.java
index 3387c9d..84d90a6 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/SwaggerConfig.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/SwaggerConfig.java
@@ -41,7 +41,6 @@ public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
-// .globalOperationParameters(globalParameterList())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("eu.dnetlib.uoamonitorservice.controllers"))
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java
index 42c31fd..676f4ea 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java
@@ -12,9 +12,8 @@ import org.springframework.data.mongodb.MongoDbFactory;
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;
-//"uoahelptexts"
+
@Configuration
@EnableMongoRepositories(basePackages = {"eu.dnetlib.uoamonitorservice.dao", "eu.dnetlib.uoaadmintoolslibrary.dao"})
public class MongoConnection {
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/CategoryController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/CategoryController.java
index d2f0d23..8f53d88 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/CategoryController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/CategoryController.java
@@ -1,20 +1,19 @@
package eu.dnetlib.uoamonitorservice.controllers;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
-import eu.dnetlib.uoamonitorservice.dao.*;
-import eu.dnetlib.uoamonitorservice.entities.*;
-import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
-import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
+import eu.dnetlib.uoamonitorservice.dto.CategoryFull;
+import eu.dnetlib.uoamonitorservice.entities.Category;
+import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
+import eu.dnetlib.uoamonitorservice.entities.Topic;
+import eu.dnetlib.uoamonitorservice.primitives.Visibility;
+import eu.dnetlib.uoamonitorservice.service.CategoryService;
+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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
import java.util.List;
@RestController
@@ -22,205 +21,29 @@ import java.util.List;
public class CategoryController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private RolesUtils rolesUtils;
+ private final StakeholderService stakeholderService;
+ private final TopicService topicService;
+ private final CategoryService categoryService;
@Autowired
- private StakeholderDAO stakeholderDAO;
-
- @Autowired
- private TopicDAO topicDAO;
-
- @Autowired
- private CategoryDAO categoryDAO;
-
- @Autowired
- private SubCategoryDAO subCategoryDAO;
-
- @Autowired
- private SubCategoryController subCategoryController;
-
- public Category buildCategory(Category categoryFull) {
- Category category = new Category<>(categoryFull);
-
- List subCategories = new ArrayList<>();
- List subCategoriesFull = new ArrayList<>();
- for(SubCategory> subCategory : categoryFull.getSubCategories()) {
- SubCategory> subcategoryFull = subCategoryController.buildSubCategory(subCategory);
- subCategoriesFull.add(subcategoryFull);
- subCategories.add(subcategoryFull.getId());
- }
- categoryFull.setSubCategories(subCategoriesFull);
- category.setSubCategories(subCategories);
-
- Date date = new Date();
- category.setCreationDate(date);
- category.setUpdateDate(date);
-
- categoryFull.setCreationDate(date);
- categoryFull.setUpdateDate(date);
-
- categoryDAO.save(category);
-
- categoryFull.setId(category.getId());
- return categoryFull;
+ public CategoryController(StakeholderService stakeholderService, TopicService topicService, CategoryService categoryService) {
+ this.stakeholderService = stakeholderService;
+ this.topicService = topicService;
+ this.categoryService = categoryService;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/save", method = RequestMethod.POST)
- public Category saveCategory(@PathVariable("stakeholderId") String stakeholderId,
+ public CategoryFull saveCategory(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
- @RequestBody Category categoryFull) {
+ @RequestBody CategoryFull categoryFull) {
log.debug("save category");
- log.debug("Alias: "+categoryFull.getAlias() + " - Id: "+categoryFull.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- if(stakeholder != null) {
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Save Category: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- Category oldCategory = null;
- if(categoryFull.getId() != null) {
- oldCategory = categoryDAO.findById(categoryFull.getId());
- if(oldCategory == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("save category: Category with id: " + categoryFull.getId() + " not found");
- }
- }
-
- Topic topic = topicDAO.findById(topicId);
- if(topic != null) {
- if(stakeholder.getTopics().contains(topicId)) {
- Category category = new Category<>(categoryFull);
-
- Date date = new Date();
- category.setUpdateDate(date);
- categoryFull.setUpdateDate(date);
-
- List subCategories = new ArrayList<>();
-
- // if category not exists (no id), create a new default subcategory, identical to category
- if(categoryFull.getId() == null) {
- category.setCreationDate(date);
- categoryFull.setCreationDate(date);
-
- SubCategory subCategory = new SubCategory<>();
- subCategory.createOverviewSubCategory(categoryFull);
-
- subCategoryDAO.save(subCategory);
-
- List subCategoriesFull = categoryFull.getSubCategories();
- subCategoriesFull.add(subCategory);
-
- for(SubCategory oldSubCategory : subCategoriesFull) {
- subCategories.add(oldSubCategory.getId());
- }
- } else {
- for(String subCategoryId : oldCategory.getSubCategories()) {
- SubCategory subCategory = subCategoryDAO.findById(subCategoryId);
- if (subCategory == null) {
- // EXCEPTION - SubCategory not found
- throw new EntityNotFoundException("Save category: SubCategory with id: "+subCategoryId+" not found (subcategory exists in category: "+category.getId()+")");
- }
- subCategories.add(subCategory.getId());
- }
- }
-
- category.setSubCategories(subCategories);
-
- if(stakeholder.getDefaultId() == null) {
- if(categoryFull.getId() == null) {
- categoryDAO.save(category);
- onSaveDefaultCategory(category, topicId);
- } else {
- onUpdateDefaultCategory(category, oldCategory);
- categoryDAO.save(category);
- }
- } else {
- categoryDAO.save(category);
- }
-
- List categories = topic.getCategories();
- int index = categories.indexOf(category.getId());
- if(index == -1) {
- categories.add(category.getId());
- topicDAO.save(topic);
- log.debug("Category saved!");
-
- categoryFull.setId(category.getId());
- }
-
- subCategories = null;
- category = null;
- } else {
- // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
- throw new PathNotValidException("Save category: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
- }
- } else {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Save category: Topic with id: "+topicId+" not found");
- }
- } else {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Save category: Stakeholder with id: "+stakeholderId+" not found");
- }
- return categoryFull;
+ log.debug("Alias: " + categoryFull.getAlias() + " - Id: " + categoryFull.getId() + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId);
+ Stakeholder stakeholder = stakeholderService.findByPath(stakeholderId);
+ Topic topic = topicService.findByPath(stakeholder, topicId);
+ return this.categoryService.save(stakeholder, topic, new Category(categoryFull));
}
- public void onSaveDefaultCategory(Category category, String topicId) {
- log.debug("On save default category");
-
- List topics = topicDAO.findByDefaultId(topicId);
- for(Topic topic : topics) {
- Category categoryNew = new Category();
- categoryNew.copyFromDefault(category);
-
- categoryDAO.save(categoryNew);
-
- List categories = topic.getCategories();
- categories.add(categoryNew.getId());
-
- topicDAO.save(topic);
- }
- String subCategoryOverviewId = category.getSubCategories().get(0);
- SubCategory subCategoryOverview = subCategoryDAO.findById(subCategoryOverviewId);
- subCategoryController.onSaveDefaultSubCategory(subCategoryOverview, category.getId());
- }
-
- public void onUpdateDefaultCategory(Category category, Category oldCategory) {
- log.debug("On update default category");
-
- List categories = categoryDAO.findByDefaultId(category.getId());
- boolean changed = false;
- for(Category categoryBasedOnDefault : categories) {
- if(category.getName() != null && !category.getName().equals(categoryBasedOnDefault.getName())
- && (oldCategory.getName() == null || oldCategory.getName().equals(categoryBasedOnDefault.getName()))) {
-
- categoryBasedOnDefault.setName(category.getName());
- categoryBasedOnDefault.setAlias(category.getAlias());
- changed = true;
- }
- if(category.getDescription() != null && !category.getDescription().equals(categoryBasedOnDefault.getDescription())
- && (oldCategory.getDescription() == null || oldCategory.getDescription().equals(categoryBasedOnDefault.getDescription()))) {
-
- categoryBasedOnDefault.setDescription(category.getDescription());
- changed = true;
- }
-
- if(!changed) {
-// break;
- continue;
- }
-
-// categoryBasedOnDefault.setName(category.getName());
-// categoryBasedOnDefault.setDescription(category.getDescription());
- categoryBasedOnDefault.setUpdateDate(category.getUpdateDate());
- categoryDAO.save(categoryBasedOnDefault);
- }
- }
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/delete", method = RequestMethod.DELETE)
@@ -229,343 +52,37 @@ public class CategoryController {
@PathVariable("categoryId") String categoryId,
@RequestParam(required = false) String children) {
log.debug("delete category");
- log.debug("Id: "+categoryId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- if(stakeholder != null) {
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Delete category: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- Topic topic = topicDAO.findById(topicId);
- if(topic != null) {
- if(stakeholder.getTopics().contains(topicId)) {
-
- Category category = categoryDAO.findById(categoryId);
- if(category != null) {
-
- if(category.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(stakeholder.getType())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Delete category: You are not authorized to delete a default Category in stakeholder with id: "+stakeholderId);
- }
-
-
- List categories = topic.getCategories();
- int index = categories.indexOf(categoryId);
- if(index != -1) {
- // this category belongs in default profile
- if(topic.getDefaultId() == null && children != null) {
- onDeleteDefaultCategory(categoryId, topicId, children);
- }
-
-// for(String subCategoryId : category.getSubCategories()) {
-// SubCategory subcategory = subCategoryDAO.findById(subCategoryId);
-// if(subcategory == null) {
-// // EXCEPTION - SubCategory not found
-// throw new EntityNotFoundException("Delete category: SubCategory with id: "+subCategoryId+" not found (subcategory exists in category: "+categoryId+")");
-// }
-//
-// for(String chartSectionId : subcategory.getCharts()) {
-// Section chartSection = sectionDAO.findById(chartSectionId);
-// if (chartSection == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Delete topic: Section with id: "+chartSectionId+" not found (section exists in subcategory: "+subCategoryId+")");
-// }
-//
-// for (String chartId : chartSection.getIndicators()) {
-// indicatorDAO.delete(chartId);
-// }
-// subcategory.setCharts(null);
-// sectionDAO.delete(chartSectionId);
-// }
-//
-// for(String numberSectionId : subcategory.getNumbers()) {
-// Section numberSection = sectionDAO.findById(numberSectionId);
-// if (numberSection == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Delete topic: Section with id: "+numberSectionId+" not found (section exists in subcategory: "+subCategoryId+")");
-// }
-//
-// for (String numberId : numberSection.getIndicators()) {
-// indicatorDAO.delete(numberId);
-// }
-// subcategory.setNumbers(null);
-// sectionDAO.delete(numberSectionId);
-// }
-//
-// subCategoryDAO.delete(subCategoryId);
-// }
- subCategoryController.deleteTree(category);
-
- category.setSubCategories(null);
-
- categories.remove(index);
- topicDAO.save(topic);
-
- categoryDAO.delete(categoryId);
- log.debug("Category deleted!");
- } else {
- // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
- throw new PathNotValidException("Delete category: Category with id: "+categoryId+" not found in Topic: "+topicId);
- }
-
- } else {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Delete category: Category with id: "+categoryId+" not found");
- }
- } else {
- // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
- throw new PathNotValidException("Delete category: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
- }
- } else {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Delete category: Topic with id: "+topicId+" not found");
- }
- } else {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Delete category: Stakeholder with id: "+stakeholderId+" not found");
- }
- return true;
- }
-
-
- public boolean onDeleteDefaultCategory(String defaultCategoryId, String defaultTopicId, String children) {
- if(children.equals("delete")) {
- List topics = topicDAO.findByDefaultId(defaultTopicId);
- List categories = categoryDAO.findByDefaultId(defaultCategoryId);
-
- for(Topic topic : topics) {
- Iterator categoriesIterator = categories.iterator();
- while(categoriesIterator.hasNext()) {
- Category category = categoriesIterator.next();
-
- String categoryId = category.getId();
-
- if(topic.getCategories() != null && topic.getCategories().contains(categoryId)) {
- categoriesIterator.remove();
-
- topic.getCategories().remove(categoryId);
- topicDAO.save(topic);
-
- subCategoryController.deleteTree(category);
-
- categoryDAO.delete(categoryId);
- log.debug("Category with id: "+categoryId+" deleted!");
-
- break;
- }
- }
- }
- } else if(children.equals("disconnect")) {
- List categories = categoryDAO.findByDefaultId(defaultCategoryId);
- for(Category category : categories) {
- subCategoryController.disConnectTree(category);
-
- category.setDefaultId(null);
- categoryDAO.save(category);
-
- log.debug("DefaultId for Category with id: "+category.getId()+" empty!");
- }
- }
+ log.debug("Id: " + categoryId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, topicId);
+ Category category = this.categoryService.findByPath(topic, categoryId);
+ this.categoryService.delete(stakeholder.getType(), category, true);
return true;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/reorder", method = RequestMethod.POST)
- public List reorderCategories(@PathVariable("stakeholderId") String stakeholderId,
- @PathVariable("topicId") String topicId,
- @RequestBody List categories) {
+ public List reorderCategories(@PathVariable("stakeholderId") String stakeholderId,
+ @PathVariable("topicId") String topicId,
+ @RequestBody List categories) {
log.debug("reorder categories");
- log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId);
-
- Topic topic = checkForExceptions(stakeholderId, topicId);
-
- List oldCategories = topic.getCategories();
- for (String categoryId : oldCategories) {
- if (!categories.contains(categoryId)) {
- categories.add(categoryId);
- }
- }
- topic.setCategories(categories);
-
- List categoriesFull = new ArrayList<>();
- for(String categoryId : categories) {
- Category category = categoryDAO.findById(categoryId);
- if(category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Reorder Categories: Category with id: " + categoryId + " not found");
- }
- categoriesFull.add(category);
- }
-
- topicDAO.save(topic);
- log.debug("Categories reordered!");
-
- return categoriesFull;
+ 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();
}
-// @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/toggle-status", method = RequestMethod.POST)
-// public Boolean toggleCategoryStatus(@PathVariable("stakeholderId") String stakeholderId,
-// @PathVariable("topicId") String topicId,
-// @PathVariable("categoryId") String categoryId) {
-// log.debug("toggle category status (isActive)");
-// log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId);
-//
-// Category category = categoryDAO.findById(categoryId);
-// if (category == null) {
-// // EXCEPTION - Category not found
-// throw new EntityNotFoundException("Toggle category status: Category with id: "+categoryId+" not found");
-// }
-// category.setIsActive(!category.getIsActive());
-//
-// this.toggleCategory(stakeholderId, topicId, category);
-//
-// return category.getIsActive();
-// }
-//
-// @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/toggle-access", method = RequestMethod.POST)
-// public Boolean toggleCategoryAccess(@PathVariable("stakeholderId") String stakeholderId,
-// @PathVariable("topicId") String topicId,
-// @PathVariable("categoryId") String categoryId) {
-// log.debug("toggle category access (isPublic)");
-// log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId);
-//
-// Category category = categoryDAO.findById(categoryId);
-// if (category == null) {
-// // EXCEPTION - Category not found
-// throw new EntityNotFoundException("Toggle category access: Category with id: "+categoryId+" not found");
-// }
-// category.setIsPublic(!category.getIsPublic());
-//
-// this.toggleCategory(stakeholderId, topicId, category);
-//
-// return category.getIsPublic();
-// }
-
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/change-visibility", method = RequestMethod.POST)
- public Category changeCategoryVisibility(@PathVariable("stakeholderId") String stakeholderId,
- @PathVariable("topicId") String topicId,
- @PathVariable("categoryId") String categoryId,
- @RequestParam("visibility") Visibility visibility, @RequestParam(required = false) Boolean propagate) {
- log.debug("change category visibility: "+visibility + " - toggle propagate: "+((propagate != null && propagate) ? "true" : "false"));
- log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- if (stakeholder != null) {
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Toggle category: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- Topic topic = topicDAO.findById(topicId);
- if (topic != null) {
- if (stakeholder.getTopics().contains(topicId)) {
- if (topic.getCategories().contains(categoryId)) {
- return changeVisibilityTree(categoryId, visibility, propagate);
- } else {
- // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
- throw new PathNotValidException("Toggle category: Category with id: "+categoryId+" not found in Topic: "+topicId);
- }
- } else {
- // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
- throw new PathNotValidException("Toggle category: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
- }
- } else {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Toggle category: Topic with id: "+topicId+" not found");
- }
- } else {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Toggle category: Stakeholder with id: "+stakeholderId+" not found");
- }
- }
-
- public Category changeVisibilityTree(String categoryId, Visibility visibility, Boolean propagate) {
- Category category = categoryDAO.findById(categoryId);
- if (category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Change category visibility: Category with id: "+categoryId+" not found");
- }
-
- Category categoryFull = new Category(category);
- List subCategoriesFull = new ArrayList<>();
-
- if(propagate != null && propagate) {
- for (String subCategoryId : category.getSubCategories()) {
- subCategoriesFull.add(subCategoryController.changeVisibilityTree(subCategoryId, visibility, propagate));
- }
- }
-
- category.setVisibility(visibility);
- categoryDAO.save(category);
- log.debug("Category toggled!");
-
- categoryFull.setVisibility(visibility);
- categoryFull.setSubCategories(subCategoriesFull);
-
- return categoryFull;
- }
-
-
- private Topic checkForExceptions(String stakeholderId, String topicId) {
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- if(stakeholder == null) {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("checkForExceptions category: Stakeholder with id: " + stakeholderId + " not found");
- }
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("checkForExceptions category: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- Topic topic = topicDAO.findById(topicId);
- if(topic == null) {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("checkForExceptions category: Topic with id: "+topicId+" not found");
- }
-
- if(!stakeholder.getTopics().contains(topicId)) {
- // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
- throw new PathNotValidException("checkForExceptions category: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
- }
-
- return topic;
- }
-
- public void deleteTree(Topic topic) {
- List categories = topic.getCategories();
- for(String categoryId : categories) {
- Category category = categoryDAO.findById(categoryId);
- if (category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Category delete tree: Category with id: "+categoryId+" not found (category exists in topic: "+topic.getId()+")");
- }
-
- subCategoryController.deleteTree(category);
-
- categoryDAO.delete(categoryId);
- }
- }
-
- public void disConnectTree(Topic topic) {
- List categories = topic.getCategories();
- for(String categoryId : categories) {
- Category category = categoryDAO.findById(categoryId);
- if (category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Category disconnect tree: Category with id: "+categoryId+" not found (category exists in topic: "+topic.getId()+")");
- }
-
- subCategoryController.disConnectTree(category);
-
- category.setDefaultId(null);
- categoryDAO.save(category);
- }
+ public CategoryFull changeCategoryVisibility(@PathVariable("stakeholderId") String stakeholderId,
+ @PathVariable("topicId") String topicId,
+ @PathVariable("categoryId") String categoryId,
+ @RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false") Boolean propagate) {
+ log.debug("change category visibility: " + visibility + " - toggle propagate: " + propagate);
+ log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, topicId);
+ Category category = this.categoryService.findByPath(topic, categoryId);
+ return this.categoryService.changeVisibility(stakeholder.getType(), stakeholder.getAlias(), category, visibility, propagate);
}
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/EmailController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/EmailController.java
index 24dc8c2..960fe75 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/EmailController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/EmailController.java
@@ -10,28 +10,30 @@ import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
@RestController
@CrossOrigin(origins = "*")
public class EmailController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private EmailSender emailSender;
+ private final EmailSender emailSender;
+ private final VerifyRecaptcha verifyRecaptcha;
@Autowired
- private VerifyRecaptcha verifyRecaptcha;
+ public EmailController(EmailSender emailSender, VerifyRecaptcha verifyRecaptcha) {
+ this.emailSender = emailSender;
+ this.verifyRecaptcha = verifyRecaptcha;
+ }
@RequestMapping(value = "/contact", method = RequestMethod.POST)
- public Boolean contact(@RequestBody EmailRecaptcha form) throws InvalidReCaptchaException {
+ public Boolean contact(@RequestBody EmailRecaptcha form) throws InvalidReCaptchaException {
verifyRecaptcha.processResponse(form.getRecaptcha());
Email email = form.getEmail();
- ArrayList sendTo = new ArrayList<>();
- for(String userMail: email.getRecipients()){
- sendTo.add(userMail);
- }
- return emailSender.send(sendTo, email.getSubject(), email.getBody(), false);
+ return emailSender.send(email.getRecipients(), email.getSubject(), email.getBody(), false);
}
@RequestMapping(value = "/sendMail", method = RequestMethod.POST)
@@ -40,18 +42,18 @@ public class EmailController {
String successString = "success";
String failureString = "failure";
Map> mailResults = new HashMap<>();
- boolean bcc = (optional.isPresent())?optional.get():true;
- for(String userMail:email.getRecipients()){
+ boolean bcc = optional.orElse(true);
+ for (String userMail : email.getRecipients()) {
ArrayList sendTo = new ArrayList<>();
sendTo.add(userMail);
- boolean success =emailSender.send(sendTo,email.getSubject(),email.getBody(), bcc);
- if(success){
- if(!mailResults.containsKey(successString)) {
+ boolean success = emailSender.send(sendTo, email.getSubject(), email.getBody(), bcc);
+ if (success) {
+ if (!mailResults.containsKey(successString)) {
mailResults.put(successString, new ArrayList<>());
}
mailResults.get(successString).add(userMail);
} else {
- if(!mailResults.containsKey(failureString)) {
+ if (!mailResults.containsKey(failureString)) {
mailResults.put(failureString, new ArrayList<>());
}
mailResults.get(failureString).add(userMail);
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/IndicatorController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/IndicatorController.java
index 9c33130..52f9452 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/IndicatorController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/IndicatorController.java
@@ -1,12 +1,11 @@
package eu.dnetlib.uoamonitorservice.controllers;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
-import eu.dnetlib.uoamonitorservice.dao.*;
+import eu.dnetlib.uoamonitorservice.dto.SectionFull;
+import eu.dnetlib.uoamonitorservice.dto.StakeholderFull;
import eu.dnetlib.uoamonitorservice.entities.*;
-import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
-import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
+import eu.dnetlib.uoamonitorservice.primitives.Visibility;
+import eu.dnetlib.uoamonitorservice.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@@ -14,136 +13,46 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
-import java.util.*;
+import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class IndicatorController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private RolesUtils rolesUtils;
+ private final StakeholderService stakeholderService;
+ private final TopicService topicService;
+ private final CategoryService categoryService;
+ private final SubCategoryService subCategoryService;
+ private final SectionService sectionService;
+ private final IndicatorService indicatorService;
@Autowired
- private StakeholderDAO stakeholderDAO;
-
- @Autowired
- private TopicDAO topicDAO;
-
- @Autowired
- private CategoryDAO categoryDAO;
-
- @Autowired
- private SubCategoryDAO subCategoryDAO;
-
- @Autowired
- private SectionDAO sectionDAO;
-
- @Autowired
- private IndicatorDAO indicatorDAO;
-
- @Autowired
- private SectionController sectionController;
-
- @Autowired
- private StakeholderController stakeholderController;
+ public IndicatorController(StakeholderService stakeholderService, TopicService topicService, CategoryService categoryService,
+ SubCategoryService subCategoryService, SectionService sectionService, IndicatorService indicatorService) {
+ this.stakeholderService = stakeholderService;
+ this.topicService = topicService;
+ this.categoryService = categoryService;
+ this.subCategoryService = subCategoryService;
+ this.sectionService = sectionService;
+ this.indicatorService = indicatorService;
+ }
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/save-bulk", method = RequestMethod.POST)
- public Stakeholder saveBulkIndicators(@PathVariable("stakeholderId") String stakeholderId,
- @PathVariable("topicId") String topicId,
- @PathVariable("categoryId") String categoryId,
- @PathVariable("subcategoryId") String subcategoryId,
- @RequestBody List> sections) throws UnsupportedEncodingException {
+ public StakeholderFull saveBulkIndicators(@PathVariable("stakeholderId") String stakeholderId,
+ @PathVariable("topicId") String topicId,
+ @PathVariable("categoryId") String categoryId,
+ @PathVariable("subcategoryId") String subcategoryId,
+ @RequestBody List sections) throws UnsupportedEncodingException {
log.debug("save bulk indicators");
- log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- Date date = new Date();
-
- createSectionsAndSaveBulk(date, sections, stakeholder, topicId, categoryId, subcategoryId);
-// createSectionAndSaveBulk(date, "number", "Numbers imported from file", number_indicators, stakeholder, topicId, categoryId, subcategoryId);
-
- return stakeholderController.setFullEntities(stakeholder);
- }
-
- private void createSectionsAndSaveBulk(Date date, List> old_sections,
- Stakeholder stakeholder, String topicId, String categoryId, String subcategoryId) throws UnsupportedEncodingException {
- for(Section section : old_sections) {
- if(section == null) {
- continue;
- }
-
- Section chart_section = null;
- Section number_section = null;
-
- List chart_indicators = null;
- List number_indicators = null;
-
- if(section.getType().equals("chart")) {
- chart_section = createSection(chart_section, "chart", section.getTitle(), date, stakeholder, topicId, categoryId, subcategoryId);
- chart_indicators = chart_section.getIndicators();
- } else if(section.getType().equals("number")) {
- number_section = createSection(number_section, "number", section.getTitle(), date, stakeholder, topicId, categoryId, subcategoryId);
- number_indicators = number_section.getIndicators();
- }
-
- List indicators = section.getIndicators();
- for (Indicator indicator : indicators) {
- if(indicator == null) {
- continue;
- }
-
- if (indicator.getType().equals("chart")) {
- saveIndicatorAndAddInSection(indicator, date, stakeholder, subcategoryId, chart_section, chart_indicators);
-
- } else if (indicator.getType().equals("number")) {
- saveIndicatorAndAddInSection(indicator, date, stakeholder, subcategoryId, number_section, number_indicators);
- }
- }
-
- if (chart_section != null) {
- sectionDAO.save(chart_section);
- }
- if (number_section != null) {
- sectionDAO.save(number_section);
- }
- }
- }
-
- private Section createSection(Section section, String type, String title, Date date,
- Stakeholder stakeholder, String topicId, String categoryId, String subcategoryId) {
- section = new Section<>();
- section.setType(type);
- section.setTitle(title);
- section.setStakeholderAlias(stakeholder.getAlias());
- section.setUpdateDate(date);
- section.setCreationDate(date);
- section.setIndicators(new ArrayList<>());
- section = sectionController.saveSection(stakeholder.getId(), topicId, categoryId, subcategoryId, "-1", section);
-
- return section;
- }
-
-// private void saveIndicatorAndAddInSection(Indicator indicator, Date date, Stakeholder stakeholder, Section section, List indicators) throws UnsupportedEncodingException {
-// saveIndicatorAndAddInSection(indicator, date, stakeholder, section, indicators);
-// }
-
- private void saveIndicatorAndAddInSection(Indicator indicator, Date date, Stakeholder stakeholder, String subcategoryId, Section section, List indicators) throws UnsupportedEncodingException {
- // indicator does not exist in DB
- indicator.setCreationDate(date);
- indicator.setUpdateDate(date);
-
- if (stakeholder.getDefaultId() == null) { // this indicator belongs in default profile and it is new
- indicatorDAO.save(indicator);
- onSaveDefaultIndicator(indicator, section, subcategoryId);
- } else { // this indicator belongs in a stakeholder's profile and it is new
- indicatorDAO.save(indicator);
- }
-
- indicators.add(indicator.getId());
- log.debug("Indicator saved!");
+ log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
+ Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, topicId);
+ 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);
}
@PreAuthorize("isAuthenticated()")
@@ -153,410 +62,15 @@ public class IndicatorController {
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@PathVariable("sectionId") String sectionId,
- @RequestBody Indicator indicator) throws UnsupportedEncodingException {
+ @RequestBody Indicator indicator) {
log.debug("save indicator");
- log.debug("Name: "+indicator.getName() + " - Id: "+indicator.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
-
- Section section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
-
- Date date = new Date();
- indicator.setUpdateDate(date);
-
- Indicator oldIndicator = null;
- if(indicator.getId() != null) {
- oldIndicator = indicatorDAO.findById(indicator.getId());
- if(oldIndicator == null) {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("save indicator: Indicator with id: " + indicator.getId() + " not found");
- }
- } else { // indicator does not exist in DB
- indicator.setCreationDate(date);
- }
-
- String indicatorId = indicator.getId();
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- // this indicator belongs in default profile and it is new or it is updated
- if(stakeholder.getDefaultId() == null) {
- if(indicatorId == null) {
- indicatorDAO.save(indicator);
- onSaveDefaultIndicator(indicator, section, subcategoryId);
- }
- else {
- onUpdateDefaultIndicator(indicator, stakeholder, oldIndicator);
- indicatorDAO.save(indicator);
- }
- } else {
- indicatorDAO.save(indicator);
- }
-
- List indicators = section.getIndicators();
-
- int index = indicators.indexOf(indicator.getId());
- if (index == -1) {
- indicators.add(indicator.getId());
- sectionDAO.save(section);
- log.debug("Indicator saved!");
- }
-
- return indicator;
- }
-
- public void onSaveDefaultIndicator(Indicator indicator, Section defaultSection, String defaultSubcategoryId) throws UnsupportedEncodingException {
- log.debug("On save default indicator");
-
- // new indicator in default profile - add it on profiles of the same type
- List subCategories = subCategoryDAO.findByDefaultId(defaultSubcategoryId);
- for (SubCategory subCategory : subCategories) {
-
- List sections = null;
- if(defaultSection.getType().equals("chart")) {
- sections = subCategory.getCharts();
- } else {
- sections = subCategory.getNumbers();
- }
-
- for (String sectionId : sections) {
- Section section = sectionDAO.findById(sectionId);
- if(section.getDefaultId() != null && section.getDefaultId().equals(defaultSection.getId())) {
- Indicator indicatorNew = new Indicator();
- indicatorNew.copyFromDefault(indicator, subCategory.getVisibility());
- for (IndicatorPath indicatorPath : indicatorNew.getIndicatorPaths()) {
- Stakeholder stakeholder = stakeholderDAO.findByAlias(section.getStakeholderAlias());
- parameterMapping(indicatorPath, stakeholder);
- }
-
- indicatorDAO.save(indicatorNew);
-
- List indicators = section.getIndicators();
- indicators.add(indicatorNew.getId());
-
- sectionDAO.save(section);
- }
- }
- }
- }
-
- public void onUpdateDefaultIndicator(Indicator indicator, Stakeholder stakeholder, Indicator oldIndicator) throws UnsupportedEncodingException {
- log.debug("On update default indicator");
-
- // indicator already exists - check if changed and update all indicators based on it
-
- boolean changed;
- List indicators = indicatorDAO.findByDefaultId(indicator.getId());
-
- for(Indicator indicatorBasedOnDefault : indicators) {
- changed = false;
-
-// if(indicator.getName() != null && !indicator.getName().equals(indicatorBasedOnDefault.getName())
-// && (oldIndicator.getName() == null || oldIndicator.getName().equals(indicatorBasedOnDefault.getName()))) {
- if((
- (indicator.getName() == null && oldIndicator.getName() != null)
- ||
- (indicator.getName() != null && !indicator.getName().equals(indicatorBasedOnDefault.getName()))
- ) && (
- (oldIndicator.getName() == null && indicatorBasedOnDefault.getName() == null)
- ||
- (oldIndicator.getName() != null && oldIndicator.getName().equals(indicatorBasedOnDefault.getName()))
- )) {
- indicatorBasedOnDefault.setName(indicator.getName());
- changed = true;
- }
-
- if(indicator.getDescription() != null && !indicator.getDescription().equals(indicatorBasedOnDefault.getDescription())
- || indicator.getDescription() == null && indicatorBasedOnDefault.getDescription() != null) {
-
- indicatorBasedOnDefault.setDescription(indicator.getDescription());
- changed = true;
- }
-
-// if(indicator.getAdditionalDescription() != null && !indicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription())
-// && (oldIndicator.getAdditionalDescription() == null || oldIndicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription()))) {
- if((
- (indicator.getAdditionalDescription() == null && oldIndicator.getAdditionalDescription() != null)
- ||
- (indicator.getAdditionalDescription() != null && !indicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription()))
- ) && (
- (oldIndicator.getAdditionalDescription() == null && indicatorBasedOnDefault.getAdditionalDescription() == null)
- ||
- (oldIndicator.getAdditionalDescription() != null && oldIndicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription()))
- )) {
- indicatorBasedOnDefault.setAdditionalDescription(indicator.getAdditionalDescription());
- changed = true;
- }
-
- int i = 0;
- List indicatorPaths = indicatorBasedOnDefault.getIndicatorPaths();
- if(indicatorPaths == null && indicator.getIndicatorPaths() != null) {
- indicatorPaths = new ArrayList<>();
- }
-
- for (IndicatorPath indicatorPath : indicator.getIndicatorPaths()) {
- IndicatorPath indicatorPathBasedOnDefault = null;
- if(i < indicatorPaths.size()) {
- indicatorPathBasedOnDefault = indicatorPaths.get(i);
- }
-
- if(indicatorPathBasedOnDefault == null) {
- // Add new indicator path in existing indicators
- IndicatorPath indicatorPathNew = new IndicatorPath(indicatorPath);
- parameterMapping(indicatorPathNew, stakeholder);
- indicatorPaths.add(indicatorPathNew);
- changed = true;
- } else {
- IndicatorPath oldIndicatorPath = oldIndicator.getIndicatorPaths().get(i);
-
- // Check if there are changes in indicator path and update existing indicators if needed
- log.debug("update indicator path: "+i + " (indicator id: "+indicatorBasedOnDefault.getId()+")");
-
-// if(indicatorPath.getType() != null
-// && !indicatorPath.getType().equals(indicatorPathBasedOnDefault.getType())
-// && (oldIndicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))) {
- if((
- (indicatorPath.getType() == null && oldIndicatorPath.getType() != null)
- ||
- (indicatorPath.getType() != null && !indicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))
- ) && (
- (oldIndicatorPath.getType() == null && indicatorPathBasedOnDefault.getType() == null)
- ||
- (oldIndicatorPath.getType() != null && oldIndicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))
- )) {
- indicatorPathBasedOnDefault.setType(indicatorPath.getType());
- changed = true; // parameter "type" needs to be changed as well
- }
- log.debug("After type check: "+changed);
-
- if((
- (indicatorPath.getFormat() == null && oldIndicatorPath.getFormat() != null)
- ||
- (indicatorPath.getFormat() != null && !indicatorPath.getFormat().equals(indicatorPathBasedOnDefault.getFormat()))
- ) && (
- (oldIndicatorPath.getFormat() == null && indicatorPathBasedOnDefault.getFormat() == null)
- ||
- (oldIndicatorPath.getFormat() != null && oldIndicatorPath.getFormat().equals(indicatorPathBasedOnDefault.getFormat()))
- )) {
- indicatorPathBasedOnDefault.setFormat(indicatorPath.getFormat());
- changed = true;
- }
- log.debug("After type check: "+changed);
-
-// if(indicatorPath.getSource() != null
-// && !indicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource())
-// && (oldIndicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))) {
- if((
- (indicatorPath.getSource() == null && oldIndicatorPath.getSource() != null)
- ||
- (indicatorPath.getSource() != null && !indicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))
- ) && (
- (oldIndicatorPath.getSource() == null && indicatorPathBasedOnDefault.getSource() == null)
- ||
- (oldIndicatorPath.getSource() != null && oldIndicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))
- )) {
- indicatorPathBasedOnDefault.setSource(indicatorPath.getSource());
- changed = true;
- }
- log.debug("After source check: "+changed);
-
-// if(indicatorPath.getUrl() != null
-// && !indicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl())
-// && (oldIndicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))) {
- if((
- (indicatorPath.getUrl() == null && oldIndicatorPath.getUrl() != null)
- ||
- (indicatorPath.getUrl() != null && !indicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))
- ) && (
- (oldIndicatorPath.getUrl() == null && indicatorPathBasedOnDefault.getUrl() == null)
- ||
- (oldIndicatorPath.getUrl() != null && oldIndicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))
- )) {
- indicatorPathBasedOnDefault.setUrl(indicatorPath.getUrl());
- changed = true;
- }
- log.debug("After url check: "+changed);
-
- if((
- (indicatorPath.getChartObject() == null && oldIndicatorPath.getChartObject() != null)
- ||
- (indicatorPath.getChartObject() != null && !indicatorPath.getChartObject().equals(indicatorPathBasedOnDefault.getChartObject()))
- ) && (
- (oldIndicatorPath.getChartObject() == null && indicatorPathBasedOnDefault.getChartObject() == null)
- ||
- (oldIndicatorPath.getChartObject() != null && oldIndicatorPath.getChartObject().equals(indicatorPathBasedOnDefault.getChartObject()))
- )) {
-
- indicatorPathBasedOnDefault.setChartObject(indicatorPath.getChartObject());
- changed = true;
- }
- log.debug("After chartObject check: "+changed);
-
- if(indicatorPath.getParameters() != null) {
- if (indicatorPathBasedOnDefault.getParameters() == null) {
- indicatorPathBasedOnDefault.setParameters(new HashMap<>());
- }
- //if (indicatorPath.getParameters().size() != indicatorPathBasedOnDefault.getParameters().size()) {
- //log.debug("Different number of parameters");
- for (Map.Entry parameter : indicatorPath.getParameters().entrySet()) {
- log.debug("\nindicatorPath: parameter.getKey(): "+parameter.getKey()+" - value: "+parameter.getValue()
- +"\nindicatorPathBasedOnDefault:parameters:key: "+ indicatorPathBasedOnDefault.getParameters().get(parameter.getKey())
- +"\noldIndicatorPath:parameters:key: "+ (oldIndicatorPath.getParameters() == null ? "null" : oldIndicatorPath.getParameters().get(parameter.getKey())));
- if (!indicatorPathBasedOnDefault.getParameters().containsKey(parameter.getKey())
- || (oldIndicatorPath.getParameters() == null || oldIndicatorPath.getParameters().get(parameter.getKey()) == null
- || (oldIndicatorPath.getParameters().get(parameter.getKey()).equals(indicatorPathBasedOnDefault.getParameters().get(parameter.getKey()))
- && !parameter.getValue().equals(indicatorPathBasedOnDefault.getParameters().get(parameter.getKey()))))
- ) {
- indicatorPathBasedOnDefault.getParameters().put(parameter.getKey(), parameter.getValue());
- changed = true;
- }
-// else if(parameter.getKey().equals("type")) {
-// indicatorPathBasedOnDefault.getParameters().put(parameter.getKey(), parameter.getValue());
-// changed = true;
-// }
- }
-
- // When deleting indicator path parameters in a default profile, delete them also from all children profiles
- if(oldIndicatorPath.getParameters() != null && indicatorPath.getParameters().size() < oldIndicatorPath.getParameters().size()) {
- for (Map.Entry parameter : oldIndicatorPath.getParameters().entrySet()) {
- if(!indicatorPath.getParameters().containsKey(parameter.getKey())) {
- indicatorPathBasedOnDefault.getParameters().remove(parameter.getKey());
- }
- }
- }
- parameterMapping(indicatorPathBasedOnDefault, stakeholder);
- //}
- }
- log.debug("After parameters check: " + changed);
-
- if(indicatorPath.getJsonPath() != null) {
- boolean jsonPathChanged = false;
- boolean breaked = false;
-
- int oldJsonPathSize = 0;
- if(oldIndicatorPath.getJsonPath() != null) {
- oldJsonPathSize = oldIndicatorPath.getJsonPath().size();
- }
- int basedOnDefaultJsonPathSize = 0;
- if(indicatorPathBasedOnDefault.getJsonPath() != null) {
- basedOnDefaultJsonPathSize = indicatorPathBasedOnDefault.getJsonPath().size();
- }
- log.debug("old: "+oldJsonPathSize+" - based on default: "+basedOnDefaultJsonPathSize+" - new: "+indicatorPath.getJsonPath().size());
- if(oldJsonPathSize == basedOnDefaultJsonPathSize) {
- if(indicatorPathBasedOnDefault.getJsonPath() == null && indicatorPath.getJsonPath().size() > 0) {
- indicatorPathBasedOnDefault.setJsonPath(new ArrayList<>());
- }
-
- int basedOnDefaultIndex = 0;
- int oldIndex = 0;
-
- Iterator jsonStringBasedOnDefaultIterator = indicatorPathBasedOnDefault.getJsonPath().iterator();
- while (jsonStringBasedOnDefaultIterator.hasNext()) {
- String jsonStringBasedOnDefault = jsonStringBasedOnDefaultIterator.next();
- if(oldIndicatorPath.getJsonPath().get(oldIndex).equals(jsonStringBasedOnDefault)) {
- if(basedOnDefaultIndex >= indicatorPath.getJsonPath().size()) { // string deleted
- jsonStringBasedOnDefaultIterator.remove();
- jsonPathChanged = true;
- } else { // check if string changed
- if(!indicatorPath.getJsonPath().get(basedOnDefaultIndex).equals(jsonStringBasedOnDefault)) {
- indicatorPathBasedOnDefault.getJsonPath().set(basedOnDefaultIndex, indicatorPath.getJsonPath().get(basedOnDefaultIndex));
- jsonPathChanged = true;
- }
- basedOnDefaultIndex++;
- }
- oldIndex++;
- } else {
- breaked = true;
- jsonPathChanged = false;
- log.debug("not the same: "+oldIndex);
- break;
- }
- }
-
- int index=0;
- if(!breaked && indicatorPath.getJsonPath().size() > indicatorPathBasedOnDefault.getJsonPath().size()) { // strings added
- jsonPathChanged = true;
- for(index=indicatorPathBasedOnDefault.getJsonPath().size(); index < indicatorPath.getJsonPath().size(); index++) {
- indicatorPathBasedOnDefault.getJsonPath().add(indicatorPath.getJsonPath().get(index));
- }
- }
-
- if(jsonPathChanged) {
- changed = true;
- }
- }
- // TODO when deleting indicator path json path strings... --> is this done? (line 327)
- }
- log.debug("After jsonPath check: " + changed);
- }
- i++;
- }
- // TODO when deleting indicator paths...
-
- if(!changed) {
-// break;
- continue;
- }
-
- indicatorBasedOnDefault.setUpdateDate(indicator.getUpdateDate());
- indicatorDAO.save(indicatorBasedOnDefault);
- }
- }
-
- public void parameterMapping(IndicatorPath indicatorPath, Stakeholder stakeholder) throws UnsupportedEncodingException {
- if (indicatorPath.getParameters() != null) {
- if (indicatorPath.getParameters().containsKey("index_name")) {
- indicatorPath.getParameters().put("index_name", stakeholder.getIndex_name());
- } else if (indicatorPath.getParameters().containsKey("index_shortName")) {
- if(stakeholder.getIndex_shortName() != null) {
- indicatorPath.getParameters().put("index_shortName", stakeholder.getIndex_shortName().toLowerCase());
- } else {
- indicatorPath.getParameters().remove("index_shortName");
- }
- } else if (indicatorPath.getParameters().containsKey("index_id")) {
- indicatorPath.getParameters().put("index_id", stakeholder.getIndex_id());
- }
- }
-
-// // url encoding for number indicators
-// String url = indicatorPath.getUrl();
-// String encoded_index_id = urlEncode(URLEncoder.encode(stakeholder.getIndex_id(), "UTF-8"));
-// url = url.replace("index_id", encoded_index_id);
-// String encoded_index_name = urlEncode(URLEncoder.encode(stakeholder.getIndex_name(), "UTF-8"));
-// url = url.replace("index_name", encoded_index_name);
-// String encoded_index_shortName = urlEncode(URLEncoder.encode(stakeholder.getIndex_shortName(), "UTF-8"));
-// url = url.replace("index_shortName", encoded_index_shortName);
-// indicatorPath.setUrl(url);
- }
-
- public String urlEncode(String encodedIndicatorPathField) {
- String indicatorPathField = "";
-
- for( int i=0; i section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- if(indicator.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(stakeholder.getType())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Delete indicator: You are not authorized to delete a default Indicator in stakeholder with id: "+stakeholderId);
- }
-
- List indicators = section.getIndicators();
-
- int index = indicators.indexOf(indicatorId);
- if (index != -1) {
-
- // this indicator belongs in default profile
- if(section.getDefaultId() == null && children != null) {
- onDeleteDefaultIndicator(indicatorId, sectionId, children);
- }
-
-
- indicators.remove(index);
- sectionDAO.save(section);
-
- indicatorDAO.delete(indicatorId);
- log.debug("Indicator deleted!");
- } else {
- // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
- throw new PathNotValidException("Delete indicator: Indicator with id: "+indicatorId+" not found in Sectiom: "+sectionId);
- }
- } else {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("Delete indicator: Indicator with id: "+indicatorId+" not found");
- }
+ log.debug("Id: " + indicatorId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId + " - Section: " + sectionId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, 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);
+ this.indicatorService.delete(stakeholder.getType(), indicator, true);
return true;
}
- public boolean onDeleteDefaultIndicator(String defaultIndicatorId, String defaultSectionId, String children) {
- if(children.equals("delete")) {
-// // 1st way
-// List sections = sectionDAO.findByDefaultId(defaultSectionId);
-//
-// for(Section section : sections) {
-// List indicators = section.getIndicators();
-//
-// Iterator indicatorsIterator = indicators.iterator();
-// while(indicatorsIterator.hasNext()) {
-// String indicatorId = indicatorsIterator.next();
-//
-// Indicator indicator = indicatorDAO.findById(indicatorId);
-// if (indicator.getDefaultId().equals(defaultIndicatorId)) {
-// indicatorsIterator.remove();
-// sectionDAO.save(section);
-//
-// indicatorDAO.delete(indicatorId);
-// log.debug("Indicator deleted!");
-//
-// break;
-// }
-// }
-// }
-
- // 2nd way
- List sections = sectionDAO.findByDefaultId(defaultSectionId);
- List indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
-
- for(Section section : sections) {
- Iterator indicatorsIterator = indicators.iterator();
- while(indicatorsIterator.hasNext()) {
- String indicatorId = indicatorsIterator.next().getId();
- if(section.getIndicators().contains(indicatorId)) {
- indicatorsIterator.remove();
-
- section.getIndicators().remove(indicatorId);
- sectionDAO.save(section);
-
- indicatorDAO.delete(indicatorId);
- log.debug("Indicator with id: "+indicatorId+" deleted!");
-
- break;
- }
- }
- }
-
-// // 3rd way - parentId
-// List indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
-// for(Indicator indicator : indicators) {
-// Section section = sectionDAO.findById(indicator.getParent());
-// List sectionIndicators = section.getIndicators();
-//
-// sectionIndicators.remove(indicator.getId());
-// sectionDAO.save(section);
-//
-// indicatorDAO.delete(indicator.getId());
-// log.debug("Indicator deleted!");
-// }
- } else if(children.equals("disconnect")) {
- List indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
- for(Indicator indicator : indicators) {
- indicator.setDefaultId(null);
- indicatorDAO.save(indicator);
- log.debug("DefaultId for Indicator with id: "+indicator.getId()+" empty!");
- }
- }
- return true;
- }
-
-// @RequestMapping(value = "/{stakeholderId}/charts/delete", method = RequestMethod.DELETE)
-// public boolean deleteAllChartIndicators(@PathVariable("stakeholderId") String stakeholderId) {
-// log.debug("delete all chart indicators of stakeholder");
-// log.debug("Stakeholder: "+stakeholderId);
-//
-// Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-// if(stakeholder != null) {
-//
-// for(String topicId : stakeholder.getTopics()) {
-// Topic topic = topicDAO.findById(topicId);
-// if(topic != null) {
-// for(String categoryId : topic.getCategories()) {
-// Category category = categoryDAO.findById(categoryId);
-// if(category != null) {
-// for(String subcategoryId : category.getSubCategories()) {
-// SubCategory subcategory = subCategoryDAO.findById(subcategoryId);
-// if(subcategory != null) {
-//
-// for(String sectionId : subcategory.getCharts()) {
-// Section section = sectionDAO.findById(sectionId);
-// if (section != null) {
-//
-// List indicators = section.getIndicators();
-// Iterator indicatorsIterator = section.getIndicators().iterator();
-//
-// while (indicatorsIterator.hasNext()) {
-// String indicatorId = indicatorsIterator.next();
-// Indicator indicator = indicatorDAO.findById(indicatorId);
-// if (indicator != null) {
-// int index = indicators.indexOf(indicatorId);
-// if (index != -1) {
-// indicatorsIterator.remove();
-// //indicators.remove(index);
-//
-// indicatorDAO.delete(indicatorId);
-// log.debug("Indicator deleted!");
-// } else {
-// // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
-// throw new PathNotValidException("Delete indicator: Indicator with id: " + indicatorId + " not found in Section: " + sectionId);
-// }
-// } else {
-// // EXCEPTION - Indicator not found
-// throw new EntityNotFoundException("Delete indicator: Indicator with id: " + indicatorId + " not found");
-// }
-// }
-// sectionDAO.save(section);
-// } else {
-// // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
-// throw new PathNotValidException("Delete indicator: Section with id: " + sectionId + " not found in SubCategory: " + subcategoryId);
-// }
-// }
-// } else {
-// // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
-// throw new PathNotValidException("Delete indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
-// }
-// }
-// } else {
-// // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
-// throw new PathNotValidException("Delete indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
-// }
-// }
-// } else {
-// // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
-// throw new PathNotValidException("Delete indicator: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
-// }
-// }
-// } else {
-// // EXCEPTION - Stakeholder not found
-// throw new EntityNotFoundException("Delete indicator: Stakeholder with id: "+stakeholderId+" not found");
-// }
-// return true;
-// }
@PreAuthorize("isAuthenticated()")
- @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{type}/reorder", method = RequestMethod.POST)
+ @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/reorder", method = RequestMethod.POST)
public List reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
@PathVariable("sectionId") String sectionId,
- @PathVariable("type") String type,
- @RequestBody ReorderEvent reorderEvent) {
- log.debug("reorder indicators of type: "+type);
- log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
-
- List indicators = reorderEvent.getIds();
- String actionType = reorderEvent.getAction();
- String targetId = reorderEvent.getTarget();
-
- Section section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, type);
-
- List oldIndicators = section.getIndicators();
- for (String indicatorId : oldIndicators) {
- if ((!actionType.equals("removed") || !targetId.equals(indicatorId)) && !indicators.contains(indicatorId)) {
- indicators.add(indicatorId);
- }
- }
- section.setIndicators(indicators);
-
- List indicatorsFull = new ArrayList<>();
- for(String indicatorId : indicators) {
- Indicator indicator = indicatorDAO.findById(indicatorId);
- if(indicator == null) {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("Reorder indicators: Indicator with id: " + indicatorId + " not found");
- }
- indicatorsFull.add(indicator);
- }
-
- sectionDAO.save(section);
- log.debug("Indicators reordered!");
-
- return indicatorsFull;
+ @RequestBody List indicators) {
+ log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId + " - Section: " + sectionId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, topicId);
+ 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();
}
-// @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/toggle-status", method = RequestMethod.POST)
-// public Boolean toggleIndicatorStatus(@PathVariable("stakeholderId") String stakeholderId,
-// @PathVariable("topicId") String topicId,
-// @PathVariable("categoryId") String categoryId,
-// @PathVariable("subcategoryId") String subcategoryId,
-// @PathVariable("sectionId") String sectionId,
-// @PathVariable("indicatorId") String indicatorId) {
-// log.debug("toggle indicator status (isActive)");
-// log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
-//
-// Indicator indicator = indicatorDAO.findById(indicatorId);
-// if (indicator == null) {
-// // EXCEPTION - Indicator not found
-// throw new EntityNotFoundException("Toggle indicator status: Indicator with id: "+indicatorId+" not found");
-// }
-// indicator.setIsActive(!indicator.getIsActive());
-//
-// this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
-//
-// return indicator.getIsActive();
-// }
-//
-// @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/toggle-access", method = RequestMethod.POST)
-// public Boolean toggleIndicatorAccess(@PathVariable("stakeholderId") String stakeholderId,
-// @PathVariable("topicId") String topicId,
-// @PathVariable("categoryId") String categoryId,
-// @PathVariable("subcategoryId") String subcategoryId,
-// @PathVariable("sectionId") String sectionId,
-// @PathVariable("indicatorId") String indicatorId) {
-// log.debug("toggle indicator access (isPublic)");
-// log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
-//
-// Indicator indicator = indicatorDAO.findById(indicatorId);
-// if (indicator == null) {
-// // EXCEPTION - Indicator not found
-// throw new EntityNotFoundException("Toggle indicator access: Indicator with id: "+indicatorId+" not found");
-// }
-// indicator.setIsPublic(!indicator.getIsPublic());
-//
-// this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
-//
-// return indicator.getIsPublic();
-// }
-
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/change-visibility", method = RequestMethod.POST)
public Indicator changeIndicatorVisibility(@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("visibility") Visibility visibility) {
- log.debug("change indicator visibility: "+visibility);
- log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
-
- Indicator indicator = indicatorDAO.findById(indicatorId);
- if (indicator == null) {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("Change indicator visibility: Indicator with id: " + indicatorId + " not found");
- }
-
- Section section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
- List indicators = section.getIndicators();
-
- if(indicators.contains(indicatorId)) {
- return changeVisibilityTree(indicatorId, indicator, visibility);
- } else {
- // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subCategory.getAlias(); -> Section: section.getTitle();
- throw new PathNotValidException("Toggle indicators: Indicator with id: "+indicatorId+" not found in Section: "+sectionId);
- }
- }
-
- public Indicator changeVisibilityTree(String indicatorId, Indicator indicator, Visibility visibility) {
- if(indicator == null) {
- indicator = indicatorDAO.findById(indicatorId);
- if (indicator == null) {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("Change indicator visibility: Indicator with id: " + indicatorId + " not found");
- }
- }
-
- indicator.setVisibility(visibility);
- indicatorDAO.save(indicator);
- log.debug("Indicator toggled!");
-
- return indicator;
- }
-
- private Section checkForExceptions(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, String indicatorType) {
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- if(stakeholder == null) {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
- }
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("CheckForExceptions Indicator: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- Topic topic = topicDAO.findById(topicId);
- if(topic == null) {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Save indicator: Topic with id: "+topicId+" not found");
- }
-
- if(!stakeholder.getTopics().contains(topicId)) {
- // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
- throw new PathNotValidException("Save indicator: Topic with id: " + topicId + " not found in Stakeholder: " + stakeholderId);
- }
-
- Category category = categoryDAO.findById(categoryId);
- if(category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Save indicator: Category with id: "+categoryId+" not found");
- }
-
- if(!topic.getCategories().contains(categoryId)) {
- // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
- throw new PathNotValidException("Save indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
- }
-
- SubCategory subcategory = subCategoryDAO.findById(subcategoryId);
- if(subcategory == null) {
- // EXCEPTION - SubCategory not found
- throw new EntityNotFoundException("Save indicator: SubCategory with id: "+subcategoryId+" not found");
- }
-
- if (!category.getSubCategories().contains(subcategoryId)) {
- // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
- throw new PathNotValidException("Save indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
- }
-
- Section section = sectionDAO.findById(sectionId);
- if(section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Save indicator: Section with id: "+sectionId+" not found");
- }
-
- if(indicatorType.equals("chart")) {
- if (!subcategory.getCharts().contains(sectionId)) {
- // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
- throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
- }
- } else if(indicatorType.equals("number")) {
- if (!subcategory.getNumbers().contains(sectionId)) {
- // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
- throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
- }
- }
-
- return section;
- }
-
- public void deleteTree(Section section) {
- List indicators = section.getIndicators();
- for(String indicatorId : indicators) {
- indicatorDAO.delete(indicatorId);
- }
- }
-
- public void disConnectTree(Section section) {
- List indicators = section.getIndicators();
- for(String indicatorId : indicators) {
- Indicator indicator = indicatorDAO.findById(indicatorId);
- indicator.setDefaultId(null);
- indicatorDAO.save(indicator);
- }
+ @PathVariable("topicId") String topicId,
+ @PathVariable("categoryId") String categoryId,
+ @PathVariable("subcategoryId") String subcategoryId,
+ @PathVariable("sectionId") String sectionId,
+ @PathVariable("indicatorId") String indicatorId,
+ @RequestParam("visibility") Visibility visibility) {
+ log.debug("change indicator visibility: " + visibility);
+ log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId + " - Section: " + sectionId + " - Indicator: " + indicatorId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, 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);
}
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorController.java
index fa68f01..1c959e3 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorController.java
@@ -16,9 +16,6 @@ import java.util.*;
@CrossOrigin(origins = "*")
public class MonitorController {
private final Logger log = LogManager.getLogger(this.getClass());
-//
-// @Autowired
-// private LayoutService layoutService;
@Autowired
private PortalService portalService;
@@ -36,11 +33,6 @@ public class MonitorController {
if (!old_pid.equals(new_pid)) {
pageService.updatePid(old_pid, new_pid, portal.getType());
}
-// String old_pid = portalResponse.getPid();
-// String new_pid = portal.getPid();
-// if(!old_pid.equals(new_pid)) {
-// layoutService.updatePid(old_pid, new_pid);
-// }
return portalResponse;
}
@@ -53,23 +45,8 @@ public class MonitorController {
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public Boolean deletePortals(@RequestBody List portals) {
- for (String id: portals) {
- String pid = portalService.deletePortal(id);
-// layoutService.deleteByPid(pid);
- }
-
+ portals.forEach(id -> portalService.deletePortal(id));
return true;
}
-
-// @RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET)
-// public Layout getLayoutForCommunity(@PathVariable(value = "pid") String pid) {
-// return layoutService.findByPid(pid);
-// }
-//
-// @RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST)
-// public Layout updateLayoutForCommunity(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) {
-// return layoutService.save(layout);
-// }
-
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorLibraryCheckDeployController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorLibraryCheckDeployController.java
index 6b84e53..3fd7065 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorLibraryCheckDeployController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorLibraryCheckDeployController.java
@@ -1,42 +1,27 @@
package eu.dnetlib.uoamonitorservice.controllers;
-import com.mongodb.BasicDBObject;
-import com.mongodb.CommandResult;
-import com.mongodb.DBObject;
-import eu.dnetlib.uoamonitorservice.application.UoaMonitorServiceApplication;
-import eu.dnetlib.uoamonitorservice.configuration.GlobalVars;
-import eu.dnetlib.uoamonitorservice.configuration.mongo.MongoConnection;
-import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
+import eu.dnetlib.uoamonitorservice.service.MonitorDeployService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
-import org.springframework.context.annotation.Conditional;
-import org.springframework.data.mongodb.core.MongoTemplate;
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;
-import java.util.HashMap;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/monitor-library")
-//@ConditionalOnBean(UoaMonitorServiceApplication.class)
public class MonitorLibraryCheckDeployController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private MongoConnection mongoConnection;
+ private final MonitorDeployService service;
- @Autowired
- private MongoConfig mongoConfig;
-
- @Autowired
- private GlobalVars globalVars;
+ public MonitorLibraryCheckDeployController(MonitorDeployService service) {
+ this.service = service;
+ }
@RequestMapping(value = {"", "/health_check"}, method = RequestMethod.GET)
public String hello() {
@@ -47,34 +32,6 @@ public class MonitorLibraryCheckDeployController {
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/health_check/advanced", method = RequestMethod.GET)
public Map checkEverything() {
- Map response = new HashMap<>();
-
- MongoTemplate mt = mongoConnection.getMongoTemplate();
- DBObject ping = new BasicDBObject("ping", "1");
- try {
- CommandResult answer = mt.getDb().command(ping);
- response.put("Mongo try: error", answer.getErrorMessage());
- } catch (Exception e) {
- response.put("Mongo catch: error", e.getMessage());
- }
-
- 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]");
-// response.put("Define also", "monitorservice.mongodb.username, monitorservice.mongodb.password");
-
- if(globalVars.date != null) {
- response.put("Date of deploy", globalVars.date.toString());
- }
- if(globalVars.getBuildDate() != null) {
- response.put("Date of build", globalVars.getBuildDate());
- }
- if(globalVars.getVersion() != null) {
- response.put("Version", globalVars.getVersion());
- }
-
- return response;
+ return this.service.checkEverything();
}
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorServiceCheckDeployController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorServiceCheckDeployController.java
index fea6107..ae7fee7 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorServiceCheckDeployController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/MonitorServiceCheckDeployController.java
@@ -6,6 +6,7 @@ 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 eu.dnetlib.uoamonitorservice.service.MonitorDeployService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@@ -24,14 +25,11 @@ import java.util.Map;
public class MonitorServiceCheckDeployController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private MongoConnection mongoConnection;
+ private final MonitorDeployService service;
- @Autowired
- private MongoConfig mongoConfig;
-
- @Autowired
- private GlobalVars globalVars;
+ public MonitorServiceCheckDeployController(MonitorDeployService service) {
+ this.service = service;
+ }
@RequestMapping(value = {"", "/health_check"}, method = RequestMethod.GET)
public String hello() {
@@ -42,34 +40,6 @@ public class MonitorServiceCheckDeployController {
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/health_check/advanced", method = RequestMethod.GET)
public Map checkEverything() {
- Map response = new HashMap<>();
-
- MongoTemplate mt = mongoConnection.getMongoTemplate();
- DBObject ping = new BasicDBObject("ping", "1");
- try {
- CommandResult answer = mt.getDb().command(ping);
- response.put("Mongo try: error", answer.getErrorMessage());
- } catch (Exception e) {
- response.put("Mongo catch: error", e.getMessage());
- }
-
- 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]");
-// response.put("Define also", "monitorservice.mongodb.username, monitorservice.mongodb.password");
-
- if(globalVars.date != null) {
- response.put("Date of deploy", globalVars.date.toString());
- }
- if(globalVars.getBuildDate() != null) {
- response.put("Date of build", globalVars.getBuildDate());
- }
- if(globalVars.getVersion() != null) {
- response.put("Version", globalVars.getVersion());
- }
-
- return response;
+ return this.service.checkEverything();
}
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SectionController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SectionController.java
index a7506ee..46115dc 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SectionController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SectionController.java
@@ -1,20 +1,17 @@
package eu.dnetlib.uoamonitorservice.controllers;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
-import eu.dnetlib.uoamonitorservice.dao.*;
+import eu.dnetlib.uoamonitorservice.dto.MoveIndicator;
+import eu.dnetlib.uoamonitorservice.dto.SectionFull;
+import eu.dnetlib.uoamonitorservice.dto.SubCategoryFull;
import eu.dnetlib.uoamonitorservice.entities.*;
-import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
+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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
import java.util.List;
@RestController
@@ -22,203 +19,37 @@ import java.util.List;
public class SectionController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private RolesUtils rolesUtils;
+ private final StakeholderService stakeholderService;
+ private final TopicService topicService;
+ private final CategoryService categoryService;
+ private final SubCategoryService subCategoryService;
+ private final SectionService sectionService;
@Autowired
- private StakeholderDAO stakeholderDAO;
-
- @Autowired
- private TopicDAO topicDAO;
-
- @Autowired
- private CategoryDAO categoryDAO;
-
- @Autowired
- private SubCategoryDAO subCategoryDAO;
-
- @Autowired
- private SectionDAO sectionDAO;
-
- @Autowired
- private IndicatorDAO indicatorDAO;
-
- @Autowired
- private IndicatorController indicatorController;
-
- public Section buildSection(Section sectionFull) {
- Section section = new Section<>(sectionFull);
-
- List indicators = new ArrayList<>();
- List indicatorsFull = new ArrayList<>();
- for(Indicator chart : sectionFull.getIndicators()) {
- Indicator chartSaved = indicatorDAO.save(chart);
- chart.setId(chartSaved.getId());
- indicatorsFull.add(chart);
- indicators.add(chartSaved.getId());
- }
- sectionFull.setIndicators(indicatorsFull);
- section.setIndicators(indicators);
-
- Date date = new Date();
- section.setCreationDate(date);
- section.setUpdateDate(date);
-
- sectionFull.setCreationDate(date);
- sectionFull.setUpdateDate(date);
-
- sectionDAO.save(section);
-
- sectionFull.setId(section.getId());
- return sectionFull;
+ public SectionController(StakeholderService stakeholderService, TopicService topicService, CategoryService categoryService,
+ SubCategoryService subCategoryService, SectionService sectionService) {
+ this.stakeholderService = stakeholderService;
+ this.topicService = topicService;
+ this.categoryService = categoryService;
+ this.subCategoryService = subCategoryService;
+ this.sectionService = sectionService;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/save/{index}", method = RequestMethod.POST)
- public Section saveSection(@PathVariable("stakeholderId") String stakeholderId,
- @PathVariable("topicId") String topicId,
- @PathVariable("categoryId") String categoryId,
- @PathVariable("subcategoryId") String subcategoryId,
- @PathVariable("index") String index,
- @RequestBody Section sectionFull) {
+ 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) {
log.debug("save section");
- log.debug("Name: "+sectionFull.getTitle() + " - Id: "+sectionFull.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
-
- SubCategory subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
-
- Section section = new Section<>(sectionFull);
-
- Date date = new Date();
- section.setUpdateDate(date);
- sectionFull.setUpdateDate(date);
-
- List indicators = new ArrayList<>();
-
- Section oldSection = null;
- if(sectionFull.getId() != null) {
- oldSection = sectionDAO.findById(sectionFull.getId());
- if(oldSection == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("save section: Section with id: " + sectionFull.getId() + " not found");
- }
-
- for(String indicatorId : oldSection.getIndicators()) {
- Indicator indicator = indicatorDAO.findById(indicatorId);
- if (indicator == null) {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("Save section: Indicator with id: "+indicatorId+" not found (indicator exists in section: "+section.getId()+")");
- }
- indicators.add(indicator.getId());
- }
- } else { // section does not exist in DB
- section.setCreationDate(date);
- sectionFull.setCreationDate(date);
-
- for(Indicator indicator : sectionFull.getIndicators()) {
- indicators.add(indicator.getId());
- }
- }
-
- String sectionId = sectionFull.getId();
-
- section.setIndicators(indicators);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- // this section belongs in default profile and it is new or it is updated
- if(stakeholder.getDefaultId() == null) {
- if(sectionId == null) {
- sectionDAO.save(section);
- onSaveDefaultSection(section, topicId, categoryId, subcategoryId, stakeholder);
- }
- else {
- onUpdateDefaultSection(section, stakeholder, oldSection);
- sectionDAO.save(section);
- }
- } else {
- sectionDAO.save(section);
- }
-
- List sections = null;
- if(sectionFull.getType().equals("chart")) {
- sections = subCategory.getCharts();
- } else if(sectionFull.getType().equals("number")) {
- sections = subCategory.getNumbers();
- }
-
- int existing_index = sections.indexOf(section.getId());
- if (existing_index == -1) {
- if(Integer.parseInt(index) != -1) {
- sections.add(Integer.parseInt(index), section.getId());
- } else {
- sections.add(section.getId());
- }
- subCategoryDAO.save(subCategory);
- log.debug("Section saved!");
-
- sectionFull.setId(section.getId());
- }
-
- return sectionFull;
- }
-
- public void onSaveDefaultSection(Section section,
- String defaultTopicId, String defaultCategoryId,
- String defaultSubcategoryId, Stakeholder defaultStakeholder) {
- log.debug("On save default section");
-
-
- // new section in default profile - add it on profiles of the same type
- List subCategories = subCategoryDAO.findByDefaultId(defaultSubcategoryId);
-
- for (SubCategory subCategory : subCategories) {
- Category parentCategory = categoryDAO.findBySubCategoriesContaining(subCategory.getId());
- Topic parentTopic = topicDAO.findByCategoriesContaining(parentCategory.getId());
- Stakeholder parentStakeholder = stakeholderDAO.findByTopicsContaining(parentTopic.getId());
-
- Section sectionNew = new Section();
- sectionNew.copyFromDefault(section);
-
- sectionNew.setStakeholderAlias(parentStakeholder.getAlias());
-
- sectionDAO.save(sectionNew);
-
- List sections = null;
- if (section.getType().equals("chart")) {
- sections = subCategory.getCharts();
- } else if (section.getType().equals("number")) {
- sections = subCategory.getNumbers();
- }
- sections.add(sectionNew.getId());
-
- subCategoryDAO.save(subCategory);
- }
- }
-
- public void onUpdateDefaultSection(Section section, Stakeholder stakeholder, Section oldSection) {
- log.debug("On update default section");
-
- // section already exists - check if changed and update all sections based on it
-
- boolean changed = false;
- List sections = sectionDAO.findByDefaultId(section.getId());
-
- for(Section sectionBasedOnDefault : sections) {
- if(section.getTitle() != null && !section.getTitle().equals(sectionBasedOnDefault.getTitle())
- && (oldSection.getTitle() == null || oldSection.getTitle().equals(sectionBasedOnDefault.getTitle()))) {
-
- sectionBasedOnDefault.setTitle(section.getTitle());
- changed = true;
- }
-
- if(!changed) {
-// break;
- continue;
- }
-
-// sectionBasedOnDefault.setTitle(section.getTitle());
- sectionBasedOnDefault.setUpdateDate(section.getUpdateDate());
- sectionDAO.save(sectionBasedOnDefault);
- }
+ log.debug("Name: " + sectionFull.getTitle() + " - Id: " + sectionFull.getId() + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
+ Stakeholder stakeholder = this.stakeholderService.findByPath(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, topicId);
+ Category category = this.categoryService.findByPath(topic, categoryId);
+ SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
+ return this.sectionService.save(stakeholder, subCategory, new Section(sectionFull), Integer.parseInt(index));
}
@PreAuthorize("isAuthenticated()")
@@ -230,331 +61,29 @@ public class SectionController {
@PathVariable("sectionId") String sectionId,
@RequestParam(required = false) String children) {
log.debug("delete section");
- log.debug("Id: "+sectionId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
-
- Section section = sectionDAO.findById(sectionId);
- if(section != null) {
- SubCategory subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- if(section.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(stakeholder.getType())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Delete section: You are not authorized to delete a default Section in stakeholder with id: "+stakeholderId);
- }
-
- String type = "";
- List sections = null;
- if (section.getType().equals("chart")) {
- sections = subCategory.getCharts();
- type = "chart";
- } else if (section.getType().equals("number")) {
- sections = subCategory.getNumbers();
- type = "number";
- }
-
- int index = sections.indexOf(sectionId);
- if (index != -1) {
- // this section belongs in default profile
- if(subCategory.getDefaultId() == null && children != null) {
- onDeleteDefaultSection(sectionId, subcategoryId, children, type);
- }
-
- indicatorController.deleteTree(section);
-
- sections.remove(index);
- subCategoryDAO.save(subCategory);
-
- sectionDAO.delete(sectionId);
- log.debug("Section deleted!");
- } else {
- // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
- throw new PathNotValidException("Delete section: Section with id: "+sectionId+" not found in SubCategory: "+subcategoryId);
- }
- } else {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Delete section: Section with id: "+sectionId+" not found");
- }
- return true;
- }
-
- public boolean onDeleteDefaultSection(String defaultSectionId, String defaultSubCategoryId, String children, String type) {
- if(children.equals("delete")) {
- List subCategories = subCategoryDAO.findByDefaultId(defaultSubCategoryId);
- List sections = sectionDAO.findByDefaultId(defaultSectionId);
-
- for(SubCategory subCategory : subCategories) {
- Iterator sectionsIterator = sections.iterator();
- while(sectionsIterator.hasNext()) {
- Section section = sectionsIterator.next();
-
- String sectionId = section.getId();
- List subCategorySections = null;
- if(type.equals("chart")) {
- subCategorySections = subCategory.getCharts();
- } else if(type.equals("number")) {
- subCategorySections = subCategory.getNumbers();
- }
- if(subCategorySections != null && subCategorySections.contains(sectionId)) {
- sectionsIterator.remove();
-
- subCategorySections.remove(sectionId);
- subCategoryDAO.save(subCategory);
-
- indicatorController.deleteTree(section);
-
- sectionDAO.delete(sectionId);
- log.debug("Section with id: "+sectionId+" deleted!");
-
- break;
- }
- }
- }
- } else if(children.equals("disconnect")) {
- List sections = sectionDAO.findByDefaultId(defaultSectionId);
- for(Section section : sections) {
- indicatorController.disConnectTree(section);
-
- section.setDefaultId(null);
- sectionDAO.save(section);
-
- log.debug("DefaultId for Section with id: "+section.getId()+" empty!");
- }
- }
+ log.debug("Id: " + sectionId + " - Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ Topic topic = this.topicService.findByPath(stakeholder, topicId);
+ Category category = this.categoryService.findByPath(topic, categoryId);
+ SubCategory subCategory = this.subCategoryService.findByPath(category, subcategoryId);
+ Section section = this.sectionService.findByPath(subCategory, sectionId);
+ this.sectionService.delete(stakeholder.getType(), section, true);
return true;
}
@PreAuthorize("isAuthenticated()")
- @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{type}/reorder", method = RequestMethod.POST)
- public List reorderSections(@PathVariable("stakeholderId") String stakeholderId,
+ @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/moveIndicator", method = RequestMethod.POST)
+ public SubCategoryFull moveIndicator(@PathVariable("stakeholderId") String stakeholderId,
@PathVariable("topicId") String topicId,
@PathVariable("categoryId") String categoryId,
@PathVariable("subcategoryId") String subcategoryId,
- @PathVariable("type") String type,
- @RequestBody List sections) {
- log.debug("reorder sections of type: "+type);
- log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
-
- SubCategory subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
-
- if (type.equals("chart")) {
- List oldSections = subCategory.getCharts();
- for (String sectionId : oldSections) {
- if (!sections.contains(sectionId)) {
- sections.add(sectionId);
- }
- }
- subCategory.setCharts(sections);
- } else if (type.equals("number")) {
- List oldSections = subCategory.getNumbers();
- for (String sectionId : oldSections) {
- if (!sections.contains(sectionId)) {
- sections.add(sectionId);
- }
- }
- subCategory.setNumbers(sections);
- }
-
- List sectionsFull = new ArrayList<>();
- for(String sectionId : sections) {
- Section section = sectionDAO.findById(sectionId);
- if(section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Reorder sections: Section with id: " + sectionId + " not found");
- }
- sectionsFull.add(section);
- }
-
- subCategoryDAO.save(subCategory);
- log.debug("Sections reordered!");
-
- return sectionsFull;
- }
-
-// @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/toggle-status", method = RequestMethod.POST)
-// public Boolean toggleSectionStatus(@PathVariable("stakeholderId") String stakeholderId,
-// @PathVariable("topicId") String topicId,
-// @PathVariable("categoryId") String categoryId,
-// @PathVariable("subcategoryId") String subcategoryId,
-// @PathVariable("sectionId") String sectionId) {
-// log.debug("toggle section status (isActive)");
-// log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId+ " - Section: "+sectionId);
-//
-// Section section = sectionDAO.findById(sectionId);
-// if (section == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Toggle section status: Section with id: "+sectionId+" not found");
-// }
-// section.setIsActive(!section.getIsActive());
-//
-// this.toggleSection(stakeholderId, topicId, categoryId, subcategoryId, section);
-//
-// return section.getIsActive();
-// }
-
-// @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/toggle-access", method = RequestMethod.POST)
-// public Boolean toggleSectionAccess(@PathVariable("stakeholderId") String stakeholderId,
-// @PathVariable("topicId") String topicId,
-// @PathVariable("categoryId") String categoryId,
-// @PathVariable("subcategoryId") String subcategoryId,
-// @PathVariable("sectionId") String sectionId) {
-// log.debug("toggle section access (isPublic)");
-// log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
-//
-// Section section = sectionDAO.findById(sectionId);
-// if (section == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Toggle section access: Section with id: "+sectionId+" not found");
-// }
-// section.setIsPublic(!section.getIsPublic());
-//
-// this.toggleSection(stakeholderId, topicId, categoryId, subcategoryId);
-//
-// return section.getIsPublic();
-// }
-
-
- public void toggleSection(String stakeholderId, String topicId, String categoryId, String subcategoryId, Section section) {
- SubCategory subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
-
- List sections = null;
- if (section.getType().equals("chart")) {
- sections = subCategory.getCharts();
- } else if (section.getType().equals("number")) {
- sections = subCategory.getNumbers();
- }
-
- if(sections.contains(section.getId())) {
- sectionDAO.save(section);
- log.debug("Section toggled!");
- } else {
- // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subCategory.getAlias();
- throw new PathNotValidException("Toggle section: Section with id: "+section.getId()+" not found in SubCategory: "+subcategoryId);
- }
-
- }
-
- private SubCategory checkForExceptions(String stakeholderId, String topicId, String categoryId, String subcategoryId) {
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-
- if(stakeholder == null) {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
- }
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("CheckForExceptions Section: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- Topic topic = topicDAO.findById(topicId);
- if(topic == null) {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Save indicator: Topic with id: "+topicId+" not found");
- }
-
- if(!stakeholder.getTopics().contains(topicId)) {
- // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
- throw new PathNotValidException("Save indicator: Topic with id: " + topicId + " not found in Stakeholder: " + stakeholderId);
- }
-
- Category category = categoryDAO.findById(categoryId);
- if(category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Save indicator: Category with id: "+categoryId+" not found");
- }
-
- if(!topic.getCategories().contains(categoryId)) {
- // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
- throw new PathNotValidException("Save indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
- }
-
- SubCategory subcategory = subCategoryDAO.findById(subcategoryId);
- if(subcategory == null) {
- // EXCEPTION - SubCategory not found
- throw new EntityNotFoundException("Save indicator: SubCategory with id: "+subcategoryId+" not found");
- }
-
- if (!category.getSubCategories().contains(subcategoryId)) {
- // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
- throw new PathNotValidException("Save indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
- }
-
- return subcategory;
- }
-
- public void deleteTree(SubCategory subCategory) {
- List sections = subCategory.getCharts();
- for(String sectionId : sections) {
- Section section = sectionDAO.findById(sectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Section delete tree: Chart Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
- }
-
- indicatorController.deleteTree(section);
-
- sectionDAO.delete(sectionId);
- }
-
- sections = subCategory.getNumbers();
- for(String sectionId : sections) {
- Section section = sectionDAO.findById(sectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Section delete tree: Number Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
- }
-
- indicatorController.deleteTree(section);
-
- sectionDAO.delete(sectionId);
- }
- }
-
- public void disConnectTree(SubCategory subCategory) {
- List sections = subCategory.getCharts();
- for(String sectionId : sections) {
- Section section = sectionDAO.findById(sectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Section disconnect tree: Chart Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
- }
-
- indicatorController.disConnectTree(section);
-
- section.setDefaultId(null);
- sectionDAO.save(section);
- }
-
- sections = subCategory.getNumbers();
- for(String sectionId : sections) {
- Section section = sectionDAO.findById(sectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Section disconnect tree: Number Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
- }
-
- indicatorController.disConnectTree(section);
-
- section.setDefaultId(null);
- sectionDAO.save(section);
- }
- }
-
- public Section changeVisibilityTree(String sectionId, Visibility visibility) {
- Section section = sectionDAO.findById(sectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Change section visibility: Section with id: " + sectionId + " not found");
- }
-
- Section sectionFull = new Section(section);
- List indicatorsFull = new ArrayList();
-
- for (String indicatorId : section.getIndicators()) {
- indicatorsFull.add(indicatorController.changeVisibilityTree(indicatorId, null, visibility));
- }
-
- sectionFull.setIndicators(indicatorsFull);
- return sectionFull;
+ @RequestBody MoveIndicator moveIndicator) {
+ log.debug("move indicator");
+ log.debug("Stakeholder: " + stakeholderId + " - Topic: " + topicId + " - Category: " + categoryId + " - SubCategory: " + subcategoryId);
+ Stakeholder stakeholder = this.stakeholderService.find(stakeholderId);
+ 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);
}
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java
index f6293a4..2b98882 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java
@@ -1,680 +1,132 @@
package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
-import eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
-import eu.dnetlib.uoamonitorservice.dao.*;
-import eu.dnetlib.uoamonitorservice.entities.*;
-import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
+import eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
+import eu.dnetlib.uoamonitorservice.dto.StakeholderFull;
+import eu.dnetlib.uoamonitorservice.dto.TopicFull;
+import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
+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.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
-import java.util.*;
+import java.util.List;
+import java.util.stream.Collectors;
@RestController
@CrossOrigin(origins = "*")
public class StakeholderController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private RolesUtils rolesUtils;
+ private final PortalService portalService;
+ private final StakeholderService stakeholderService;
@Autowired
- private StakeholderService stakeholderService;
-
- @Autowired
- private StakeholderDAO stakeholderDAO;
-
- @Autowired
- private TopicDAO topicDAO;
-
- @Autowired
- private CategoryDAO categoryDAO;
-
- @Autowired
- private SubCategoryDAO subCategoryDAO;
-
- @Autowired
- private SectionDAO sectionDAO;
-
- @Autowired
- private IndicatorDAO indicatorDAO;
-
- @Autowired
- private TopicController topicController;
-
- @Autowired
- private PortalService portalService;
+ public StakeholderController(PortalService portalService, StakeholderService stakeholderService) {
+ this.portalService = portalService;
+ this.stakeholderService = stakeholderService;
+ }
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/stakeholder/alias", method = RequestMethod.GET)
public List getAllReservedStakeholderAlias() {
-// log.debug("get all stakeholder reserved alias-es");
- List stakeholderAlias = new ArrayList<>();
-
- List stakeholders = stakeholderDAO.findAll();
- if(stakeholders != null) {
- stakeholders.forEach(stakeholder -> {
- stakeholderAlias.add(stakeholder.getAlias());
- });
- }
- stakeholderAlias.add( "all");
+ List stakeholderAlias = this.stakeholderService.getAllAliases();
+ stakeholderAlias.add("all");
stakeholderAlias.add("default");
stakeholderAlias.add("alias");
-
return stakeholderAlias;
}
-// @PreAuthorize("isAuthenticated()")
@PreAuthorize("hasAnyAuthority(" +
- "@AuthorizationService.PORTAL_ADMIN, " +
- "@AuthorizationService.curator(#stakeholderFull.getType()))")
+ "@AuthorizationService.PORTAL_ADMIN, " +
+ "@AuthorizationService.curator(#stakeholder.getType()))")
@RequestMapping(value = "/build-stakeholder", method = RequestMethod.POST)
- public Stakeholder>>>> buildFullStakeholder(@RequestBody Stakeholder>>>> stakeholderFull) {
+ public StakeholderFull buildStakeholder(@RequestBody StakeholderFull stakeholder) {
log.debug("build stakeholder");
- log.debug("Alias: "+stakeholderFull.getAlias());
-
- Stakeholder stakeholder = new Stakeholder<>(stakeholderFull);
-
- List topics = new ArrayList<>();
- List>>>> topicsFull = new ArrayList<>();
- for(Topic topic : stakeholderFull.getTopics()) {
- Topic>>> topicFull = topicController.buildTopic(topic);
- topicsFull.add(topicFull);
- topics.add(topicFull.getId());
- }
- stakeholderFull.setTopics(topicsFull);
- stakeholder.setTopics(topics);
-
- Date date = new Date();
- stakeholder.setCreationDate(date);
- stakeholder.setUpdateDate(date);
-
- stakeholderFull.setCreationDate(date);
- stakeholderFull.setUpdateDate(date);
-
- Stakeholder stakeholderSaved = stakeholderDAO.save(stakeholder);
- stakeholderFull.setId(stakeholderSaved.getId());
-
- Portal portal = portalService.getPortal(stakeholderFull.getAlias());
- if(portal == null) {
+ log.debug("Alias: " + stakeholder.getAlias());
+ Portal portal = portalService.getPortal(stakeholder.getAlias());
+ if (portal == null) {
portal = new Portal();
- portal.setPid(stakeholderFull.getAlias());
- portal.setName(stakeholderFull.getName());
- portal.setType(stakeholderFull.getType());
+ portal.setPid(stakeholder.getAlias());
+ portal.setName(stakeholder.getName());
+ portal.setType(stakeholder.getType());
portalService.insertPortal(portal);
}
-
- return stakeholderFull;
- //return null;
+ return this.stakeholderService.buildStakeholder(stakeholder);
}
- public Stakeholder setFullEntities(Stakeholder stakeholder) {
- boolean addAll = false;
- boolean addPublicAndRestricted = false;
-
-// if(roles == null
-// || roles.contains(authorizationService.PORTAL_ADMIN)
-// || roles.contains(authorizationService.curator(stakeholder.getType()))
-// || roles.contains(authorizationService.manager(stakeholder.getType(), stakeholder.getAlias()))) {
- if(rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- //if(visibility == null || visibility == (Visibility.PRIVATE)) {
- addAll = true;
- //}
- //if(visibility == null || visibility == (Visibility.PRIVATE) || visibility == (Visibility.RESTRICTED)) {
- addPublicAndRestricted = true;
- //}
-// } else if(roles != null && roles.contains(authorizationService.member(stakeholder.getType(), stakeholder.getAlias()))) {
- } else if(rolesUtils.isMember(stakeholder.getType(), stakeholder.getAlias())) {
- //if(visibility == null || visibility == (Visibility.PRIVATE) || visibility == (Visibility.RESTRICTED)) {
- addPublicAndRestricted = true;
- //}
- }
-
- Stakeholder stakeholderFull = new Stakeholder<>(stakeholder);
-
- List topics = new ArrayList<>();
-
- for (String topicId: (List)stakeholder.getTopics()) {
- Topic topic = topicDAO.findById(topicId);
- if(topic == null) {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Get stakeholder: Topic with id: "+topicId+" not found (topic exists in stakeholder: "+stakeholder.getId()+")");
- }
-
- if((!addAll && topic.getVisibility() == Visibility.PRIVATE)
- || (!addPublicAndRestricted && topic.getVisibility() == Visibility.RESTRICTED)) {
- continue;
- }
-
- Topic topicFull = new Topic(topic);
-
- List categories = new ArrayList<>();
-
- for(String categoryId : topic.getCategories()) {
- Category category = categoryDAO.findById(categoryId);
- if(category == null) {
- // EXCEPTION - Category not found
- throw new EntityNotFoundException("Get stakeholder: Category with id: "+categoryId+" not found (category exists in topic: "+topicId+")");
- }
-
- if((!addAll && category.getVisibility() == Visibility.PRIVATE)
- || (!addPublicAndRestricted && category.getVisibility() == Visibility.RESTRICTED)) {
- continue;
- }
-
- Category categoryFull = new Category(category);
-
- List subCategories = new ArrayList<>();
-
- for(String subCategoryId : category.getSubCategories()) {
- SubCategory subCategory = subCategoryDAO.findById(subCategoryId);
- if(subCategory == null) {
- // EXCEPTION - SubCategory not found
- throw new EntityNotFoundException("Get stakeholder: SubCategory with id: "+subCategoryId+" not found (subCategory exists in category: "+categoryId+")");
- }
-
- if((!addAll && subCategory.getVisibility() == Visibility.PRIVATE)
- || (!addPublicAndRestricted && subCategory.getVisibility() == Visibility.RESTRICTED)) {
- continue;
- }
-
- SubCategory subCategoryFull = new SubCategory>(subCategory);
-
- List sectionsCharts = new ArrayList<>();
-
- for(String sectionId : subCategory.getCharts()) {
- sectionsCharts.add(getSectionFull(sectionId, subCategoryId, addAll, addPublicAndRestricted));
- }
- subCategoryFull.setCharts(sectionsCharts);
-
- List sectionsNumbers = new ArrayList<>();
-
- for(String sectionId : subCategory.getNumbers()) {
- sectionsNumbers.add(getSectionFull(sectionId, subCategoryId, addAll, addPublicAndRestricted));
- }
- subCategoryFull.setNumbers(sectionsNumbers);
-
-// List charts = new ArrayList<>();
-// for(String indicatorId : subCategory.getCharts()) {
-// Indicator indicator = indicatorDAO.findById(indicatorId);
-// if(indicator == null) {
-// // EXCEPTION - Indicator not found
-// throw new EntityNotFoundException("Get stakeholder: Indicator with id: "+indicatorId+" not found (indicator exists in subCategory: "+subCategoryId+")");
-// }
-// charts.add(indicator);
-// }
-// subCategoryFull.setCharts(charts);
-//
-// List numbers = new ArrayList<>();
-// for (String indicatorId : subCategory.getNumbers()) {
-// Indicator indicator = indicatorDAO.findById(indicatorId);
-// if (indicator == null) {
-// // EXCEPTION - Indicator not found
-// throw new EntityNotFoundException("Get stakeholder: Indicator with id: " + indicatorId + " not found (indicator exists in subCategory: " + subCategoryId + ")");
-// }
-// numbers.add(indicator);
-// }
-// subCategoryFull.setNumbers(numbers);
-
- subCategories.add(subCategoryFull);
- }
-
- categoryFull.setSubCategories(subCategories);
- categories.add(categoryFull);
- }
-
- topicFull.setCategories(categories);
- topics.add(topicFull);
- }
-
- stakeholderFull.setTopics(topics);
- return stakeholderFull;
- }
-
-// private SubCategory setFullSubcategory(SubCategory subCategory) {
-// SubCategory subCategoryFull = new SubCategory>(subCategory);
-//
-// List sectionsCharts = new ArrayList<>();
-//
-// for(String sectionId : subCategory.getCharts()) {
-// sectionsCharts.add(getSectionFull(sectionId, subCategoryId, addAll, addPublicAndRestricted));
-// }
-// subCategoryFull.setCharts(sectionsCharts);
-//
-// List sectionsNumbers = new ArrayList<>();
-//
-// for(String sectionId : subCategory.getNumbers()) {
-// sectionsNumbers.add(getSectionFull(sectionId, subCategoryId, addAll, addPublicAndRestricted));
-// }
-// subCategoryFull.setNumbers(sectionsNumbers);
-// }
-
- private Section getSectionFull(String sectionId, String subCategoryId, boolean addAll, boolean addPublicAndRestricted) {
- Section section = sectionDAO.findById(sectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Get stakeholder: Section with id: " + sectionId + " not found (section exists in subCategory: " + subCategoryId + ")");
- }
-
- Section sectionFull = new Section(section);
-
- List indicators = new ArrayList<>();
- for (String indicatorId : section.getIndicators()) {
- Indicator indicator = indicatorDAO.findById(indicatorId);
- if (indicator == null) {
- // EXCEPTION - Indicator not found
- throw new EntityNotFoundException("Get stakeholder: Indicator with id: " + indicatorId + " not found (indicator exists in section: " + sectionId + ")");
- }
-
- if((!addAll && indicator.getVisibility() == Visibility.PRIVATE)
- || (!addPublicAndRestricted && indicator.getVisibility() == Visibility.RESTRICTED)) {
- continue;
- }
-
- indicators.add(indicator);
- }
- sectionFull.setIndicators(indicators);
-
- return sectionFull;
- }
-
- @PreAuthorize("hasAnyAuthority(" +
- "@AuthorizationService.PORTAL_ADMIN)")
+ @PreAuthorize("hasAnyAuthority(" + "@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/stakeholder/all", method = RequestMethod.GET)
public List getAllStakeholders(@RequestParam(required = false) String type) {
-// log.debug("get all stakeholders" + (type != null ? " with type: "+type : ""));
-
- List stakeholders;
- if(type == null) {
- stakeholders = stakeholderDAO.findAll();
- } else {
- stakeholders = stakeholderDAO.findByType(type);
- }
-
- List stakeholdersFull = new ArrayList<>();
- for(Stakeholder stakeholder : stakeholders) {
- stakeholdersFull.add(this.setFullEntities(stakeholder));
- }
-
- return stakeholdersFull;
+ return this.stakeholderService.getAll(type);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/stakeholder/default", method = RequestMethod.GET)
- public List getAllDefaultStakeholders(@RequestParam(required = false) String type) {
-// log.debug("get all default stakeholders" + (type != null ? " with type: "+type : ""));
-
- List stakeholders;
- if(type == null) {
- stakeholders = stakeholderDAO.findByDefaultId(null);
- } else {
- stakeholders = stakeholderDAO.findByDefaultIdAndType(null, type);
- }
-
- List stakeholdersFull = new ArrayList<>();
-
- // Remove stakeholders for which i do not have authority
- if(stakeholders != null && stakeholders.size() > 0) {
-// log.debug("ROLES: ");
-// roles.forEach(role -> log.debug(role));
-//
-// if (roles.contains(authorizationService.PORTAL_ADMIN)) {
- if (rolesUtils.isPortalAdmin()) {
- for(Stakeholder stakeholder : stakeholders) {
- stakeholdersFull.add(this.setFullEntities(stakeholder));
- }
- return stakeholdersFull;
- }
-
- Iterator stakeholderIterator = stakeholders.iterator();
- while(stakeholderIterator.hasNext()) {
- Stakeholder stakeholder = stakeholderIterator.next();
-
-// if(roles.contains(authorizationService.curator(stakeholder.getType()))) {
- if(rolesUtils.isCurator(stakeholder.getType())) {
- stakeholdersFull.add(this.setFullEntities(stakeholder));
- continue;
- }
- stakeholderIterator.remove();
- }
- }
-
- return stakeholdersFull;
+ public List getAllDefaultStakeholders(@RequestParam(required = false) String type) {
+ return this.stakeholderService.getAllDefaultByRole(type).stream()
+ .map(this.stakeholderService::getFullStakeholder)
+ .collect(Collectors.toList());
}
@RequestMapping(value = "/stakeholder", method = RequestMethod.GET)
- public List getAllRealStakeholders(@RequestParam(required = false) String type,
+ public List getVisibleStakeholders(@RequestParam(required = false) String type,
@RequestParam(required = false) String defaultId) {
return stakeholderService.getStakeholdersByTypeAndRole(type, defaultId, false);
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/my-stakeholder", method = RequestMethod.GET)
- public List getMyRealStakeholders(@RequestParam(required = false) String type) {
-// log.debug("get my NOT default stakeholders" + (type != null ? " with type: "+type : ""));
+ public List getManagedStakeholders(@RequestParam(required = false) String type) {
return stakeholderService.getStakeholdersByTypeAndRole(type, null, true);
}
@RequestMapping(value = "/stakeholder/{alias:.+}", method = RequestMethod.GET)
- public Stakeholder getStakeholder(@PathVariable("alias") String alias) {
-// log.debug("get stakeholder: "+alias);
-
- Stakeholder stakeholder = stakeholderDAO.findByAlias(alias);
- if(stakeholder == null) {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Get stakeholder: Stakeholder with alias: "+alias+" not found");
+ public StakeholderFull getStakeholder(@PathVariable("alias") String alias) {
+ StakeholderFull stakeholder = this.stakeholderService.getFullStakeholder(this.stakeholderService.findByAlias(alias));
+ if (stakeholder == null) {
+ throw new ForbiddenException("Get stakeholder: You are not authorized to access stakeholder with alias: " + alias);
}
-
-// List roles = authorizationService.getRoles();
- if(stakeholder.getDefaultId() == null && !rolesUtils.isLoggedIn()) {
- // EXCEPTION - Unauthorized
- throw new AccessDeniedException("Get stakeholder: You are not authorized (not logged in) to access stakeholder with alias: "+alias);
- }
- if(stakeholder.getDefaultId() == null && !rolesUtils.hasCreateAndDeleteAuthority(stakeholder.getType())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Get stakeholder: You are not authorized to access stakeholder with alias: "+alias);
- }
-
- if((stakeholder.getVisibility() == Visibility.PRIVATE && !rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())
- || (stakeholder.getVisibility() == Visibility.RESTRICTED && !rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias()) && !rolesUtils.isMember(stakeholder.getType(), stakeholder.getAlias())))) {
-// // EXCEPTION - Access denied
-// throw new ForbiddenException("Get stakeholder: You are not authorized to get stakeholder with alias: "+alias);
- List topicsEmpty = stakeholder.getTopics();
- topicsEmpty.clear();
- stakeholder.setTopics(topicsEmpty);
- stakeholder.setVisibility(Visibility.PRIVATE);
- return stakeholder;
- }
-
- return this.setFullEntities(stakeholder);
+ return stakeholder;
}
-// @PreAuthorize("isAuthenticated()")
@PreAuthorize("hasAnyAuthority("
- + "@AuthorizationService.PORTAL_ADMIN, "
- + "@AuthorizationService.curator(#_stakeholder.getType()), "
- + "@AuthorizationService.manager(#_stakeholder.getType(), #_stakeholder.getAlias()) "
- + ")")
+ + "@AuthorizationService.PORTAL_ADMIN, "
+ + "@AuthorizationService.curator(#stakeholder.getType()), "
+ + "@AuthorizationService.manager(#stakeholder.getType(), #stakeholder.getAlias()) "
+ + ")")
@RequestMapping(value = "/save", method = RequestMethod.POST)
- public Stakeholder saveStakeholder(@RequestBody Stakeholder _stakeholder) {
+ public StakeholderFull saveStakeholder(@RequestBody StakeholderFull stakeholder) {
log.debug("save stakeholder");
- log.debug("Alias: "+_stakeholder.getAlias() + " - Id: "+_stakeholder.getId());
-
-// if(_stakeholder == null) {
-// log.debug("stakeholder null");
-// // EXCEPTION - Parameter for Stakeholder is not accepted
-// }
-
- Stakeholder stakeholder = new Stakeholder<>(_stakeholder);
-
- Date date = new Date();
- stakeholder.setUpdateDate(date);
-
- List topics = new ArrayList<>();
-
- // stakeholder does not exist in DB
- if(_stakeholder.getId() == null) {
- stakeholder.setCreationDate(date);
-
-// for(Topic topic : _stakeholder.getTopics()) {
-// topics.add(topic.getId());
-// }
- } else {
- Stakeholder oldStakeholder = stakeholderDAO.findById(_stakeholder.getId());
- if(oldStakeholder == null) {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("save stakeholder: Stakeholder with id: "+_stakeholder.getId()+" not found");
- }
- for(String topicId : oldStakeholder.getTopics()) {
- Topic topic = topicDAO.findById(topicId);
- if (topic == null) {
- // EXCEPTION - Topic not found
- throw new EntityNotFoundException("Save stakeholder: Topic with id: "+topicId+" not found (topic exists in stakeholder: "+stakeholder.getId()+")");
- }
- topics.add(topic.getId());
- }
-// stakeholder.setTopics(topics);
-// _stakeholder = this.setFullEntities(stakeholder, rolesUtils.getRoles());
- }
-
- stakeholder.setTopics(topics);
-
- Stakeholder stakeholderSaved = stakeholderDAO.save(stakeholder);
- _stakeholder.setId(stakeholderSaved.getId());
- _stakeholder.setCreationDate(stakeholderSaved.getCreationDate());
- _stakeholder.setUpdateDate(stakeholderSaved.getUpdateDate());
-
- topics = null;
- stakeholder = null;
- stakeholderSaved = null;
-
- return _stakeholder;
+ log.debug("Alias: " + stakeholder.getAlias() + " - Id: " + stakeholder.getId());
+ return this.stakeholderService.getFullStakeholder(this.stakeholderService.save(new Stakeholder(stakeholder)));
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/delete", method = RequestMethod.DELETE)
- public boolean deleteStakeholder(@PathVariable("stakeholderId") String stakeholderId) {
+ public boolean deleteStakeholder(@PathVariable("stakeholderId") String id) {
log.debug("delete stakeholder");
- log.debug("Id: "+stakeholderId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- String pid = null;
-
- if(stakeholder != null) {
- pid = stakeholder.getAlias();
-
-// if(!roles.contains(authorizationService.PORTAL_ADMIN)
-// && !roles.contains(authorizationService.curator(stakeholder.getType()))) {
- if(!rolesUtils.hasCreateAndDeleteAuthority(stakeholder.getType())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Delete stakeholder: You are not authorized to delete stakeholder with id: "+stakeholderId);
- }
-
-// for(String topicId : stakeholder.getTopics()) {
-// Topic topic = topicDAO.findById(topicId);
-// if (topic == null) {
-// // EXCEPTION - Topic not found
-// throw new EntityNotFoundException("Delete stakeholder: Topic with id: "+topicId+" not found (topic exists in stakeholder: "+stakeholderId+")");
-// }
-//
-// for (String categoryId : topic.getCategories()) {
-// Category category = categoryDAO.findById(categoryId);
-// if (category == null) {
-// // EXCEPTION - Category not found
-// throw new EntityNotFoundException("Delete stakeholder: Category with id: "+categoryId+" not found (category exists in topic: "+topicId+")");
-// }
-//
-// for (String subCategoryId : category.getSubCategories()) {
-// SubCategory subcategory = subCategoryDAO.findById(subCategoryId);
-// if (subcategory == null) {
-// // EXCEPTION - SubCategory not found
-// throw new EntityNotFoundException("Delete stakeholder: SubCategory with id: "+subCategoryId+" not found (subcategory exists in category: "+categoryId+")");
-// }
-//
-// for(String chartSectionId : subcategory.getCharts()) {
-// Section chartSection = sectionDAO.findById(chartSectionId);
-// if (chartSection == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Delete topic: Section with id: "+chartSectionId+" not found (section exists in subcategory: "+subCategoryId+")");
-// }
-//
-// for (String chartId : chartSection.getIndicators()) {
-// indicatorDAO.delete(chartId);
-// }
-// subcategory.setCharts(null);
-// sectionDAO.delete(chartSectionId);
-// }
-//
-// for(String numberSectionId : subcategory.getNumbers()) {
-// Section numberSection = sectionDAO.findById(numberSectionId);
-// if (numberSection == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Delete topic: Section with id: "+numberSectionId+" not found (section exists in subcategory: "+subCategoryId+")");
-// }
-//
-// for (String numberId : numberSection.getIndicators()) {
-// indicatorDAO.delete(numberId);
-// }
-// subcategory.setNumbers(null);
-// sectionDAO.delete(numberSectionId);
-// }
-//
-// subCategoryDAO.delete(subCategoryId);
-// }
-// category.setSubCategories(null);
-// categoryDAO.delete(categoryId);
-// }
-// topic.setCategories(null);
-// topicDAO.delete(topicId);
-// }
-
- topicController.deleteTree(stakeholder);
-
- stakeholder.setTopics(null);
- stakeholderDAO.delete(stakeholderId);
- log.debug("Stakeholder deleted!");
-
- Portal portal = portalService.getPortal(pid);
- if(portal != null) {
- portalService.deletePortal(portal.getId());
- }
- } else {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Delete stakeholder: Stakeholder with id: "+stakeholderId+" not found");
+ log.debug("Id: " + id);
+ Portal portal = portalService.getPortal(this.stakeholderService.delete(id));
+ if (portal != null) {
+ portalService.deletePortal(portal.getId());
}
return true;
}
-
-// @RequestMapping(value = "/{stakeholderId}/toggle-status", method = RequestMethod.POST)
-// public Boolean toggleStakeholderStatus(@PathVariable("stakeholderId") String stakeholderId) {
-// log.debug("toggle stakeholder status (isActive)");
-// log.debug("Stakeholder: "+stakeholderId);
-//
-// Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-// if (stakeholder == null) {
-// // EXCEPTION - Stakeholder not found
-// throw new EntityNotFoundException("Toggle stakeholder status: Stakeholder with id: "+stakeholderId+" not found");
-// }
-// stakeholder.setIsActive(!stakeholder.getIsActive());
-//
-// stakeholderDAO.save(stakeholder);
-// log.debug("Stakeholder toggled!");
-//
-// return stakeholder.getIsActive();
-// }
-//
-// @RequestMapping(value = "/{stakeholderId}/toggle-access", method = RequestMethod.POST)
-// public Boolean toggleStakeholderAccess(@PathVariable("stakeholderId") String stakeholderId) {
-// log.debug("toggle stakeholder access (isPublic)");
-// log.debug("Stakeholder: "+stakeholderId);
-//
-// Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
-// if (stakeholder == null) {
-// // EXCEPTION - Stakeholder not found
-// throw new EntityNotFoundException("Toggle stakeholder access: Stakeholder with id: "+stakeholderId+" not found");
-// }
-// stakeholder.setIsPublic(!stakeholder.getIsPublic());
-//
-// stakeholderDAO.save(stakeholder);
-// log.debug("Stakeholder toggled!");
-//
-// return stakeholder.getIsPublic();
-// }
-
-
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/change-visibility", method = RequestMethod.POST)
- public Stakeholder changeStakeholderVisibility(@PathVariable("stakeholderId") String stakeholderId,
- @RequestParam("visibility") Visibility visibility, @RequestParam(required = false) Boolean propagate) {
- log.debug("change stakeholder visibility: "+visibility + " - toggle propagate: "+((propagate != null && propagate) ? "true" : "false"));
- log.debug("Stakeholder: "+stakeholderId);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- if (stakeholder == null) {
- // EXCEPTION - Stakeholder not found
- throw new EntityNotFoundException("Change stakeholder visibility: Stakeholder with id: "+stakeholderId+" not found");
- }
-
-// List roles = authorizationService.getRoles();
-
-// if(!roles.contains(authorizationService.PORTAL_ADMIN)
-// && !roles.contains(authorizationService.curator(stakeholder.getType()))
-// && !roles.contains(authorizationService.manager(stakeholder.getType(), stakeholder.getAlias()))) {
- if(!rolesUtils.hasUpdateAuthority(stakeholder.getType(), stakeholder.getAlias())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Change stakeholder visibility: You are not authorized to update stakeholder with id: "+stakeholderId);
- }
-
- return changeStakeholderVisibilityTree(stakeholder, visibility, propagate);
+ public StakeholderFull changeStakeholderVisibility(@PathVariable("stakeholderId") String stakeholderId,
+ @RequestParam("visibility") Visibility visibility, @RequestParam(defaultValue = "false") 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);
}
-
- private Stakeholder changeStakeholderVisibilityTree(Stakeholder stakeholder, Visibility visibility, Boolean propagate) {
- Stakeholder stakeholderFull = new Stakeholder<>(stakeholder);
- List topicsFull = new ArrayList<>();
-
- if(propagate != null && propagate) {
- for (String topicId : stakeholder.getTopics()) {
- topicsFull.add(topicController.changeVisibilityTree(topicId, visibility, propagate));
- }
- }
-
- stakeholder.setVisibility(visibility);
- stakeholderDAO.save(stakeholder);
- log.debug("Stakeholder toggled!");
-
- stakeholderFull.setVisibility(visibility);
- stakeholderFull.setTopics(topicsFull);
-
- return stakeholder;
- }
-
- // The following are not supposed to be used
-// @RequestMapping(value = "/stakeholder/dates", method = RequestMethod.GET)
-// public List getAllStakeholderDates() {
-// List profiles = stakeholderDAO.findAll();
-// List profileDates = new ArrayList<>();
-//
-// int i=0;
-// for(Stakeholder profile : profiles) {
-// log.debug(profile.getCreationDate());
-// profileDates.add(profile.getCreationDate());
-// log.debug(profileDates.get(i));
-// i++;
-// }
-// return profileDates;
-// }
-//
-// @RequestMapping(value = "/stakeholder/dates1", method = RequestMethod.GET)
-// public List getAllStakeholderDates1() {
-// List profiles = stakeholderDAO.findAll();
-// List profileDates = new ArrayList<>();
-//
-// for(Stakeholder profile : profiles) {
-// log.debug(profile.getCreationDate().toString());
-// profileDates.add(profile.getCreationDate().toString());
-// }
-// return profileDates;
-// }
-//
-// @RequestMapping(value = "/stakeholder/dates2", method = RequestMethod.GET)
-// public List getAllStakeholderDates2() {
-// List profiles = stakeholderDAO.findAll();
-// List profileDates = new ArrayList<>();
-// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-//
-// for(Stakeholder profile : profiles) {
-// log.debug(format.format(profile.getCreationDate()));
-// profileDates.add(format.format(profile.getCreationDate()));
-// }
-// return profileDates;
-// }
}
diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SubCategoryController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SubCategoryController.java
index 06c005f..01aa2fd 100644
--- a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SubCategoryController.java
+++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/SubCategoryController.java
@@ -1,20 +1,21 @@
package eu.dnetlib.uoamonitorservice.controllers;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
-import eu.dnetlib.uoamonitorservice.dao.*;
-import eu.dnetlib.uoamonitorservice.entities.*;
-import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
-import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
-import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
+import eu.dnetlib.uoamonitorservice.dto.SubCategoryFull;
+import eu.dnetlib.uoamonitorservice.entities.Category;
+import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
+import eu.dnetlib.uoamonitorservice.entities.SubCategory;
+import eu.dnetlib.uoamonitorservice.entities.Topic;
+import eu.dnetlib.uoamonitorservice.primitives.Visibility;
+import eu.dnetlib.uoamonitorservice.service.CategoryService;
+import eu.dnetlib.uoamonitorservice.service.StakeholderService;
+import eu.dnetlib.uoamonitorservice.service.SubCategoryService;
+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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
import java.util.List;
@RestController
@@ -22,220 +23,31 @@ import java.util.List;
public class SubCategoryController {
private final Logger log = LogManager.getLogger(this.getClass());
- @Autowired
- private RolesUtils rolesUtils;
+ private final StakeholderService stakeholderService;
+ private final TopicService topicService;
+ private final CategoryService categoryService;
+ private final SubCategoryService subCategoryService;
@Autowired
- private StakeholderDAO stakeholderDAO;
-
- @Autowired
- private TopicDAO topicDAO;
-
- @Autowired
- private CategoryDAO categoryDAO;
-
- @Autowired
- private SubCategoryDAO subCategoryDAO;
-
- @Autowired
- private SectionDAO sectionDAO;
-
- @Autowired
- private IndicatorDAO indicatorDAO;
-
- @Autowired
- private SectionController sectionController;
-
- public SubCategory> buildSubCategory(SubCategory> subcategoryFull) {
- SubCategory subCategory = new SubCategory<>(subcategoryFull);
-
- List sectionCharts = new ArrayList<>();
- List> sectionChartsFull = new ArrayList<>();
-
- for(Section section : subcategoryFull.getCharts()) {
- Section sectionFull = sectionController.buildSection(section);
- sectionChartsFull.add(sectionFull);
- sectionCharts.add(sectionFull.getId());
- }
- subcategoryFull.setCharts(sectionChartsFull);
- subCategory.setCharts(sectionCharts);
-
- List sectionNumbers = new ArrayList<>();
- List> sectionNumbersFull = new ArrayList<>();
-
- for(Section section : subcategoryFull.getNumbers()) {
- Section sectionFull = sectionController.buildSection(section);
- sectionNumbersFull.add(sectionFull);
- sectionNumbers.add(sectionFull.getId());
- }
- subcategoryFull.setNumbers(sectionNumbersFull);
- subCategory.setNumbers(sectionNumbers);
-
- Date date = new Date();
- subCategory.setCreationDate(date);
- subCategory.setUpdateDate(date);
-
- subcategoryFull.setCreationDate(date);
- subcategoryFull.setUpdateDate(date);
-
-
- subCategoryDAO.save(subCategory);
-
- subcategoryFull.setId(subCategory.getId());
- return subcategoryFull;
+ public SubCategoryController(StakeholderService stakeholderService, TopicService topicService, CategoryService categoryService, SubCategoryService subCategoryService) {
+ this.stakeholderService = stakeholderService;
+ this.topicService = topicService;
+ this.categoryService = categoryService;
+ this.subCategoryService = subCategoryService;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/save", method = RequestMethod.POST)
- public SubCategory> saveSubCategory(@PathVariable("stakeholderId") String stakeholderId,
- @PathVariable("topicId") String topicId,
- @PathVariable("categoryId") String categoryId,
- @RequestBody SubCategory> subcategoryFull) {
+ public 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);
-
- Category category = checkForExceptions(stakeholderId, topicId, categoryId);
-
- SubCategory subCategory = new SubCategory<>(subcategoryFull);
-
- Date date = new Date();
- subCategory.setUpdateDate(date);
- subcategoryFull.setUpdateDate(date);
-
- List chartSections = new ArrayList<>();
- List numberSections = new ArrayList<>();
-
- SubCategory oldSubcategory = null;
- if(subcategoryFull.getId() != null) {
- oldSubcategory = subCategoryDAO.findById(subcategoryFull.getId());
- if(oldSubcategory == null) {
- // EXCEPTION - SubCategory not found
- throw new EntityNotFoundException("save subcategory: SubCategory with id: " + subcategoryFull.getId() + " not found");
- }
-
- for(String chartSectionId : oldSubcategory.getCharts()) {
- Section section = sectionDAO.findById(chartSectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Save subcategory: Chart section with id: "+chartSectionId+" not found (section exists in subcategory: "+subCategory.getId()+")");
- }
- chartSections.add(section.getId());
- }
-
- for(String numberSectionId : oldSubcategory.getNumbers()) {
- Section section = sectionDAO.findById(numberSectionId);
- if (section == null) {
- // EXCEPTION - Section not found
- throw new EntityNotFoundException("Save subcategory: Number section with id: "+numberSectionId+" not found (section exists in subcategory: "+subCategory.getId()+")");
- }
- numberSections.add(section.getId());
- }
- } else { // subcategory does not exist in DB
- subCategory.setCreationDate(date);
- subcategoryFull.setCreationDate(date);
-
- for(Section chartSection : subcategoryFull.getCharts()) {
- chartSections.add(chartSection.getId());
- }
-
- for(Section numberSection : subcategoryFull.getNumbers()) {
- numberSections.add(numberSection.getId());
- }
- }
-
-// List charts = new ArrayList<>();
-// for(Indicator chart : subcategoryFull.getCharts()) {
-// charts.add(chart.getId());
-// }
-// subCategory.setCharts(charts);
-//
-// List numbers = new ArrayList<>();
-// for(Indicator numbr : subcategoryFull.getNumbers()) {
-// numbers.add(numbr.getId());
-// }
-// subCategory.setNumbers(numbers);
-
-
- subCategory.setCharts(chartSections);
- subCategory.setNumbers(numberSections);
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- if(stakeholder.getDefaultId() == null) {
- if(subcategoryFull.getId() == null) {
- subCategoryDAO.save(subCategory);
- onSaveDefaultSubCategory(subCategory, categoryId);
- } else {
- onUpdateDefaultSubCategory(subCategory, oldSubcategory);
- subCategoryDAO.save(subCategory);
- }
- } else {
- subCategoryDAO.save(subCategory);
- }
-
- List subcategories = category.getSubCategories();
- int index = subcategories.indexOf(subCategory.getId());
- if(index == -1) {
- subcategories.add(subCategory.getId());
- categoryDAO.save(category);
- log.debug("Subcategory saved!");
-
- subcategoryFull.setId(subCategory.getId());
- }
-
- chartSections = null;
- numberSections = null;
- subCategory = null;
-
- return subcategoryFull;
- }
-
- public void onSaveDefaultSubCategory(SubCategory subCategory, String categoryId) {
- log.debug("On save default subCategory");
-
- List categories = categoryDAO.findByDefaultId(categoryId);
- for(Category category : categories) {
- SubCategory subCategoryNew = new SubCategory();
- subCategoryNew.copyFromDefault(subCategory);
-
- subCategoryDAO.save(subCategoryNew);
-
- List subCategories = category.getSubCategories();
- subCategories.add(subCategoryNew.getId());
-
- categoryDAO.save(category);
- }
- }
-
- public void onUpdateDefaultSubCategory(SubCategory subCategory, SubCategory oldSubcategory) {
- log.debug("On update default subCategory");
-
- List subCategories = subCategoryDAO.findByDefaultId(subCategory.getId());
- boolean changed = false;
- for(SubCategory subCategoryBasedOnDefault : subCategories) {
- if(subCategory.getName() != null && !subCategory.getName().equals(subCategoryBasedOnDefault.getName())
- && (oldSubcategory.getName() == null || oldSubcategory.getName().equals(subCategoryBasedOnDefault.getName()))) {
-
- subCategoryBasedOnDefault.setName(subCategory.getName());
- subCategoryBasedOnDefault.setAlias(subCategory.getAlias());
- changed = true;
- }
- if(subCategory.getDescription() != null && !subCategory.getDescription().equals(subCategoryBasedOnDefault.getDescription())
- && (oldSubcategory.getDescription() == null || oldSubcategory.getDescription().equals(subCategoryBasedOnDefault.getDescription()))) {
-
- subCategoryBasedOnDefault.setDescription(subCategory.getDescription());
- changed = true;
- }
-
- if(!changed) {
-// break;
- continue;
- }
-
-// subCategoryBasedOnDefault.setName(subCategory.getName());
-// subCategoryBasedOnDefault.setDescription(subCategory.getDescription());
- subCategoryBasedOnDefault.setUpdateDate(subCategory.getUpdateDate());
- subCategoryDAO.save(subCategoryBasedOnDefault);
- }
+ 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);
+ return this.subCategoryService.save(stakeholder, category, new SubCategory(subcategoryFull));
}
@PreAuthorize("isAuthenticated()")
@@ -246,325 +58,43 @@ public class SubCategoryController {
@PathVariable("subcategoryId") String subcategoryId,
@RequestParam(required = false) String children) {
log.debug("delete subcategory");
- log.debug("Id: "+subcategoryId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId);
-
- Category category = checkForExceptions(stakeholderId, topicId, categoryId);
-
- SubCategory subcategory = subCategoryDAO.findById(subcategoryId);
- if(subcategory != null) {
-
- Stakeholder stakeholder = stakeholderDAO.findById(stakeholderId);
- if(subcategory.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(stakeholder.getType())) {
- // EXCEPTION - Access denied
- throw new ForbiddenException("Delete subcategory: You are not authorized to delete a default SubCategory in stakeholder with id: "+stakeholderId);
- }
-
- List subcategories = category.getSubCategories();
- int index = subcategories.indexOf(subcategoryId);
- if(index != -1) {
- // this subCategory belongs in default profile
- if(category.getDefaultId() == null && children != null) {
- onDeleteDefaultSubCategory(subcategoryId, categoryId, children);
- }
-
-// for(String chartSectionId : subcategory.getCharts()) {
-// Section chartSection = sectionDAO.findById(chartSectionId);
-// if (chartSection == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Delete SubCategory: Section with id: "+chartSectionId+" not found (section exists in subcategory: "+subcategoryId+")");
-// }
-//
-// for (String chartId : chartSection.getIndicators()) {
-// indicatorDAO.delete(chartId);
-// }
-// subcategory.setCharts(null);
-// sectionDAO.delete(chartSectionId);
-// }
-//
-// for(String numberSectionId : subcategory.getNumbers()) {
-// Section numberSection = sectionDAO.findById(numberSectionId);
-// if (numberSection == null) {
-// // EXCEPTION - Section not found
-// throw new EntityNotFoundException("Delete SubCategory: Section with id: "+numberSectionId+" not found (section exists in subcategory: "+subcategoryId+")");
-// }
-//
-// for (String numberId : numberSection.getIndicators()) {
-// indicatorDAO.delete(numberId);
-// }
-// subcategory.setNumbers(null);
-// sectionDAO.delete(numberSectionId);
-// }
-
- sectionController.deleteTree(subcategory);
-
- subcategory.setCharts(null);
- subcategory.setNumbers(null);
-
- subcategories.remove(index);
- categoryDAO.save(category);
-
- subCategoryDAO.delete(subcategoryId);
- log.debug("Subcategory deleted!");
- } else {
- // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
- throw new PathNotValidException("Delete subcategory: Subcategory with id: "+subcategoryId+" not found in Category: "+categoryId);
- }
-
- } else {
- // EXCEPTION - SubCategory not found
- throw new EntityNotFoundException("Delete subcategory: SubCategory with id: "+subcategoryId+" not found");
- }
- return true;
- }
-
- public boolean onDeleteDefaultSubCategory(String defaultSubCategoryId, String defaultCategoryId, String children) {
- if(children.equals("delete")) {
- List categories = categoryDAO.findByDefaultId(defaultCategoryId);
- List subCategories = subCategoryDAO.findByDefaultId(defaultSubCategoryId);
-
- for(Category category : categories) {
- Iterator