Project

General

Profile

1
package eu.dnetlib.uoamonitorservice.controllers;
2

    
3

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

    
16
import java.io.UnsupportedEncodingException;
17
import java.lang.reflect.Field;
18
import java.net.URLEncoder;
19
import java.util.*;
20

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

    
26
    @Autowired
27
    private RolesUtils rolesUtils;
28

    
29
    @Autowired
30
    private StakeholderDAO stakeholderDAO;
31

    
32
    @Autowired
33
    private TopicDAO topicDAO;
34

    
35
    @Autowired
36
    private CategoryDAO categoryDAO;
37

    
38
    @Autowired
39
    private SubCategoryDAO subCategoryDAO;
40

    
41
    @Autowired
42
    private SectionDAO sectionDAO;
43

    
44
    @Autowired
45
    private IndicatorDAO indicatorDAO;
46

    
47

    
48
    @PreAuthorize("isAuthenticated()")
49
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/save", method = RequestMethod.POST)
50
    public Indicator saveIndicator(@PathVariable("stakeholderId") String stakeholderId,
51
                                   @PathVariable("topicId") String topicId,
52
                                   @PathVariable("categoryId") String categoryId,
53
                                   @PathVariable("subcategoryId") String subcategoryId,
54
                                   @PathVariable("sectionId") String sectionId,
55
                                   @RequestBody Indicator indicator) throws UnsupportedEncodingException {
56
        log.debug("save indicator");
57
        log.debug("Name: "+indicator.getName() + " - Id: "+indicator.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
58

    
59
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
60

    
61
        Date date = new Date();
62
        indicator.setUpdateDate(date);
63

    
64
        Indicator oldIndicator = null;
65
        if(indicator.getId() != null) {
66
            oldIndicator = indicatorDAO.findById(indicator.getId());
67
            if(oldIndicator == null) {
68
                // EXCEPTION - Indicator not found
69
                throw new EntityNotFoundException("save indicator: Indicator with id: " + indicator.getId() + " not found");
70
            }
71
        } else { // indicator does not exist in DB
72
            indicator.setCreationDate(date);
73
        }
74

    
75
        String indicatorId = indicator.getId();
76

    
77
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
78
        // this indicator belongs in default profile and it is new or it is updated
79
        if(stakeholder.getDefaultId() == null) {
80
            if(indicatorId == null) {
81
                indicatorDAO.save(indicator);
82
                onSaveDefaultIndicator(indicator, sectionId);
83
            }
84
            else {
85
                onUpdateDefaultIndicator(indicator, stakeholder, oldIndicator);
86
                indicatorDAO.save(indicator);
87
            }
88
        } else {
89
            indicatorDAO.save(indicator);
90
        }
91

    
92
        List<String> indicators = section.getIndicators();
93

    
94
        int index = indicators.indexOf(indicator.getId());
95
        if (index == -1) {
96
            indicators.add(indicator.getId());
97
            sectionDAO.save(section);
98
            log.debug("Indicator saved!");
99
        }
100

    
101
        return indicator;
102
    }
103

    
104
    public void onSaveDefaultIndicator(Indicator indicator, String defaultSectionId) throws UnsupportedEncodingException {
105
        log.debug("On save default indicator");
106

    
107
        // new indicator in default profile - add it on profiles of the same type
108
        List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
109

    
110
       for (Section section : sections) {
111
            Indicator indicatorNew = new Indicator();
112
            indicatorNew.copyFromDefault(indicator);
113
            for (IndicatorPath indicatorPath : indicatorNew.getIndicatorPaths()) {
114
                Stakeholder stakeholder = stakeholderDAO.findByAlias(section.getStakeholderAlias());
115
                parameterMapping(indicatorPath, stakeholder);
116
            }
117

    
118
            indicatorDAO.save(indicatorNew);
119

    
120
            List<String> indicators = section.getIndicators();
121
            indicators.add(indicatorNew.getId());
122

    
123
            sectionDAO.save(section);
124
        }
125
    }
126

    
127
    public void onUpdateDefaultIndicator(Indicator indicator, Stakeholder stakeholder, Indicator oldIndicator) throws UnsupportedEncodingException {
128
        log.debug("On update default indicator");
129

    
130
        // indicator already exists - check if changed and update all indicators based on it
131

    
132
        boolean changed;
133
        List<Indicator> indicators = indicatorDAO.findByDefaultId(indicator.getId());
134

    
135
        for(Indicator indicatorBasedOnDefault : indicators) {
136
            changed = false;
137

    
138
//            if(indicator.getName() != null && !indicator.getName().equals(indicatorBasedOnDefault.getName())
139
//                    && (oldIndicator.getName() == null || oldIndicator.getName().equals(indicatorBasedOnDefault.getName()))) {
140
            if((
141
                    (indicator.getName() == null && oldIndicator.getName() != null)
142
                            ||
143
                            (indicator.getName() != null && !indicator.getName().equals(indicatorBasedOnDefault.getName()))
144
            ) && (
145
                    (oldIndicator.getName() == null && indicatorBasedOnDefault.getName() == null)
146
                            ||
147
                            (oldIndicator.getName() != null && oldIndicator.getName().equals(indicatorBasedOnDefault.getName()))
148
            )) {
149
                indicatorBasedOnDefault.setName(indicator.getName());
150
                changed = true;
151
            }
152

    
153
            if(indicator.getDescription() != null && !indicator.getDescription().equals(indicatorBasedOnDefault.getDescription())
154
                || indicator.getDescription() == null && indicatorBasedOnDefault.getDescription() != null) {
155

    
156
                indicatorBasedOnDefault.setDescription(indicator.getDescription());
157
                changed = true;
158
            }
159

    
160
//            if(indicator.getAdditionalDescription() != null && !indicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription())
161
//                    && (oldIndicator.getAdditionalDescription() == null || oldIndicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription()))) {
162
            if((
163
                    (indicator.getAdditionalDescription() == null && oldIndicator.getAdditionalDescription() != null)
164
                            ||
165
                            (indicator.getAdditionalDescription() != null && !indicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription()))
166
            ) && (
167
                    (oldIndicator.getAdditionalDescription() == null && indicatorBasedOnDefault.getAdditionalDescription() == null)
168
                            ||
169
                            (oldIndicator.getAdditionalDescription() != null && oldIndicator.getAdditionalDescription().equals(indicatorBasedOnDefault.getAdditionalDescription()))
170
            )) {
171
                indicatorBasedOnDefault.setAdditionalDescription(indicator.getAdditionalDescription());
172
                changed = true;
173
            }
174

    
175
            int i = 0;
176
            List<IndicatorPath> indicatorPaths = indicatorBasedOnDefault.getIndicatorPaths();
177
            if(indicatorPaths == null && indicator.getIndicatorPaths() != null) {
178
                indicatorPaths = new ArrayList<>();
179
            }
180

    
181
            for (IndicatorPath indicatorPath : indicator.getIndicatorPaths()) {
182
                IndicatorPath indicatorPathBasedOnDefault = null;
183
                if(i < indicatorPaths.size()) {
184
                    indicatorPathBasedOnDefault = indicatorPaths.get(i);
185
                }
186

    
187
                if(indicatorPathBasedOnDefault == null) {
188
                    // Add new indicator path in existing indicators
189
                    IndicatorPath indicatorPathNew = new IndicatorPath(indicatorPath);
190
                    parameterMapping(indicatorPathNew, stakeholder);
191
                    indicatorPaths.add(indicatorPathNew);
192
                    changed = true;
193
                } else {
194
                    IndicatorPath oldIndicatorPath = oldIndicator.getIndicatorPaths().get(i);
195

    
196
                    // Check if there are changes in indicator path and update existing indicators if needed
197
                    log.debug("update indicator path: "+i + " (indicator id: "+indicatorBasedOnDefault.getId()+")");
198

    
199
//                    if(indicatorPath.getType() != null
200
//                            && !indicatorPath.getType().equals(indicatorPathBasedOnDefault.getType())
201
//                            && (oldIndicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))) {
202
                    if((
203
                            (indicatorPath.getType() == null && oldIndicatorPath.getType() != null)
204
                                    ||
205
                                    (indicatorPath.getType() != null && !indicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))
206
                    ) && (
207
                            (oldIndicatorPath.getType() == null && indicatorPathBasedOnDefault.getType() == null)
208
                                    ||
209
                                    (oldIndicatorPath.getType() != null && oldIndicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))
210
                    )) {
211
                        indicatorPathBasedOnDefault.setType(indicatorPath.getType());
212
                        changed = true; // parameter "type" needs to be changed as well
213
                    }
214
                    log.debug("After type check: "+changed);
215

    
216
//                    if(indicatorPath.getSource() != null
217
//                            && !indicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource())
218
//                            && (oldIndicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))) {
219
                    if((
220
                            (indicatorPath.getSource() == null && oldIndicatorPath.getSource() != null)
221
                                    ||
222
                                    (indicatorPath.getSource() != null && !indicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))
223
                    ) && (
224
                            (oldIndicatorPath.getSource() == null && indicatorPathBasedOnDefault.getSource() == null)
225
                                    ||
226
                                    (oldIndicatorPath.getSource() != null && oldIndicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))
227
                    )) {
228
                        indicatorPathBasedOnDefault.setSource(indicatorPath.getSource());
229
                        changed = true;
230
                    }
