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
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
                            // TODO when deleting indicator path parameters... ???
289
                        parameterMapping(indicatorPathBasedOnDefault, stakeholder);
290
                        //}
291
                    }
292
                    log.debug("After parameters check: " + changed);
293

    
294
                    if(indicatorPath.getJsonPath() != null) {
295
                        boolean jsonPathChanged = false;
296
                        boolean breaked = false;
297

    
298
                        int oldJsonPathSize = 0;
299
                        if(oldIndicatorPath.getJsonPath() != null) {
300
                            oldJsonPathSize = oldIndicatorPath.getJsonPath().size();
301
                        }
302
                        int basedOnDefaultJsonPathSize = 0;
303
                        if(indicatorPathBasedOnDefault.getJsonPath() != null) {
304
                            basedOnDefaultJsonPathSize = indicatorPathBasedOnDefault.getJsonPath().size();
305
                        }
306
                        log.debug("old: "+oldJsonPathSize+" - based on default: "+basedOnDefaultJsonPathSize+" - new: "+indicatorPath.getJsonPath().size());
307
                        if(oldJsonPathSize == basedOnDefaultJsonPathSize) {
308
                            if(indicatorPathBasedOnDefault.getJsonPath() == null && indicatorPath.getJsonPath().size() > 0) {
309
                                indicatorPathBasedOnDefault.setJsonPath(new ArrayList<>());
310
                            }
311

    
312
                            int basedOnDefaultIndex = 0;
313
                            int oldIndex = 0;
314

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

    
338
                            int index=0;
339
                            if(!breaked && indicatorPath.getJsonPath().size() > indicatorPathBasedOnDefault.getJsonPath().size()) { // strings added
340
                                jsonPathChanged = true;
341
                                for(index=indicatorPathBasedOnDefault.getJsonPath().size(); index < indicatorPath.getJsonPath().size(); index++) {
342
                                    indicatorPathBasedOnDefault.getJsonPath().add(indicatorPath.getJsonPath().get(index));
343
                                }
344
                            }
345

    
346
                            if(jsonPathChanged) {
347
                                changed = true;
348
                            }
349
                        }
350
                        // TODO when deleting indicator path json path strings...
351
                    }
352
                    log.debug("After jsonPath check: " + changed);
353
                }
354
                i++;
355
            }
356
            // TODO when deleting indicator paths...
357

    
358
            if(!changed) {
359
//                break;
360
                continue;
361
            }
362

    
363
            indicatorBasedOnDefault.setUpdateDate(indicator.getUpdateDate());
364
            indicatorDAO.save(indicatorBasedOnDefault);
365
        }
366
    }
367

    
368
    public void parameterMapping(IndicatorPath indicatorPath, Stakeholder stakeholder) throws UnsupportedEncodingException {
369
        if (indicatorPath.getParameters() != null) {
370
            if (indicatorPath.getParameters().containsKey("index_name")) {
371
                indicatorPath.getParameters().put("index_name", stakeholder.getIndex_name());
372
            } else if (indicatorPath.getParameters().containsKey("index_shortName")) {
373
                indicatorPath.getParameters().put("index_shortName", stakeholder.getIndex_name().toLowerCase());
374
            } else if (indicatorPath.getParameters().containsKey("index_id")) {
375
                indicatorPath.getParameters().put("index_id", stakeholder.getIndex_id());
376
            }
377
        }
378

    
379
//        // url encoding for number indicators
380
//        String url = indicatorPath.getUrl();
381
//        String encoded_index_id = urlEncode(URLEncoder.encode(stakeholder.getIndex_id(), "UTF-8"));
382
//        url = url.replace("index_id", encoded_index_id);
383
//        String encoded_index_name = urlEncode(URLEncoder.encode(stakeholder.getIndex_name(), "UTF-8"));
384
//        url = url.replace("index_name", encoded_index_name);
385
//        String encoded_index_shortName = urlEncode(URLEncoder.encode(stakeholder.getIndex_shortName(), "UTF-8"));
386
//        url = url.replace("index_shortName", encoded_index_shortName);
387
//        indicatorPath.setUrl(url);
388
    }
389

    
390
    public String urlEncode(String encodedIndicatorPathField) {
391
        String indicatorPathField = "";
392

    
393
        for( int i=0; i<encodedIndicatorPathField.length(); i++ ){
394
            String character = encodedIndicatorPathField.substring(i, i+1);
395

    
396
            if(character.equals("+")) {
397
                indicatorPathField = indicatorPathField.concat("%20");
398
            } else if(character.equals("%")) {
399
                //grab the hex in pairs
400
                String output = encodedIndicatorPathField.substring(i+1, (i + 3));
401

    
402
                if(output.equals("7E") || output.equals("27") || output.equals("28") || output.equals("29") || output.equals("21")) {
403
                    //convert hex to decimal
404
                    int decimal = Integer.parseInt(output, 16);
405
                    //convert the decimal to character
406
                    StringBuilder sb = new StringBuilder();
407
                    sb.append((char) decimal);
408

    
409
                    indicatorPathField = indicatorPathField.concat(sb.toString());
410
                } else {
411
                    indicatorPathField = indicatorPathField.concat(character + output);
412
                }
413

    
414
                i += 2;
415
            } else {
416
                indicatorPathField = indicatorPathField.concat(character);
417
            }
418
        }
419

    
420
        return indicatorPathField;
421
    }
