Project

General

Profile

1
package eu.dnetlib.uoamonitorservice.controllers;
2

    
3

    
4
import eu.dnetlib.uoamonitorservice.dao.*;
5
import eu.dnetlib.uoamonitorservice.entities.*;
6
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
7
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
8
import org.apache.log4j.Logger;
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.web.bind.annotation.*;
11

    
12
import java.io.UnsupportedEncodingException;
13
import java.net.URLEncoder;
14
import java.util.*;
15

    
16
@RestController
17
@CrossOrigin(origins = "*")
18
public class IndicatorController {
19
    private final Logger log = Logger.getLogger(this.getClass());
20

    
21
    @Autowired
22
    private StakeholderDAO stakeholderDAO;
23

    
24
    @Autowired
25
    private TopicDAO topicDAO;
26

    
27
    @Autowired
28
    private CategoryDAO categoryDAO;
29

    
30
    @Autowired
31
    private SubCategoryDAO subCategoryDAO;
32

    
33
    @Autowired
34
    private SectionDAO sectionDAO;
35

    
36
    @Autowired
37
    private IndicatorDAO indicatorDAO;
38

    
39

    
40
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/save", method = RequestMethod.POST)
41
    public Indicator saveIndicator(@PathVariable("stakeholderId") String stakeholderId,
42
                                   @PathVariable("topicId") String topicId,
43
                                   @PathVariable("categoryId") String categoryId,
44
                                   @PathVariable("subcategoryId") String subcategoryId,
45
                                   @PathVariable("sectionId") String sectionId,
46
                                   @RequestBody Indicator indicator) throws UnsupportedEncodingException {
47
        log.debug("save indicator");
48
        log.debug("Name: "+indicator.getName() + " - Id: "+indicator.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
49

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

    
52
        Indicator oldIndicator = null;
53
        if(indicator.getId() != null) {
54
            oldIndicator = indicatorDAO.findById(indicator.getId());
55
        }
56

    
57
        String indicatorId = indicator.getId();
58
        indicatorDAO.save(indicator);
59

    
60
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
61
        // this indicator belongs in default profile and it is new or it is updated
62
        if(stakeholder.getDefaultId() == null) {
63
            if(indicatorId == null) {
64
                onSaveDefaultIndicator(indicator, sectionId);
65
            }
66
            else {
67
                onUpdateDefaultIndicator(indicator, stakeholder, oldIndicator);
68
            }
69
        }
70

    
71
        List<String> indicators = section.getIndicators();
72

    
73
        int index = indicators.indexOf(indicator.getId());
74
        if (index == -1) {
75
            indicators.add(indicator.getId());
76
            sectionDAO.save(section);
77
            log.debug("Indicator saved!");
78
        }
79

    
80
        return indicator;
81
    }
82

    
83
    public void onSaveDefaultIndicator(Indicator indicator, String defaultSectionId) throws UnsupportedEncodingException {
84
        log.debug("On save default indicator");
85

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

    
89
        for (Section section : sections) {
90
            Indicator indicatorNew = new Indicator();
91
            indicatorNew.copyFromDefault(indicator);
92
            for (IndicatorPath indicatorPath : indicatorNew.getIndicatorPaths()) {
93
                Stakeholder stakeholder = stakeholderDAO.findByAlias(section.getStakeholderAlias());
94
                parameterMapping(indicatorPath, stakeholder);
95
            }
96

    
97
            indicatorDAO.save(indicatorNew);
98

    
99
            List<String> indicators = section.getIndicators();
100
            indicators.add(indicatorNew.getId());
101

    
102
            sectionDAO.save(section);
103
        }
104
    }
105

    
106
    public void onUpdateDefaultIndicator(Indicator indicator, Stakeholder stakeholder, Indicator oldIndicator) throws UnsupportedEncodingException {
107
        log.debug("On update default indicator");
108

    
109
        // indicator already exists - check if changed and update all indicators based on it
110

    
111
        boolean changed = false;
112
        List<Indicator> indicators = indicatorDAO.findByDefaultId(indicator.getId());
113

    
114
        for(Indicator indicatorBasedOnDefault : indicators) {
115
            if(indicator.getName() != null && !indicator.getName().equals(indicatorBasedOnDefault.getName())
116
                    && (oldIndicator.getName() == null || oldIndicator.getName().equals(indicatorBasedOnDefault.getName()))) {
117

    
118
                indicatorBasedOnDefault.setName(indicator.getName());
119
                changed = true;
120
            }
121

    
122
            if(indicator.getDescription() != null && !indicator.getDescription().equals(indicatorBasedOnDefault.getDescription())
123
                    && (oldIndicator.getDescription() == null || oldIndicator.getDescription().equals(indicatorBasedOnDefault.getDescription()))) {
124

    
125
                indicatorBasedOnDefault.setName(indicator.getName());
126
                changed = true;
127
            }
128

    
129
            int i = 0;
130
            List<IndicatorPath> indicatorPaths = indicatorBasedOnDefault.getIndicatorPaths();
131

    
132
            for (IndicatorPath indicatorPath : indicator.getIndicatorPaths()) {
133
                IndicatorPath indicatorPathBasedOnDefault = indicatorBasedOnDefault.getIndicatorPaths().get(i);
134

    
135
                if(indicatorPathBasedOnDefault == null) {
136
                    // Add new indicator path in existing indicators
137
                    IndicatorPath indicatorPathNew = new IndicatorPath(indicatorPath);
138
                    parameterMapping(indicatorPathNew, stakeholder);
139
                    indicatorPaths.add(indicatorPathNew);
140
                    changed = true;
141
                } else {
142
                    IndicatorPath oldIndicatorPath = oldIndicator.getIndicatorPaths().get(i);
143

    
144
                    // Check if there are changes in indicator path and update existing indicators if needed
145
                    log.debug("update indicator path: "+i);
146

    
147
                    if(indicatorPath.getType() != null
148
                            && !indicatorPath.getType().equals(indicatorPathBasedOnDefault.getType())
149
                            && (oldIndicatorPath.getType().equals(indicatorPathBasedOnDefault.getType()))) {
150

    
151
                        indicatorPathBasedOnDefault.setType(indicatorPath.getType());
152
                        changed = true; // parameter "type" needs to be changed as well
153
                    }
154
                    log.debug("After type check: "+changed);
155

    
156
                    if(indicatorPath.getSource() != null
157
                            && !indicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource())
158
                            && (oldIndicatorPath.getSource().equals(indicatorPathBasedOnDefault.getSource()))) {
159

    
160
                        indicatorPathBasedOnDefault.setSource(indicatorPath.getSource());
161
                        changed = true;
162
                    }
163
                    log.debug("After source check: "+changed);
164

    
165
                    if(indicatorPath.getUrl() != null
166
                            && !indicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl())
167
                            && (oldIndicatorPath.getUrl().equals(indicatorPathBasedOnDefault.getUrl()))) {
168

    
169
                        indicatorPathBasedOnDefault.setUrl(indicatorPath.getUrl());
170
                        changed = true;
171
                    }
172
                    log.debug("After url check: "+changed);
173

    
174
                    if(indicatorPath.getChartObject() != null
175
                            && !indicatorPath.getChartObject().equals(indicatorPathBasedOnDefault.getChartObject())
176
                            && (oldIndicatorPath.getChartObject().equals(indicatorPathBasedOnDefault.getChartObject()))) {
177

    
178
                        indicatorPathBasedOnDefault.setChartObject(indicatorPath.getChartObject());
179
                        changed = true;
180
                    }
181
                    log.debug("After chartObject check: "+changed);
182

    
183
                    if(indicatorPath.getParameters() != null) {
184
                        if (indicatorPathBasedOnDefault.getParameters() == null) {
185
                            indicatorPathBasedOnDefault.setParameters(new HashMap<>());
186
                        }
187
                        //if (indicatorPath.getParameters().size() != indicatorPathBasedOnDefault.getParameters().size()) {
188
                            //log.debug("Different number of parameters");
189
                            for (Map.Entry<String, String> parameter : indicatorPath.getParameters().entrySet()) {
190
                                log.debug("\nindicatorPath: parameter.getKey(): "+parameter.getKey()+" - value: "+parameter.getValue()
191
                                        +"\nindicatorPathBasedOnDefault:parameters:key: "+  indicatorPathBasedOnDefault.getParameters().get(parameter.getKey())
192
                                        +"\noldIndicatorPath:parameters:key: "+  oldIndicatorPath.getParameters().get(parameter.getKey()));
193
                                if (!indicatorPathBasedOnDefault.getParameters().containsKey(parameter.getKey())
194
                                        || (oldIndicatorPath.getParameters() == null
195
                                            || (oldIndicatorPath.getParameters().get(parameter.getKey()).equals(indicatorPathBasedOnDefault.getParameters().get(parameter.getKey()))
196
                                                && !parameter.getValue().equals(indicatorPathBasedOnDefault.getParameters().get(parameter.getKey()))))
197
                                ) {
198
                                    indicatorPathBasedOnDefault.getParameters().put(parameter.getKey(), parameter.getValue());
199
                                    changed = true;
200
                                }
201
//                                else if(parameter.getKey().equals("type")) {
202
//                                    indicatorPathBasedOnDefault.getParameters().put(parameter.getKey(), parameter.getValue());
203
//                                    changed = true;
204
//                                }
205
                            }
206
                            parameterMapping(indicatorPathBasedOnDefault, stakeholder);
207
                        //}
208
                        log.debug("After parameters check: " + changed);
209
                    }
210

    
211
                    if(indicatorPath.getJsonPath() != null) {
212
                        int j = 0;
213
                        for (String jsonString : indicatorPath.getJsonPath()) {
214
                            log.debug("indicatorPath.getJsonPath(): " + jsonString);
215
                            String jsonStringBasedOnDefault = null;
216
                            if(indicatorPathBasedOnDefault.getJsonPath() != null ) {
217
                                jsonStringBasedOnDefault = indicatorPathBasedOnDefault.getJsonPath().get(j);
218
                            } else {
219
                                indicatorPathBasedOnDefault.setJsonPath(new ArrayList<>());
220
                            }
221
                            log.debug("indicatorPathBasedOnDefault.getJsonPath().get(" + j + "): " + jsonStringBasedOnDefault);
222

    
223
                            if (!jsonString.equals(jsonStringBasedOnDefault)
224
                                    && (oldIndicatorPath.getJsonPath() == null
225
                                    || oldIndicatorPath.getJsonPath().get(i).equals(jsonStringBasedOnDefault))
226
                            ) {
227
                                indicatorPathBasedOnDefault.getJsonPath().set(j, jsonString);
228
                                changed = true;
229
                            }
230
                            j++;
231
                        }
232
                        log.debug("After jsonPath check: " + changed);
233
                    }
234
                }
235
                i++;
236
            }
237

    
238
            if(!changed) {
239
//                break;
240
                continue;
241
            }
242

    
243
            indicatorDAO.save(indicatorBasedOnDefault);
244
        }
245
    }