231
                    log.debug("After source check: "+changed);
232

    
233
//                    if(indicatorPath.getUrl() != null
234
//                            && !indicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl())
235
//                            && (oldIndicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))) {
236
                    if((
237
                            (indicatorPath.getUrl() == null && oldIndicatorPath.getUrl() != null)
238
                                    ||
239
                                    (indicatorPath.getUrl() != null && !indicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))
240
                    ) && (
241
                            (oldIndicatorPath.getUrl() == null && indicatorPathBasedOnDefault.getUrl() == null)
242
                                    ||
243
                                    (oldIndicatorPath.getUrl() != null && oldIndicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))
244
                    )) {
245
                        indicatorPathBasedOnDefault.setUrl(indicatorPath.getUrl());
246
                        changed = true;
247
                    }
248
                    log.debug("After url check: "+changed);
249

    
250
                    if((
251
                            (indicatorPath.getChartObject() == null && oldIndicatorPath.getChartObject() != null)
252
                            ||
253
                            (indicatorPath.getChartObject() != null && !indicatorPath.getChartObject().equals(indicatorPathBasedOnDefault.getChartObject()))
254
                        ) && (
255
                            (oldIndicatorPath.getChartObject() == null && indicatorPathBasedOnDefault.getChartObject() == null)
256
                            ||
257
                            (oldIndicatorPath.getChartObject() != null && oldIndicatorPath.getChartObject().equals(indicatorPathBasedOnDefault.getChartObject()))
258
                    )) {
259

    
260
                        indicatorPathBasedOnDefault.setChartObject(indicatorPath.getChartObject());
261
                        changed = true;
262
                    }