422

    
423
    @PreAuthorize("isAuthenticated()")
424
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/delete", method = RequestMethod.DELETE)
425
    public boolean deleteIndicator(@PathVariable("stakeholderId") String stakeholderId,
426
                                   @PathVariable("topicId") String topicId,
427
                                   @PathVariable("categoryId") String categoryId,
428
                                   @PathVariable("subcategoryId") String subcategoryId,
429
                                   @PathVariable("sectionId") String sectionId,
430
                                   @PathVariable("indicatorId") String indicatorId,
431
                                   @RequestParam(required = false) String children) {
432
        log.debug("delete indicator");
433
        log.debug("Id: "+indicatorId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
434

    
435
        Indicator indicator = indicatorDAO.findById(indicatorId);
436
        if(indicator != null) {
437
            Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
438

    
439
            Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
440
            List<String> roles = rolesUtils.getRoles();
441
            if(indicator.getDefaultId() != null && !rolesUtils.hasCreateAndDeleteAuthority(roles, stakeholder.getType())) {
442
                // EXCEPTION - Access denied
443
                throw new ForbiddenException("Delete indicator: You are not authorized to delete a default Indicator in stakeholder with id: "+stakeholderId);
444
            }
445

    
446
            List<String> indicators = section.getIndicators();
447

    
448
            int index = indicators.indexOf(indicatorId);
449
            if (index != -1) {
450

    
451
                // this indicator belongs in default profile
452
                if(section.getDefaultId() == null && children != null) {
453
                    onDeleteDefaultIndicator(indicatorId, sectionId, children);
454
                }
455

    
456

    
457
                indicators.remove(index);
458
                sectionDAO.save(section);
459

    
460
                indicatorDAO.delete(indicatorId);
461
                log.debug("Indicator deleted!");
462
            } else {
463
                // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
464
                throw new PathNotValidException("Delete indicator: Indicator with id: "+indicatorId+" not found in Sectiom: "+sectionId);
465
            }
466
        } else {
467
            // EXCEPTION - Indicator not found
468
            throw new EntityNotFoundException("Delete indicator: Indicator with id: "+indicatorId+" not found");
469
        }
470
        return true;
471
    }
472

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

    
498
            // 2nd way
499
            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
500
            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
501

    
502
            for(Section section : sections) {
503
                Iterator<Indicator> indicatorsIterator = indicators.iterator();
504
                while(indicatorsIterator.hasNext()) {
505
                    String indicatorId = indicatorsIterator.next().getId();
506
                    if(section.getIndicators().contains(indicatorId)) {
507
                        indicatorsIterator.remove();
508

    
509
                        section.getIndicators().remove(indicatorId);
510
                        sectionDAO.save(section);
511

    
512
                        indicatorDAO.delete(indicatorId);
513
                        log.debug("Indicator with id: "+indicatorId+" deleted!");
514

    
515
                        break;
516
                    }
517
                }
518
            }
519

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

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

    
616
    @PreAuthorize("isAuthenticated()")
617
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{type}/reorder", method = RequestMethod.POST)
618
    public List<Indicator> reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
619
                                             @PathVariable("topicId") String topicId,
620
                                             @PathVariable("categoryId") String categoryId,
621
                                             @PathVariable("subcategoryId") String subcategoryId,
622
                                             @PathVariable("sectionId") String sectionId,
623
                                             @PathVariable("type") String type,
624
                                             @RequestBody ReorderEvent reorderEvent) {
625
        log.debug("reorder indicators of type: "+type);
626
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
627

    
628
        List<String> indicators = reorderEvent.getIds();
629
        String actionType = reorderEvent.getAction();
630
        String targetId = reorderEvent.getTarget();
631

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

    
634
        List<String> oldIndicators = section.getIndicators();
635
        for (String indicatorId : oldIndicators) {
636
            if ((!actionType.equals("removed") || !targetId.equals(indicatorId)) && !indicators.contains(indicatorId)) {
637
                indicators.add(indicatorId);
638
            }
639
        }
640
        section.setIndicators(indicators);
641

    
642
        List<Indicator> indicatorsFull = new ArrayList<>();
643
        for(String indicatorId : indicators) {
644
            Indicator indicator = indicatorDAO.findById(indicatorId);
645
            if(indicator == null) {
646
                // EXCEPTION - Indicator not found
647
                throw new EntityNotFoundException("Reorder indicators: Indicator with id: " + indicatorId + " not found");
648
            }
649
            indicatorsFull.add(indicator);
650
        }
651

    
652
        sectionDAO.save(section);
653
        log.debug("Indicators reordered!");
654

    
655
        return indicatorsFull;
656
    }