246

    
247
    public void parameterMapping(IndicatorPath indicatorPath, Stakeholder stakeholder) throws UnsupportedEncodingException {
248
        if (indicatorPath.getParameters() != null) {
249
            if (indicatorPath.getParameters().containsKey("index_name")) {
250
                indicatorPath.getParameters().put("index_name", stakeholder.getIndex_name());
251
            } else if (indicatorPath.getParameters().containsKey("index_shortName")) {
252
                indicatorPath.getParameters().put("index_shortName", stakeholder.getIndex_name().toLowerCase());
253
            } else if (indicatorPath.getParameters().containsKey("index_id")) {
254
                indicatorPath.getParameters().put("index_id", stakeholder.getIndex_id());
255
            }
256
        }
257

    
258
//        // url encoding for number indicators
259
//        String url = indicatorPath.getUrl();
260
//        String encoded_index_id = urlEncode(URLEncoder.encode(stakeholder.getIndex_id(), "UTF-8"));
261
//        url = url.replace("index_id", encoded_index_id);
262
//        String encoded_index_name = urlEncode(URLEncoder.encode(stakeholder.getIndex_name(), "UTF-8"));
263
//        url = url.replace("index_name", encoded_index_name);
264
//        String encoded_index_shortName = urlEncode(URLEncoder.encode(stakeholder.getIndex_shortName(), "UTF-8"));
265
//        url = url.replace("index_shortName", encoded_index_shortName);
266
//        indicatorPath.setUrl(url);
267
    }