263
                    log.debug("After chartObject check: "+changed);
264

    
265
                    if(indicatorPath.getParameters() != null) {
266
                        if (indicatorPathBasedOnDefault.getParameters() == null) {
267
                            indicatorPathBasedOnDefault.setParameters(new HashMap<>());
268
                        }
269
                        //if (indicatorPath.getParameters().size() != indicatorPathBasedOnDefault.getParameters().size()) {
270
                            //log.debug("Different number of parameters");
271
                        for (Map.Entry<String, String> parameter : indicatorPath.getParameters().entrySet()) {
272
                            log.debug("\nindicatorPath: parameter.getKey(): "+parameter.getKey()+" - value: "+parameter.getValue()
273
                                    +"\nindicatorPathBasedOnDefault:parameters:key: "+  indicatorPathBasedOnDefault.getParameters().get(parameter.getKey())
274
                                    +"\noldIndicatorPath:parameters:key: "+  (oldIndicatorPath.getParameters() == null ? "null" : oldIndicatorPath.getParameters().get(parameter.getKey())));
275
                            if (!indicatorPathBasedOnDefault.getParameters().containsKey(parameter.getKey())
276
                                    || (oldIndicatorPath.getParameters() == null || oldIndicatorPath.getParameters().get(parameter.getKey()) == null
277
                                        || (oldIndicatorPath.getParameters().get(parameter.getKey()).equals(indicatorPathBasedOnDefault.getParameters().get(parameter.getKey()))
278
                                            && !parameter.getValue().equals(indicatorPathBasedOnDefault.getParameters().get(parameter.getKey()))))
279
                            ) {
280
                                indicatorPathBasedOnDefault.getParameters().put(parameter.getKey(), parameter.getValue());
281
                                changed = true;
282
                            }
283
//                            else if(parameter.getKey().equals("type")) {
284
//                                indicatorPathBasedOnDefault.getParameters().put(parameter.getKey(), parameter.getValue());
285
//                                changed = true;
286
//                            }
287
                        }
288

    
289
                        // When deleting indicator path parameters in a default profile, delete them also from all children profiles
290
                        if(oldIndicatorPath.getParameters() != null && indicatorPath.getParameters().size() < oldIndicatorPath.getParameters().size()) {
291
                            for (Map.Entry<String, String> parameter : oldIndicatorPath.getParameters().entrySet()) {
292
                                if(!indicatorPath.getParameters().containsKey(parameter.getKey())) {
293
                                    indicatorPathBasedOnDefault.getParameters().remove(parameter.getKey());
294
                                }
295
                            }
296
                        }
297
                        parameterMapping(indicatorPathBasedOnDefault, stakeholder);
298
                        //}
299
                    }
300
                    log.debug("After parameters check: " + changed);
