Project

General

Profile

1
package eu.dnetlib.uoamonitorservice.controllers;
2

    
3
import eu.dnetlib.uoamonitorservice.dao.*;
4
import eu.dnetlib.uoamonitorservice.entities.*;
5
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
6
import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
7
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
8
import eu.dnetlib.uoamonitorservice.handlers.utils.RolesUtils;
9
import org.apache.log4j.Logger;
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.security.access.AccessDeniedException;
12
import org.springframework.security.access.prepost.PreAuthorize;
13
import org.springframework.web.bind.annotation.*;
14

    
15
import java.util.ArrayList;
16
import java.util.Date;
17
import java.util.Iterator;
18
import java.util.List;
19

    
20
@RestController
21
@CrossOrigin(origins = "*")
22
public class SectionController {
23
    private final Logger log = Logger.getLogger(this.getClass());
24

    
25
    @Autowired
26
    private RolesUtils rolesUtils;
27

    
28
    @Autowired
29
    private StakeholderDAO stakeholderDAO;
30

    
31
    @Autowired
32
    private TopicDAO topicDAO;
33

    
34
    @Autowired
35
    private CategoryDAO categoryDAO;
36

    
37
    @Autowired
38
    private SubCategoryDAO subCategoryDAO;
39

    
40
    @Autowired
41
    private SectionDAO sectionDAO;
42

    
43
    @Autowired
44
    private IndicatorDAO indicatorDAO;
45

    
46
    @Autowired
47
    private IndicatorController indicatorController;
48

    
49
    public Section<Indicator> buildSection(Section<Indicator> sectionFull) {
50
        Section<String> section = new Section<>(sectionFull);
51

    
52
        List<String> indicators = new ArrayList<>();
53
        List<Indicator> indicatorsFull = new ArrayList<>();
54
        for(Indicator chart : sectionFull.getIndicators()) {
55
            Indicator chartSaved = indicatorDAO.save(chart);
56
            chart.setId(chartSaved.getId());
57
            indicatorsFull.add(chart);
58
            indicators.add(chartSaved.getId());
59
        }
60
        sectionFull.setIndicators(indicatorsFull);
61
        section.setIndicators(indicators);
62

    
63
        Date date = new Date();
64
        section.setCreationDate(date);
65
        section.setUpdateDate(date);
66

    
67
        sectionFull.setCreationDate(date);
68
        sectionFull.setUpdateDate(date);
69

    
70
        sectionDAO.save(section);
71

    
72
        sectionFull.setId(section.getId());
73
        return sectionFull;
74
    }
75

    
76
    @PreAuthorize("isAuthenticated()")
77
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/save/{index}", method = RequestMethod.POST)
78
    public Section saveSection(@PathVariable("stakeholderId") String stakeholderId,
79
                               @PathVariable("topicId") String topicId,
80
                               @PathVariable("categoryId") String categoryId,
81
                               @PathVariable("subcategoryId") String subcategoryId,
82
                               @PathVariable("index") String index,
83
                               @RequestBody Section<Indicator> sectionFull) {
84
        log.debug("save section");
85
        log.debug("Name: "+sectionFull.getTitle() + " - Id: "+sectionFull.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
86

    
87
        SubCategory<String> subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
88

    
89
        Section<String> section = new Section<>(sectionFull);
90

    
91
        Date date = new Date();
92
        section.setUpdateDate(date);
93
        sectionFull.setUpdateDate(date);
94

    
95
        List<String> indicators = new ArrayList<>();
96

    
97
        Section<String> oldSection = null;
98
        if(sectionFull.getId() != null) {
99
            oldSection = sectionDAO.findById(sectionFull.getId());
100
            if(oldSection == null) {
101
                // EXCEPTION - Section not found
102
                throw new EntityNotFoundException("save section: Section with id: " + sectionFull.getId() + " not found");
103
            }
104

    
105
            for(String indicatorId : oldSection.getIndicators()) {
106
                Indicator indicator = indicatorDAO.findById(indicatorId);
107
                if (indicator == null) {
108
                    // EXCEPTION - Indicator not found
109
                    throw new EntityNotFoundException("Save section: Indicator with id: "+indicatorId+" not found (indicator exists in section: "+section.getId()+")");
110
                }
111
                indicators.add(indicator.getId());
112
            }
113
        } else { // section does not exist in DB
114
            section.setCreationDate(date);
115
            sectionFull.setCreationDate(date);
116

    
117
            for(Indicator indicator : sectionFull.getIndicators()) {
118
                indicators.add(indicator.getId());
119
            }
120
        }
121

    
122
        String sectionId = sectionFull.getId();
123

    
124
        section.setIndicators(indicators);
125

    
126
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
127
        // this section belongs in default profile and it is new or it is updated
128
        if(stakeholder.getDefaultId() == null) {
129
            if(sectionId == null) {
130
                sectionDAO.save(section);
131
                onSaveDefaultSection(section, topicId, categoryId, subcategoryId, stakeholder);
132
            }
133
            else {
134
                onUpdateDefaultSection(section, stakeholder, oldSection);
135
                sectionDAO.save(section);
136
            }
137
        } else {
138
            sectionDAO.save(section);
139
        }
140

    
141
        List<String> sections = null;
142
        if(sectionFull.getType().equals("chart")) {
143
            sections = subCategory.getCharts();
144
        } else if(sectionFull.getType().equals("number")) {
145
            sections = subCategory.getNumbers();
146
        }
147

    
148
        int existing_index = sections.indexOf(section.getId());
149
        if (existing_index == -1) {
150
            if(Integer.parseInt(index) != -1) {
151
                sections.add(Integer.parseInt(index), section.getId());
152
            } else {
153
                sections.add(section.getId());
154
            }
155
            subCategoryDAO.save(subCategory);
156
            log.debug("Section saved!");
157

    
158
            sectionFull.setId(section.getId());
159
        }
160

    
161
        return sectionFull;
162
    }
163

    
164
    public void onSaveDefaultSection(Section section,
165
                                     String defaultTopicId, String defaultCategoryId,
166
                                     String defaultSubcategoryId, Stakeholder defaultStakeholder) {
167
        log.debug("On save default section");
168

    
169

    
170
        // new section in default profile - add it on profiles of the same type
171
        List<SubCategory> subCategories = subCategoryDAO.findByDefaultId(defaultSubcategoryId);
172

    
173
        for (SubCategory subCategory : subCategories) {
174
            Category parentCategory = categoryDAO.findBySubCategoriesContaining(subCategory.getId());
175
            Topic parentTopic = topicDAO.findByCategoriesContaining(parentCategory.getId());
176
            Stakeholder parentStakeholder = stakeholderDAO.findByTopicsContaining(parentTopic.getId());
177

    
178
            Section sectionNew = new Section();
179
            sectionNew.copyFromDefault(section);
180

    
181
            sectionNew.setStakeholderAlias(parentStakeholder.getAlias());
182

    
183
            sectionDAO.save(sectionNew);
184

    
185
            List<String> sections = null;
186
            if (section.getType().equals("chart")) {
187
                sections = subCategory.getCharts();
188
            } else if (section.getType().equals("number")) {
189
                sections = subCategory.getNumbers();
190
            }
191
            sections.add(sectionNew.getId());
192

    
193
            subCategoryDAO.save(subCategory);
194
        }
195
    }
196

    
197
    public void onUpdateDefaultSection(Section section, Stakeholder stakeholder, Section oldSection) {
198
        log.debug("On update default section");
199

    
200
        // section already exists - check if changed and update all sections based on it
201

    
202
        boolean changed = false;
203
        List<Section> sections = sectionDAO.findByDefaultId(section.getId());
204

    
205
        for(Section sectionBasedOnDefault : sections) {
206
            if(section.getTitle() != null && !section.getTitle().equals(sectionBasedOnDefault.getTitle())
207
                    && (oldSection.getTitle() == null || oldSection.getTitle().equals(sectionBasedOnDefault.getTitle()))) {
208

    
209
                sectionBasedOnDefault.setTitle(section.getTitle());
210
                changed = true;
211
            }
212

    
213
            if(!changed) {
214
//                break;
215
                continue;
216
            }
217

    
218
//            sectionBasedOnDefault.setTitle(section.getTitle());
219
            sectionBasedOnDefault.setUpdateDate(section.getUpdateDate());
220
            sectionDAO.save(sectionBasedOnDefault);
221
        }
222
    }
223

    
224
    @PreAuthorize("isAuthenticated()")
225
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/delete", method = RequestMethod.DELETE)
226
    public boolean deleteSection(@PathVariable("stakeholderId") String stakeholderId,
227
                                 @PathVariable("topicId") String topicId,
228
                                 @PathVariable("categoryId") String categoryId,
229
                                 @PathVariable("subcategoryId") String subcategoryId,
230
                                 @PathVariable("sectionId") String sectionId,
231
                                 @RequestParam(required = false) String children) {
232
        log.debug("delete section");
233
        log.debug("Id: "+sectionId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
234

    
235
        Section section = sectionDAO.findById(sectionId);
236
        if(section != null) {
237
            SubCategory<String> subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
238

    
239
            Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
240
            List<String> roles = rolesUtils.getRoles();
241
            if(section.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(roles, stakeholder.getType())) {
242
                // EXCEPTION - Access denied
243
                throw new ForbiddenException("Delete section: You are not authorized to delete a default Section in stakeholder with id: "+stakeholderId);
244
            }
245

    
246
            String type = "";
247
            List<String> sections = null;
248
            if (section.getType().equals("chart")) {
249
                sections = subCategory.getCharts();
250
                type = "chart";
251
            } else if (section.getType().equals("number")) {
252
                sections = subCategory.getNumbers();
253
                type = "number";
254
            }
255

    
256
            int index = sections.indexOf(sectionId);
257
            if (index != -1) {
258
                // this section belongs in default profile
259
                if(subCategory.getDefaultId() == null && children != null) {
260
                    onDeleteDefaultSection(sectionId, subcategoryId, children, type);
261
                }
262

    
263
                indicatorController.deleteTree(section);
264

    
265
                sections.remove(index);
266
                subCategoryDAO.save(subCategory);
267

    
268
                sectionDAO.delete(sectionId);
269
                log.debug("Section deleted!");
270
            } else {
271
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
272
                throw new PathNotValidException("Delete section: Section with id: "+sectionId+" not found in SubCategory: "+subcategoryId);
273
            }
274
        } else {
275
            // EXCEPTION - Section not found
276
            throw new EntityNotFoundException("Delete section: Section with id: "+sectionId+" not found");
277
        }
278
        return true;
279
    }
280

    
281
    public boolean onDeleteDefaultSection(String defaultSectionId, String defaultSubCategoryId, String children, String type) {
282
        if(children.equals("delete")) {
283
            List<SubCategory> subCategories = subCategoryDAO.findByDefaultId(defaultSubCategoryId);
284
            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
285

    
286
            for(SubCategory subCategory : subCategories) {
287
                Iterator<Section> sectionsIterator = sections.iterator();
288
                while(sectionsIterator.hasNext()) {
289
                    Section section = sectionsIterator.next();
290

    
291
                    String sectionId = section.getId();
292
                    List<String> subCategorySections = null;
293
                    if(type.equals("chart")) {
294
                        subCategorySections = subCategory.getCharts();
295
                    } else if(type.equals("number")) {
296
                        subCategorySections = subCategory.getNumbers();
297
                    }
298
                    if(subCategorySections != null && subCategorySections.contains(sectionId)) {
299
                        sectionsIterator.remove();
300

    
301
                        subCategorySections.remove(sectionId);
302
                        subCategoryDAO.save(subCategory);
303

    
304
                        indicatorController.deleteTree(section);
305

    
306
                        sectionDAO.delete(sectionId);
307
                        log.debug("Section with id: "+sectionId+" deleted!");
308

    
309
                        break;
310
                    }
311
                }
312
            }
313
        } else if(children.equals("disconnect")) {
314
            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
315
            for(Section section : sections) {
316
                indicatorController.disConnectTree(section);
317

    
318
                section.setDefaultId(null);
319
                sectionDAO.save(section);
320

    
321
                log.debug("DefaultId for Section with id: "+section.getId()+" empty!");
322
            }
323
        }
324
        return true;
325
    }
326

    
327
    @PreAuthorize("isAuthenticated()")
328
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{type}/reorder", method = RequestMethod.POST)
329
    public List<Section> reorderSections(@PathVariable("stakeholderId") String stakeholderId,
330
                                         @PathVariable("topicId") String topicId,
331
                                         @PathVariable("categoryId") String categoryId,
332
                                         @PathVariable("subcategoryId") String subcategoryId,
333
                                         @PathVariable("type") String type,
334
                                         @RequestBody List<String> sections) {
335
        log.debug("reorder sections of type: "+type);
336
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
337

    
338
        SubCategory<String> subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
339

    
340
        if (type.equals("chart")) {
341
            List<String> oldSections = subCategory.getCharts();
342
            for (String sectionId : oldSections) {
343
                if (!sections.contains(sectionId)) {
344
                    sections.add(sectionId);
345
                }
346
            }
347
            subCategory.setCharts(sections);
348
        } else if (type.equals("number")) {
349
            List<String> oldSections = subCategory.getNumbers();
350
            for (String sectionId : oldSections) {
351
                if (!sections.contains(sectionId)) {
352
                    sections.add(sectionId);
353
                }
354
            }
355
            subCategory.setNumbers(sections);
356
        }
357

    
358
        List<Section> sectionsFull = new ArrayList<>();
359
        for(String sectionId : sections) {
360
            Section section = sectionDAO.findById(sectionId);
361
            if(section == null) {
362
                // EXCEPTION - Section not found
363
                throw new EntityNotFoundException("Reorder sections: Section with id: " + sectionId + " not found");
364
            }
365
            sectionsFull.add(section);
366
        }
367

    
368
        subCategoryDAO.save(subCategory);
369
        log.debug("Sections reordered!");
370

    
371
        return sectionsFull;
372
    }
373

    
374
//    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/toggle-status", method = RequestMethod.POST)
375
//    public Boolean toggleSectionStatus(@PathVariable("stakeholderId") String stakeholderId,
376
//                                       @PathVariable("topicId") String topicId,
377
//                                       @PathVariable("categoryId") String categoryId,
378
//                                       @PathVariable("subcategoryId") String subcategoryId,
379
//                                       @PathVariable("sectionId") String sectionId) {
380
//        log.debug("toggle section status (isActive)");
381
//        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId+ " - Section: "+sectionId);
382
//
383
//        Section section = sectionDAO.findById(sectionId);
384
//        if (section == null) {
385
//            // EXCEPTION - Section not found
386
//            throw new EntityNotFoundException("Toggle section status: Section with id: "+sectionId+" not found");
387
//        }
388
//        section.setIsActive(!section.getIsActive());
389
//
390
//        this.toggleSection(stakeholderId, topicId, categoryId, subcategoryId, section);
391
//
392
//        return section.getIsActive();
393
//    }
394

    
395
//    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/toggle-access", method = RequestMethod.POST)
396
//    public Boolean toggleSectionAccess(@PathVariable("stakeholderId") String stakeholderId,
397
//                                         @PathVariable("topicId") String topicId,
398
//                                         @PathVariable("categoryId") String categoryId,
399
//                                         @PathVariable("subcategoryId") String subcategoryId,
400
//                                         @PathVariable("sectionId") String sectionId) {
401
//        log.debug("toggle section access (isPublic)");
402
//        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId);
403
//
404
//        Section section = sectionDAO.findById(sectionId);
405
//        if (section == null) {
406
//            // EXCEPTION - Section not found
407
//            throw new EntityNotFoundException("Toggle section access: Section with id: "+sectionId+" not found");
408
//        }
409
//        section.setIsPublic(!section.getIsPublic());
410
//
411
//        this.toggleSection(stakeholderId, topicId, categoryId, subcategoryId);
412
//
413
//        return section.getIsPublic();
414
//    }
415

    
416

    
417
    public void toggleSection(String stakeholderId, String topicId, String categoryId, String subcategoryId, Section section) {
418
        SubCategory<String> subCategory = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId);
419

    
420
        List<String> sections = null;
421
        if (section.getType().equals("chart")) {
422
            sections = subCategory.getCharts();
423
        } else if (section.getType().equals("number")) {
424
            sections = subCategory.getNumbers();
425
        }
426

    
427
        if(sections.contains(section.getId())) {
428
            sectionDAO.save(section);
429
            log.debug("Section toggled!");
430
        } else {
431
            // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subCategory.getAlias();
432
            throw new PathNotValidException("Toggle section: Section with id: "+section.getId()+" not found in SubCategory: "+subcategoryId);
433
        }
434

    
435
    }
436

    
437
    private SubCategory checkForExceptions(String stakeholderId, String topicId, String categoryId, String subcategoryId) {
438

    
439
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
440

    
441
        if(stakeholder == null) {
442
            // EXCEPTION - Stakeholder not found
443
            throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
444
        }
445

    
446
        List<String> roles = rolesUtils.getRoles();
447
        if(!rolesUtils.hasUpdateAuthority(roles, stakeholder.getType(), stakeholder.getAlias())) {
448
            // EXCEPTION - Access denied
449
            throw new ForbiddenException("CheckForExceptions Section: You are not authorized to update stakeholder with id: "+stakeholderId);
450
        }
451

    
452
        Topic<String> topic = topicDAO.findById(topicId);
453
        if(topic == null) {
454
            // EXCEPTION - Topic not found
455
            throw new EntityNotFoundException("Save indicator: Topic with id: "+topicId+" not found");
456
        }
457

    
458
        if(!stakeholder.getTopics().contains(topicId)) {
459
            // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
460
            throw new PathNotValidException("Save indicator: Topic with id: " + topicId + " not found in Stakeholder: " + stakeholderId);
461
        }
462

    
463
        Category<String> category = categoryDAO.findById(categoryId);
464
        if(category == null) {
465
            // EXCEPTION - Category not found
466
            throw new EntityNotFoundException("Save indicator: Category with id: "+categoryId+" not found");
467
        }
468

    
469
        if(!topic.getCategories().contains(categoryId)) {
470
            // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
471
            throw new PathNotValidException("Save indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
472
        }
473

    
474
        SubCategory<String> subcategory = subCategoryDAO.findById(subcategoryId);
475
        if(subcategory == null) {
476
            // EXCEPTION - SubCategory not found
477
            throw new EntityNotFoundException("Save indicator: SubCategory with id: "+subcategoryId+" not found");
478
        }
479

    
480
        if (!category.getSubCategories().contains(subcategoryId)) {
481
            // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
482
            throw new PathNotValidException("Save indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
483
        }
484

    
485
        return  subcategory;
486
    }
487

    
488
    public void deleteTree(SubCategory subCategory) {
489
        List<String> sections = subCategory.getCharts();
490
        for(String sectionId : sections) {
491
            Section section = sectionDAO.findById(sectionId);
492
            if (section == null) {
493
                // EXCEPTION - Section not found
494
                throw new EntityNotFoundException("Section delete tree: Chart Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
495
            }
496

    
497
            indicatorController.deleteTree(section);
498

    
499
            sectionDAO.delete(sectionId);
500
        }
501

    
502
        sections = subCategory.getNumbers();
503
        for(String sectionId : sections) {
504
            Section section = sectionDAO.findById(sectionId);
505
            if (section == null) {
506
                // EXCEPTION - Section not found
507
                throw new EntityNotFoundException("Section delete tree: Number Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
508
            }
509

    
510
            indicatorController.deleteTree(section);
511

    
512
            sectionDAO.delete(sectionId);
513
        }
514
    }
515

    
516
    public void disConnectTree(SubCategory subCategory) {
517
        List<String> sections = subCategory.getCharts();
518
        for(String sectionId : sections) {
519
            Section section = sectionDAO.findById(sectionId);
520
            if (section == null) {
521
                // EXCEPTION - Section not found
522
                throw new EntityNotFoundException("Section disconnect tree: Chart Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
523
            }
524

    
525
            indicatorController.disConnectTree(section);
526

    
527
            section.setDefaultId(null);
528
            sectionDAO.save(section);
529
        }
530

    
531
        sections = subCategory.getNumbers();
532
        for(String sectionId : sections) {
533
            Section section = sectionDAO.findById(sectionId);
534
            if (section == null) {
535
                // EXCEPTION - Section not found
536
                throw new EntityNotFoundException("Section disconnect tree: Number Section with id: "+sectionId+" not found (section exists in subCategory: "+subCategory.getId()+")");
537
            }
538

    
539
            indicatorController.disConnectTree(section);
540

    
541
            section.setDefaultId(null);
542
            sectionDAO.save(section);
543
        }
544
    }
545
}
(5-5/9)