268

    
269
    public String urlEncode(String encodedIndicatorPathField) {
270
        String indicatorPathField = "";
271

    
272
        for( int i=0; i<encodedIndicatorPathField.length(); i++ ){
273
            String character = encodedIndicatorPathField.substring(i, i+1);
274

    
275
            if(character.equals("+")) {
276
                indicatorPathField = indicatorPathField.concat("%20");
277
            } else if(character.equals("%")) {
278
                //grab the hex in pairs
279
                String output = encodedIndicatorPathField.substring(i+1, (i + 3));
280

    
281
                if(output.equals("7E") || output.equals("27") || output.equals("28") || output.equals("29") || output.equals("21")) {
282
                    //convert hex to decimal
283
                    int decimal = Integer.parseInt(output, 16);
284
                    //convert the decimal to character
285
                    StringBuilder sb = new StringBuilder();
286
                    sb.append((char) decimal);
287

    
288
                    indicatorPathField = indicatorPathField.concat(sb.toString());
289
                } else {
290
                    indicatorPathField = indicatorPathField.concat(character + output);
291
                }
292

    
293
                i += 2;
294
            } else {
295
                indicatorPathField = indicatorPathField.concat(character);
296
            }
297
        }
298

    
299
        return indicatorPathField;
300
    }
301

    
302
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/delete", method = RequestMethod.DELETE)
303
    public boolean deleteIndicator(@PathVariable("stakeholderId") String stakeholderId,
304
                                   @PathVariable("topicId") String topicId,
305
                                   @PathVariable("categoryId") String categoryId,
306
                                   @PathVariable("subcategoryId") String subcategoryId,
307
                                   @PathVariable("sectionId") String sectionId,
308
                                   @PathVariable("indicatorId") String indicatorId,
309
                                   @RequestParam(required = false) String children) {
310
        log.debug("delete indicator");
311
        log.debug("Id: "+indicatorId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
312

    
313
        Indicator indicator = indicatorDAO.findById(indicatorId);
314
        if(indicator != null) {
315
            Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
316

    
317
            List<String> indicators = section.getIndicators();
318

    
319
            int index = indicators.indexOf(indicatorId);
320
            if (index != -1) {
321

    
322
                // this indicator belongs in default profile
323
                if(section.getDefaultId() == null && children != null) {
324
                    onDeleteDefaultIndicator(indicatorId, sectionId, children);
325
                }
326

    
327

    
328
                indicators.remove(index);
329
                sectionDAO.save(section);
330

    
331
                indicatorDAO.delete(indicatorId);
332
                log.debug("Indicator deleted!");
333
            } else {
334
                // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
335
                throw new PathNotValidException("Delete indicator: Indicator with id: "+indicatorId+" not found in Sectiom: "+sectionId);
336
            }
337
        } else {
338
            // EXCEPTION - Indicator not found
339
            throw new EntityNotFoundException("Delete indicator: Indicator with id: "+indicatorId+" not found");
340
        }
341
        return true;
342
    }
343

    
344
    public boolean onDeleteDefaultIndicator(String defaultIndicatorId, String defaultSectionId, String children) {
345
        if(children.equals("delete")) {
346
//            // 1st way
347
//            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
348
//
349
//            for(Section section : sections) {
350
//                List<String> indicators = section.getIndicators();
351
//
352
//                Iterator<String> indicatorsIterator = indicators.iterator();
353
//                while(indicatorsIterator.hasNext()) {
354
//                    String indicatorId = indicatorsIterator.next();
355
//
356
//                    Indicator indicator = indicatorDAO.findById(indicatorId);
357
//                    if (indicator.getDefaultId().equals(defaultIndicatorId)) {
358
//                        indicatorsIterator.remove();
359
//                        sectionDAO.save(section);
360
//
361
//                        indicatorDAO.delete(indicatorId);
362
//                        log.debug("Indicator deleted!");
363
//
364
//                        break;
365
//                    }
366
//                }
367
//            }
368

    
369
            // 2nd way
370
            List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
371
            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
372

    
373
            for(Section section : sections) {
374
                Iterator<Indicator> indicatorsIterator = indicators.iterator();
375
                while(indicatorsIterator.hasNext()) {
376
                    String indicatorId = indicatorsIterator.next().getId();
377
                    if(section.getIndicators().contains(indicatorId)) {
378
                        indicatorsIterator.remove();
379

    
380
                        section.getIndicators().remove(indicatorId);
381
                        sectionDAO.save(section);
382

    
383
                        indicatorDAO.delete(indicatorId);
384
                        log.debug("Indicator with id: "+indicatorId+" deleted!");
385

    
386
                        break;
387
                    }
388
                }
389
            }
390

    
391
//            // 3rd way - parentId
392
//            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
393
//            for(Indicator indicator : indicators) {
394
//                Section section = sectionDAO.findById(indicator.getParent());
395
//                List<String> sectionIndicators = section.getIndicators();
396
//
397
//                sectionIndicators.remove(indicator.getId());
398
//                sectionDAO.save(section);
399
//
400
//                indicatorDAO.delete(indicator.getId());
401
//                log.debug("Indicator deleted!");
402
//            }
403
        } else if(children.equals("disconnect")) {
404
            List<Indicator> indicators = indicatorDAO.findByDefaultId(defaultIndicatorId);
405
            for(Indicator indicator : indicators) {
406
                indicator.setDefaultId(null);
407
                indicatorDAO.save(indicator);
408
                log.debug("DefaultId for Indicator with id: "+indicator.getId()+" empty!");
409
            }
410
        }
411
        return true;
412
    }
413

    
414
//    @RequestMapping(value = "/{stakeholderId}/charts/delete", method = RequestMethod.DELETE)
415
//    public boolean deleteAllChartIndicators(@PathVariable("stakeholderId") String stakeholderId) {
416
//        log.debug("delete all chart indicators of stakeholder");
417
//        log.debug("Stakeholder: "+stakeholderId);
418
//
419
//        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
420
//        if(stakeholder != null) {
421
//
422
//            for(String topicId : stakeholder.getTopics()) {
423
//                Topic<String> topic = topicDAO.findById(topicId);
424
//                if(topic != null) {
425
//                    for(String categoryId : topic.getCategories()) {
426
//                        Category<String> category = categoryDAO.findById(categoryId);
427
//                        if(category != null) {
428
//                            for(String subcategoryId : category.getSubCategories()) {
429
//                                SubCategory<String> subcategory = subCategoryDAO.findById(subcategoryId);
430
//                                if(subcategory != null) {
431
//
432
//                                    for(String sectionId : subcategory.getCharts()) {
433
//                                        Section<String> section = sectionDAO.findById(sectionId);
434
//                                        if (section != null) {
435
//
436
//                                            List<String> indicators = section.getIndicators();
437
//                                            Iterator<String> indicatorsIterator = section.getIndicators().iterator();
438
//
439
//                                            while (indicatorsIterator.hasNext()) {
440
//                                                String indicatorId = indicatorsIterator.next();
441
//                                                Indicator indicator = indicatorDAO.findById(indicatorId);
442
//                                                if (indicator != null) {
443
//                                                    int index = indicators.indexOf(indicatorId);
444
//                                                    if (index != -1) {
445
//                                                        indicatorsIterator.remove();
446
//                                                        //indicators.remove(index);
447
//
448
//                                                        indicatorDAO.delete(indicatorId);
449
//                                                        log.debug("Indicator deleted!");
450
//                                                    } else {
451
//                                                        // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias(); -> Section: section.getTitle();
452
//                                                        throw new PathNotValidException("Delete indicator: Indicator with id: " + indicatorId + " not found in Section: " + sectionId);
453
//                                                    }
454
//                                                } else {
455
//                                                    // EXCEPTION - Indicator not found
456
//                                                    throw new EntityNotFoundException("Delete indicator: Indicator with id: " + indicatorId + " not found");
457
//                                                }
458
//                                            }
459
//                                            sectionDAO.save(section);
460
//                                        } else {
461
//                                            // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
462
//                                            throw new PathNotValidException("Delete indicator: Section with id: " + sectionId + " not found in SubCategory: " + subcategoryId);
463
//                                        }
464
//                                    }
465
//                                } else {
466
//                                    // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
467
//                                    throw new PathNotValidException("Delete indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
468
//                                }
469
//                            }
470
//                        } else {
471
//                            // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
472
//                            throw new PathNotValidException("Delete indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
473
//                        }
474
//                    }
475
//                } else {
476
//                    // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
477
//                    throw new PathNotValidException("Delete indicator: Topic with id: "+topicId+" not found in Stakeholder: "+stakeholderId);
478
//                }
479
//            }
480
//        } else {
481
//            // EXCEPTION - Stakeholder not found
482
//            throw new EntityNotFoundException("Delete indicator: Stakeholder with id: "+stakeholderId+" not found");
483
//        }
484
//        return true;
485
//    }
486

    
487
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{type}/reorder", method = RequestMethod.POST)
488
    public List<Indicator> reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
489
                                             @PathVariable("topicId") String topicId,
490
                                             @PathVariable("categoryId") String categoryId,
491
                                             @PathVariable("subcategoryId") String subcategoryId,
492
                                             @PathVariable("sectionId") String sectionId,
493
                                             @PathVariable("type") String type,
494
                                             @RequestBody List<String> indicators) {
495
        log.debug("reorder indicators of type: "+type);
496
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
497

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

    
500
        section.setIndicators(indicators);
501

    
502
        sectionDAO.save(section);
503
        log.debug("Indicators reordered!");
504

    
505
        List<Indicator> indicatorsFull = new ArrayList<>();
506
        for(String indicatorId : indicators) {
507
            indicatorsFull.add(indicatorDAO.findById(indicatorId));
508
        }
509
        return indicatorsFull;
510
    }