301

    
302
                    if(indicatorPath.getJsonPath() != null) {
303
                        boolean jsonPathChanged = false;
304
                        boolean breaked = false;
305

    
306
                        int oldJsonPathSize = 0;
307
                        if(oldIndicatorPath.getJsonPath() != null) {
308
                            oldJsonPathSize = oldIndicatorPath.getJsonPath().size();
309
                        }
310
                        int basedOnDefaultJsonPathSize = 0;
311
                        if(indicatorPathBasedOnDefault.getJsonPath() != null) {
312
                            basedOnDefaultJsonPathSize = indicatorPathBasedOnDefault.getJsonPath().size();
313
                        }
314
                        log.debug("old: "+oldJsonPathSize+" - based on default: "+basedOnDefaultJsonPathSize+" - new: "+indicatorPath.getJsonPath().size());
315
                        if(oldJsonPathSize == basedOnDefaultJsonPathSize) {
316
                            if(indicatorPathBasedOnDefault.getJsonPath() == null && indicatorPath.getJsonPath().size() > 0) {
317
                                indicatorPathBasedOnDefault.setJsonPath(new ArrayList<>());
318
                            }
319

    
320
                            int basedOnDefaultIndex = 0;
321
                            int oldIndex = 0;
322

    
323
                            Iterator<String> jsonStringBasedOnDefaultIterator = indicatorPathBasedOnDefault.getJsonPath().iterator();
324
                            while (jsonStringBasedOnDefaultIterator.hasNext()) {
325
                                String jsonStringBasedOnDefault = jsonStringBasedOnDefaultIterator.next();
326
                                if(oldIndicatorPath.getJsonPath().get(oldIndex).equals(jsonStringBasedOnDefault)) {
327
                                    if(basedOnDefaultIndex >= indicatorPath.getJsonPath().size()) { // string deleted
328
                                        jsonStringBasedOnDefaultIterator.remove();
329
                                        jsonPathChanged = true;
330
                                    } else {    // check if string changed
331
                                        if(!indicatorPath.getJsonPath().get(basedOnDefaultIndex).equals(jsonStringBasedOnDefault)) {
332
                                            indicatorPathBasedOnDefault.getJsonPath().set(basedOnDefaultIndex, indicatorPath.getJsonPath().get(basedOnDefaultIndex));
333
                                            jsonPathChanged = true;
334
                                        }
335
                                        basedOnDefaultIndex++;
336
                                    }
337
                                    oldIndex++;
338
                                } else {
339
                                    breaked = true;
340
                                    jsonPathChanged = false;
341
                                    log.debug("not the same: "+oldIndex);
342
                                    break;
343
                                }
344
                            }
345

    
346
                            int index=0;
347
                            if(!breaked && indicatorPath.getJsonPath().size() > indicatorPathBasedOnDefault.getJsonPath().size()) { // strings added
348
                                jsonPathChanged = true;
349
                                for(index=indicatorPathBasedOnDefault.getJsonPath().size(); index < indicatorPath.getJsonPath().size(); index++) {
350
                                    indicatorPathBasedOnDefault.getJsonPath().add(indicatorPath.getJsonPath().get(index));
351
                                }
352
                            }
353

    
354
                            if(jsonPathChanged) {
355
                                changed = true;
356
                            }
357
                        }
358
                        // TODO when deleting indicator path json path strings... --> is this done? (line 327)
359
                    }
360
                    log.debug("After jsonPath check: " + changed);
361
                }
362
                i++;
363
            }
364
            // TODO when deleting indicator paths...
365

    
366
            if(!changed) {
367
//                break;
368
                continue;
369
            }
370

    
371
            indicatorBasedOnDefault.setUpdateDate(indicator.getUpdateDate());
372
            indicatorDAO.save(indicatorBasedOnDefault);
373
        }
374
    }
375

    
376
    public void parameterMapping(IndicatorPath indicatorPath, Stakeholder stakeholder) throws UnsupportedEncodingException {
377
        if (indicatorPath.getParameters() != null) {
378
            if (indicatorPath.getParameters().containsKey("index_name")) {
379
                indicatorPath.getParameters().put("index_name", stakeholder.getIndex_name());
380
            } else if (indicatorPath.getParameters().containsKey("index_shortName")) {
381
                indicatorPath.getParameters().put("index_shortName", stakeholder.getIndex_name().toLowerCase());
382
            } else if (indicatorPath.getParameters().containsKey("index_id")) {
383
                indicatorPath.getParameters().put("index_id", stakeholder.getIndex_id());
384
            }
385
        }
386

    
387
//        // url encoding for number indicators
388
//        String url = indicatorPath.getUrl();
389
//        String encoded_index_id = urlEncode(URLEncoder.encode(stakeholder.getIndex_id(), "UTF-8"));
390
//        url = url.replace("index_id", encoded_index_id);
391
//        String encoded_index_name = urlEncode(URLEncoder.encode(stakeholder.getIndex_name(), "UTF-8"));
392
//        url = url.replace("index_name", encoded_index_name);
393
//        String encoded_index_shortName = urlEncode(URLEncoder.encode(stakeholder.getIndex_shortName(), "UTF-8"));
394
//        url = url.replace("index_shortName", encoded_index_shortName);
395
//        indicatorPath.setUrl(url);
396
    }