657

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

    
702
    @PreAuthorize("isAuthenticated()")
703
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/change-visibility", method = RequestMethod.POST)
704
    public Visibility changeTopicVisibility(@PathVariable("stakeholderId") String stakeholderId,
705
                                            @PathVariable("topicId") String topicId,
706
                                            @PathVariable("categoryId") String categoryId,
707
                                            @PathVariable("subcategoryId") String subcategoryId,
708
                                            @PathVariable("sectionId") String sectionId,
709
                                         @PathVariable("indicatorId") String indicatorId,
710
                                            @RequestParam("visibility") Visibility visibility) {
711
        log.debug("change indicator visibility: "+visibility);
712
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
713

    
714
        Indicator indicator = indicatorDAO.findById(indicatorId);
715
        if (indicator == null) {
716
            // EXCEPTION - Indicator not found
717
            throw new EntityNotFoundException("Change indicator visibility: Indicator with id: "+indicatorId+" not found");
718
        }
719
        indicator.setVisibility(visibility);
720

    
721
        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
722

    
723
        return indicator.getVisibility();
724
    }
725

    
726
    public void toggleIndicator(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, Indicator indicator) {
727
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
728
        List<String> indicators = section.getIndicators();
729

    
730
        if(indicators.contains(indicator.getId())) {
731
            indicatorDAO.save(indicator);
732
            log.debug("Indicator toggled!");
733
        } else {
734
            // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subCategory.getAlias(); -> Section: section.getTitle();
735
            throw new PathNotValidException("Toggle indicators: Indicator with id: "+indicator.getId()+" not found in Section: "+sectionId);
736
        }
737

    
738
    }
739

    
740
    private Section checkForExceptions(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, String indicatorType) {
741

    
742
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
743

    
744
        if(stakeholder == null) {
745
            // EXCEPTION - Stakeholder not found
746
            throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
747
        }
748

    
749
        List<String> roles = rolesUtils.getRoles();
750
        if(!rolesUtils.hasUpdateAuthority(roles, stakeholder.getType(), stakeholder.getAlias())) {
751
            // EXCEPTION - Access denied
752
            throw new ForbiddenException("CheckForExceptions Indicator: You are not authorized to update stakeholder with id: "+stakeholderId);
753
        }
754

    
755
        Topic<String> topic = topicDAO.findById(topicId);
756
        if(topic == null) {
757
            // EXCEPTION - Topic not found
758
            throw new EntityNotFoundException("Save indicator: Topic with id: "+topicId+" not found");
759
        }
760

    
761
        if(!stakeholder.getTopics().contains(topicId)) {
762
            // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
763
            throw new PathNotValidException("Save indicator: Topic with id: " + topicId + " not found in Stakeholder: " + stakeholderId);
764
        }
765

    
766
        Category<String> category = categoryDAO.findById(categoryId);
767
        if(category == null) {
768
            // EXCEPTION - Category not found
769
            throw new EntityNotFoundException("Save indicator: Category with id: "+categoryId+" not found");
770
        }
771

    
772
        if(!topic.getCategories().contains(categoryId)) {
773
            // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
774
            throw new PathNotValidException("Save indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
775
        }
776

    
777
        SubCategory<String> subcategory = subCategoryDAO.findById(subcategoryId);
778
        if(subcategory == null) {
779
            // EXCEPTION - SubCategory not found
780
            throw new EntityNotFoundException("Save indicator: SubCategory with id: "+subcategoryId+" not found");
781
        }
782

    
783
        if (!category.getSubCategories().contains(subcategoryId)) {
784
            // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
785
            throw new PathNotValidException("Save indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
786
        }
787

    
788
        Section<String> section = sectionDAO.findById(sectionId);
789
        if(section == null) {
790
            // EXCEPTION - Section not found
791
            throw new EntityNotFoundException("Save indicator: Section with id: "+sectionId+" not found");
792
        }
793

    
794
        if(indicatorType.equals("chart")) {
795
            if (!subcategory.getCharts().contains(sectionId)) {
796
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
797
                throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
798
            }
799
        } else if(indicatorType.equals("number")) {
800
            if (!subcategory.getNumbers().contains(sectionId)) {
801
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
802
                throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
803
            }
804
        }
805

    
806
        return  section;
807
    }
808

    
809
    public void deleteTree(Section section) {
810
        List<String> indicators = section.getIndicators();
811
        for(String indicatorId : indicators) {
812
            indicatorDAO.delete(indicatorId);
813
        }
814
    }
815

    
816
    public void disConnectTree(Section section) {
817
        List<String> indicators = section.getIndicators();
818
        for(String indicatorId : indicators) {
819
            Indicator indicator = indicatorDAO.findById(indicatorId);
820
            indicator.setDefaultId(null);
821
            indicatorDAO.save(indicator);
822
        }
823
    }
824
}
(3-3/9)