511

    
512
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/toggle-status", method = RequestMethod.POST)
513
    public Boolean toggleIndicatorStatus(@PathVariable("stakeholderId") String stakeholderId,
514
                                         @PathVariable("topicId") String topicId,
515
                                         @PathVariable("categoryId") String categoryId,
516
                                         @PathVariable("subcategoryId") String subcategoryId,
517
                                         @PathVariable("sectionId") String sectionId,
518
                                         @PathVariable("indicatorId") String indicatorId) {
519
        log.debug("toggle indicator status (isActive)");
520
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
521

    
522
        Indicator indicator = indicatorDAO.findById(indicatorId);
523
        if (indicator == null) {
524
            // EXCEPTION - Indicator not found
525
            throw new EntityNotFoundException("Toggle indicator status: Indicator with id: "+indicatorId+" not found");
526
        }
527
        indicator.setIsActive(!indicator.getIsActive());
528

    
529
        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
530

    
531
        return indicator.getIsActive();
532
    }
533

    
534
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/toggle-access", method = RequestMethod.POST)
535
    public Boolean toggleIndicatorAccess(@PathVariable("stakeholderId") String stakeholderId,
536
                                         @PathVariable("topicId") String topicId,
537
                                         @PathVariable("categoryId") String categoryId,
538
                                         @PathVariable("subcategoryId") String subcategoryId,
539
                                         @PathVariable("sectionId") String sectionId,
540
                                         @PathVariable("indicatorId") String indicatorId) {
541
        log.debug("toggle indicator access (isPublic)");
542
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
543

    
544
        Indicator indicator = indicatorDAO.findById(indicatorId);
545
        if (indicator == null) {
546
            // EXCEPTION - Indicator not found
547
            throw new EntityNotFoundException("Toggle indicator access: Indicator with id: "+indicatorId+" not found");
548
        }
549
        indicator.setIsPublic(!indicator.getIsPublic());
550

    
551
        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
552

    
553
        return indicator.getIsPublic();
554
    }