397

    
398
    public String urlEncode(String encodedIndicatorPathField) {
399
        String indicatorPathField = "";
400

    
401
        for( int i=0; i<encodedIndicatorPathField.length(); i++ ){
402
            String character = encodedIndicatorPathField.substring(i, i+1);
403

    
404
            if(character.equals("+")) {
405
                indicatorPathField = indicatorPathField.concat("%20");
406
            } else if(character.equals("%")) {
407
                //grab the hex in pairs
408
                String output = encodedIndicatorPathField.substring(i+1, (i + 3));
409

    
410
                if(output.equals("7E") || output.equals("27") || output.equals("28") || output.equals("29") || output.equals("21")) {
411
                    //convert hex to decimal
412
                    int decimal = Integer.parseInt(output, 16);
413
                    //convert the decimal to character
414
                    StringBuilder sb = new StringBuilder();
415
                    sb.append((char) decimal);
416

    
417
                    indicatorPathField = indicatorPathField.concat(sb.toString());
418
                } else {
419
                    indicatorPathField = indicatorPathField.concat(character + output);
420
                }
421

    
422
                i += 2;
423
            } else {
424
                indicatorPathField = indicatorPathField.concat(character);
425
            }
426
        }
427

    
428
        return indicatorPathField;
429
    }
430

    
431
    @PreAuthorize("isAuthenticated()")
432
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/delete", method = RequestMethod.DELETE)
433
    public boolean deleteIndicator(@PathVariable("stakeholderId") String stakeholderId,
434
                                   @PathVariable("topicId") String topicId,
435
                                   @PathVariable("categoryId") String categoryId,
436
                                   @PathVariable("subcategoryId") String subcategoryId,
437
                                   @PathVariable("sectionId") String sectionId,
438
                                   @PathVariable("indicatorId") String indicatorId,
439
                                   @RequestParam(required = false) String children) {
440
        log.debug("delete indicator");
441
        log.debug("Id: "+indicatorId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
442

    
443
        Indicator indicator = indicatorDAO.findById(indicatorId);
444
        if(indicator != null) {
445
            Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
446

    
447
            Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
448
            List<String> roles = rolesUtils.getRoles();
449
            if(indicator.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(roles, stakeholder.getType())) {
450
                // EXCEPTION - Access denied
451
                throw new ForbiddenException("Delete indicator: You are not authorized to delete a default Indicator in stakeholder with id: "+stakeholderId);
452
            }
453

    
454
            List<String> indicators = section.getIndicators();
455

    
456
            int index = indicators.indexOf(indicatorId);
457
            if (index != -1) {
458

    
459
                // this indicator belongs in default profile
460
                if(section.getDefaultId() == null && children != null) {
461
                    onDeleteDefaultIndicator(indicatorId, sectionId, children);
462
                }
463

    
464

    
465
                indicators.remove(index);
466
                sectionDAO.save(section);
467

    
468
                indicatorDAO.delete(indicatorId);
469
                log.debug("Indicator deleted!");
470
            } else {
471
                // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
472
                throw new PathNotValidException("Delete indicator: Indicator with id: "+indicatorId+" not found in Sectiom: "+sectionId);
473
            }
474
        } else {
475
            // EXCEPTION - Indicator not found
476
            throw new EntityNotFoundException("Delete indicator: Indicator with id: "+indicatorId+" not found");
477
        }
478
        return true;
479
    }
480

    
481
    public boolean onDeleteDefaultIndicator(String defaultIndicatorId, String defaultSectionId, String children) {
482
        if(children.equals("delete")) {
483
//            // 1st way
484
//            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
485
//
486
//            for(Section section : sections) {
487
//                List<String> indicators = section.getIndicators();
488
//
489
//                Iterator<String> indicatorsIterator = indicators.iterator();
490
//                while(indicatorsIterator.hasNext()) {
491
//                    String indicatorId = indicatorsIterator.next();
492
//
493
//                    Indicator indicator = indicatorDAO.findById(indicatorId);
494
//                    if (indicator.getDefaultId().equals(defaultIndicatorId)) {
495
//                        indicatorsIterator.remove();
496
//                        sectionDAO.save(section);
497
//
498
//                        indicatorDAO.delete(indicatorId);
499
//                        log.debug("Indicator deleted!");
500
//
501
//                        break;
502
//                    }
503
//                }
504
//            }
505

    
506
            // 2nd way
507
            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
508
            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
509

    
510
            for(Section section : sections) {
511
                Iterator<Indicator> indicatorsIterator = indicators.iterator();
512
                while(indicatorsIterator.hasNext()) {
513
                    String indicatorId = indicatorsIterator.next().getId();
514
                    if(section.getIndicators().contains(indicatorId)) {
515
                        indicatorsIterator.remove();
516

    
517
                        section.getIndicators().remove(indicatorId);
518
                        sectionDAO.save(section);
519

    
520
                        indicatorDAO.delete(indicatorId);
521
                        log.debug("Indicator with id: "+indicatorId+" deleted!");
522

    
523
                        break;
524
                    }
525
                }
526
            }
527

    
528
//            // 3rd way - parentId
529
//            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
530
//            for(Indicator indicator : indicators) {
531
//                Section section = sectionDAO.findById(indicator.getParent());
532
//                List<String> sectionIndicators = section.getIndicators();
533
//
534
//                sectionIndicators.remove(indicator.getId());
535
//                sectionDAO.save(section);
536
//
537
//                indicatorDAO.delete(indicator.getId());
538
//                log.debug("Indicator deleted!");
539
//            }
540
        } else if(children.equals("disconnect")) {
541
            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
542
            for(Indicator indicator : indicators) {
543
                indicator.setDefaultId(null);
544
                indicatorDAO.save(indicator);
545
                log.debug("DefaultId for Indicator with id: "+indicator.getId()+" empty!");
546
            }
547
        }
548
        return true;
549
    }
550

    
551
//    @RequestMapping(value = "/{stakeholderId}/charts/delete", method = RequestMethod.DELETE)
552
//    public boolean deleteAllChartIndicators(@PathVariable("stakeholderId") String stakeholderId) {
553
//        log.debug("delete all chart indicators of stakeholder");
554
//        log.debug("Stakeholder: "+stakeholderId);
555
//
556
//        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
557
//        if(stakeholder != null) {
558
//
559
//            for(String topicId : stakeholder.getTopics()) {
560
//                Topic<String> topic = topicDAO.findById(topicId);
561
//                if(topic != null) {
562
//                    for(String categoryId : topic.getCategories()) {
563
//                        Category<String> category = categoryDAO.findById(categoryId);
564
//                        if(category != null) {
565
//                            for(String subcategoryId : category.getSubCategories()) {
566
//                                SubCategory<String> subcategory = subCategoryDAO.findById(subcategoryId);
567
//                                if(subcategory != null) {
568
//
569
//                                    for(String sectionId : subcategory.getCharts()) {
570
//                                        Section<String> section = sectionDAO.findById(sectionId);
571
//                                        if (section != null) {
572
//
573
//                                            List<String> indicators = section.getIndicators();
574
//                                            Iterator<String> indicatorsIterator = section.getIndicators().iterator();
575
//
576
//                                            while (indicatorsIterator.hasNext()) {
577
//                                                String indicatorId = indicatorsIterator.next();
578
//                                                Indicator indicator = indicatorDAO.findById(indicatorId);
579
//                                                if (indicator != null) {
580
//                                                    int index = indicators.indexOf(indicatorId);
581
//                                                    if (index != -1) {
582
//                                                        indicatorsIterator.remove();
583
//                                                        //indicators.remove(index);
584
//
585
//                                                        indicatorDAO.delete(indicatorId);
586
//                                                        log.debug("Indicator deleted!");
587
//                                                    } else {
588
//                                                        // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
589
//                                                        throw new PathNotValidException("Delete indicator: Indicator with id: " + indicatorId + " not found in Section: " + sectionId);
590
//                                                    }
591
//                                                } else {
592
//                                                    // EXCEPTION - Indicator not found
593
//                                                    throw new EntityNotFoundException("Delete indicator: Indicator with id: " + indicatorId + " not found");
594
//                                                }
595
//                                            }
596
//                                            sectionDAO.save(section);
597
//                                        } else {
598
//                                            // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
599
//                                            throw new PathNotValidException("Delete indicator: Section with id: " + sectionId + " not found in SubCategory: " + subcategoryId);
600
//                                        }
601
//                                    }
602
//                                } else {
603
//                                    // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
604
//                                    throw new PathNotValidException("Delete indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
605
//                                }
606
//                            }
607
//                        } else {
608
//                            // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
609
//                            throw new PathNotValidException("Delete indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
610
//                        }
611
//                    }
612
//                } else {
613
//                    // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
614
//                    throw new PathNotValidException("Delete indicator: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
615
//                }
616
//            }
617
//        } else {
618
//            // EXCEPTION - Stakeholder not found
619
//            throw new EntityNotFoundException("Delete indicator: Stakeholder with id: "+stakeholderId+" not found");
620
//        }
621
//        return true;
622
//    }
623

    
624
    @PreAuthorize("isAuthenticated()")
625
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{type}/reorder", method = RequestMethod.POST)
626
    public List<Indicator> reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
627
                                             @PathVariable("topicId") String topicId,
628
                                             @PathVariable("categoryId") String categoryId,
629
                                             @PathVariable("subcategoryId") String subcategoryId,
630
                                             @PathVariable("sectionId") String sectionId,
631
                                             @PathVariable("type") String type,
632
                                             @RequestBody ReorderEvent reorderEvent) {
633
        log.debug("reorder indicators of type: "+type);
634
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
635

    
636
        List<String> indicators = reorderEvent.getIds();
637
        String actionType = reorderEvent.getAction();
638
        String targetId = reorderEvent.getTarget();
639

    
640
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, type);
641

    
642
        List<String> oldIndicators = section.getIndicators();