555

    
556
    public void toggleIndicator(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, Indicator indicator) {
557
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
558
        List<String> indicators = section.getIndicators();
559

    
560
        if(indicators.contains(indicator.getId())) {
561
            indicatorDAO.save(indicator);
562
            log.debug("Indicator toggled!");
563
        } else {
564
            // EXCEPTION - Indicator not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subCategory.getAlias(); -> Section: section.getTitle();
565
            throw new PathNotValidException("Toggle indicators: Indicator with id: "+indicator.getId()+" not found in Section: "+sectionId);
566
        }
567

    
568
    }
569

    
570
    private Section checkForExceptions(String stakeholderId, String topicId, String categoryId, String subcategoryId, String sectionId, String indicatorType) {
571

    
572
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
573

    
574
        if(stakeholder == null) {
575
            // EXCEPTION - Stakeholder not found
576
            throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
577
        }
578

    
579
        Topic<String> topic = topicDAO.findById(topicId);
580
        if(topic == null) {
581
            // EXCEPTION - Topic not found
582
            throw new EntityNotFoundException("Save indicator: Topic with id: "+topicId+" not found");
583
        }
584

    
585
        if(!stakeholder.getTopics().contains(topicId)) {
586
            // EXCEPTION - Topic not found in Stakeholder: stakeholder.getAlias();
587
            throw new PathNotValidException("Save indicator: Topic with id: " + topicId + " not found in Stakeholder: " + stakeholderId);
588
        }
589

    
590
        Category<String> category = categoryDAO.findById(categoryId);
591
        if(category == null) {
592
            // EXCEPTION - Category not found
593
            throw new EntityNotFoundException("Save indicator: Category with id: "+categoryId+" not found");
594
        }
595

    
596
        if(!topic.getCategories().contains(categoryId)) {
597
            // EXCEPTION - Category not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias();
598
            throw new PathNotValidException("Save indicator: Category with id: "+categoryId+" not found in Topic: "+topicId);
599
        }
600

    
601
        SubCategory<String> subcategory = subCategoryDAO.findById(subcategoryId);
602
        if(subcategory == null) {
603
            // EXCEPTION - SubCategory not found
604
            throw new EntityNotFoundException("Save indicator: SubCategory with id: "+subcategoryId+" not found");
605
        }
606

    
607
        if (!category.getSubCategories().contains(subcategoryId)) {
608
            // EXCEPTION - SubCategory not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias();
609
            throw new PathNotValidException("Save indicator: SubCategory with id: "+subcategoryId+" not found in Category: "+categoryId);
610
        }
611

    
612
        Section<String> section = sectionDAO.findById(sectionId);
613
        if(section == null) {
614
            // EXCEPTION - Section not found
615
            throw new EntityNotFoundException("Save indicator: Section with id: "+sectionId+" not found");
616
        }
617

    
618
        if(indicatorType.equals("chart")) {
619
            if (!subcategory.getCharts().contains(sectionId)) {
620
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
621
                throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
622
            }
623
        } else if(indicatorType.equals("number")) {
624
            if (!subcategory.getNumbers().contains(sectionId)) {
625
                // EXCEPTION - Section not found in Stakeholder: stakeholder.getAlias(); -> Topic: topic.getAlias(); -> Category: category.getAlias(); -> SubCategory: subcategory.getAlias();
626
                throw new PathNotValidException("Save indicator: SubCategory with id: " + subcategoryId + " not found in Category: " + categoryId);
627
            }
628
        }
629

    
630
        return  section;
631
    }
632

    
633
    public void deleteTree(Section section) {
634
        List<String> indicators = section.getIndicators();
635
        for(String indicatorId : indicators) {
636
            indicatorDAO.delete(indicatorId);
637
        }
638
    }
639

    
640
    public void disConnectTree(Section section) {
641
        List<String> indicators = section.getIndicators();
642
        for(String indicatorId : indicators) {
643
            Indicator indicator = indicatorDAO.findById(indicatorId);
644
            indicator.setDefaultId(null);
645
            indicatorDAO.save(indicator);
646
        }
647
    }
648
}
(3-3/8)