643
        for (String indicatorId : oldIndicators) {
644
            if ((!actionType.equals("removed") || !targetId.equals(indicatorId)) && !indicators.contains(indicatorId)) {
645
                indicators.add(indicatorId);
646
            }
647
        }
648
        section.setIndicators(indicators);
649

    
650
        List<Indicator> indicatorsFull = new ArrayList<>();
651
        for(String indicatorId : indicators) {
652
            Indicator indicator = indicatorDAO.findById(indicatorId);
653
            if(indicator == null) {
654
                // EXCEPTION - Indicator not found
655
                throw new EntityNotFoundException("Reorder indicators: Indicator with id: " + indicatorId + " not found");
656
            }
657
            indicatorsFull.add(indicator);
658
        }
659

    
660
        sectionDAO.save(section);
661
        log.debug("Indicators reordered!");
662

    
663
        return indicatorsFull;
664
    }
665

    
666
//    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/toggle-status", method = RequestMethod.POST)
667
//    public Boolean toggleIndicatorStatus(@PathVariable("stakeholderId") String stakeholderId,
668
//                                         @PathVariable("topicId") String topicId,
669
//                                         @PathVariable("categoryId") String categoryId,
670
//                                         @PathVariable("subcategoryId") String subcategoryId,
671
//                                         @PathVariable("sectionId") String sectionId,
672
//                                         @PathVariable("indicatorId") String indicatorId) {
673
//        log.debug("toggle indicator status (isActive)");
674
//        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
675
//
676
//        Indicator indicator = indicatorDAO.findById(indicatorId);
677
//        if (indicator == null) {
678
//            // EXCEPTION - Indicator not found
679
//            throw new EntityNotFoundException("Toggle indicator status: Indicator with id: "+indicatorId+" not found");
680
//        }
681
//        indicator.setIsActive(!indicator.getIsActive());
682
//
683
//        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
684
//
685
//        return indicator.getIsActive();
686
//    }
687
//
688
//    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/toggle-access", method = RequestMethod.POST)
689
//    public Boolean toggleIndicatorAccess(@PathVariable("stakeholderId") String stakeholderId,
690
//                                         @PathVariable("topicId") String topicId,
691
//                                         @PathVariable("categoryId") String categoryId,
692
//                                         @PathVariable("subcategoryId") String subcategoryId,
693
//                                         @PathVariable("sectionId") String sectionId,
694
//                                         @PathVariable("indicatorId") String indicatorId) {
695
//        log.debug("toggle indicator access (isPublic)");
696
//        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
697
//
698
//        Indicator indicator = indicatorDAO.findById(indicatorId);
699
//        if (indicator == null) {
700
//            // EXCEPTION - Indicator not found
701
//            throw new EntityNotFoundException("Toggle indicator access: Indicator with id: "+indicatorId+" not found");
702
//        }
703
//        indicator.setIsPublic(!indicator.getIsPublic());
704
//
705
//        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
706
//
707
//        return indicator.getIsPublic();
708
//    }
709

    
710
    @PreAuthorize("isAuthenticated()")
711
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/change-visibility", method = RequestMethod.POST)
712
    public Visibility changeTopicVisibility(@PathVariable("stakeholderId") String stakeholderId,
713
                                            @PathVariable("topicId") String topicId,
714
                                            @PathVariable("categoryId") String categoryId,
715
                                            @PathVariable("subcategoryId") String subcategoryId,
716
                                            @PathVariable("sectionId") String sectionId,
717
                                         @PathVariable("indicatorId") String indicatorId,
718
                                            @RequestParam("visibility") Visibility visibility) {
719
        log.debug("change indicator visibility: "+visibility);
720
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
721

    
722
        Indicator indicator = indicatorDAO.findById(indicatorId);
723
        if (indicator == null) {
724
            // EXCEPTION - Indicator not found
725
            throw new EntityNotFoundException("Change indicator visibility: Indicator with id: "+indicatorId+" not found");
726
        }
727
        indicator.setVisibility(visibility);
728

    
729
        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
730

    
731
        return indicator.getVisibility();
732
    }
733

    
734
    public void toggleIndicator(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, Indicator indicator) {
735
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
736
        List<String> indicators = section.getIndicators();
737

    
738
        if(indicators.contains(indicator.getId())) {
739
            indicatorDAO.save(indicator);
740
            log.debug("Indicator toggled!");
741
        } else {
742
            // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subCategory.getAlias(); -> Section: section.getTitle();
743
            throw new PathNotValidException("Toggle indicators: Indicator with id: "+indicator.getId()+" not found in Section: "+sectionId);
744
        }
745

    
746
    }
747

    
748
    private Section checkForExceptions(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, String indicatorType) {
749

    
750
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
751

    
752
        if(stakeholder == null) {
753
            // EXCEPTION - Stakeholder not found
754
            throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
755
        }
756

    
757
        List<String> roles = rolesUtils.getRoles();
758
        if(!rolesUtils.hasUpdateAuthority(roles, stakeholder.getType(), stakeholder.getAlias())) {
759
            // EXCEPTION - Access denied
760
            throw new ForbiddenException("CheckForExceptions Indicator: You are not authorized to update stakeholder with id: "+stakeholderId);
761
        }
762

    
763
        Topic<String> topic = topicDAO.findById(topicId);
764
        if(topic == null) {
765
            // EXCEPTION - Topic not found
766
            throw new EntityNotFoundException("Save indicator: Topic with id: "+topicId+" not found");
767
        }
768

    
769
        if(!stakeholder.getTopics().contains(topicId)) {
770
            // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
771
            throw new PathNotValidException("Save indicator: Topic with id: " + topicId + " not found in Stakeholder: " + stakeholderId);
772
        }
773

    
774
        Category<String> category = categoryDAO.findById(categoryId);
775
        if(category == null) {
776
            // EXCEPTION - Category not found
777
            throw new EntityNotFoundException("Save indicator: Category with id: "+categoryId+" not found");
778
        }
779

    
780
        if(!topic.getCategories().contains(categoryId)) {
781
            // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
782
            throw new PathNotValidException("Save indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
783
        }
784

    
785
        SubCategory<String> subcategory = subCategoryDAO.findById(subcategoryId);
786
        if(subcategory == null) {
787
            // EXCEPTION - SubCategory not found
788
            throw new EntityNotFoundException("Save indicator: SubCategory with id: "+subcategoryId+" not found");
789
        }
790

    
791
        if (!category.getSubCategories().contains(subcategoryId)) {
792
            // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
793
            throw new PathNotValidException("Save indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
794
        }
795

    
796
        Section<String> section = sectionDAO.findById(sectionId);
797
        if(section == null) {
798
            // EXCEPTION - Section not found
799
            throw new EntityNotFoundException("Save indicator: Section with id: "+sectionId+" not found");
800
        }
801

    
802
        if(indicatorType.equals("chart")) {
803
            if (!subcategory.getCharts().contains(sectionId)) {
804
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
805
                throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
806
            }
807
        } else if(indicatorType.equals("number")) {
808
            if (!subcategory.getNumbers().contains(sectionId)) {
809
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
810
                throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
811
            }
812
        }
813

    
814
        return  section;
815
    }
816

    
817
    public void deleteTree(Section section) {
818
        List<String> indicators = section.getIndicators();
819
        for(String indicatorId : indicators) {
820
            indicatorDAO.delete(indicatorId);
821
        }
822
    }
823

    
824
    public void disConnectTree(Section section) {
825
        List<String> indicators = section.getIndicators();
826
        for(String indicatorId : indicators) {
827
            Indicator indicator = indicatorDAO.findById(indicatorId);
828
            indicator.setDefaultId(null);
829
            indicatorDAO.save(indicator);
830
        }
831
    }
832
}
(3-3/10)