Project

General

Profile

1 57671 konstantin
package eu.dnetlib.uoamonitorservice.controllers;
2
3
4 60490 konstantin
import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
5 57671 konstantin
import eu.dnetlib.uoamonitorservice.dao.*;
6
import eu.dnetlib.uoamonitorservice.entities.*;
7
import eu.dnetlib.uoamonitorservice.handlers.EntityNotFoundException;
8 60107 konstantin
import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException;
9 57671 konstantin
import eu.dnetlib.uoamonitorservice.handlers.PathNotValidException;
10
import org.apache.log4j.Logger;
11
import org.springframework.beans.factory.annotation.Autowired;
12 59814 konstantin
import org.springframework.security.access.AccessDeniedException;
13
import org.springframework.security.access.prepost.PreAuthorize;
14 57671 konstantin
import org.springframework.web.bind.annotation.*;
15
16 57987 konstantin
import java.io.UnsupportedEncodingException;
17 60107 konstantin
import java.lang.reflect.Field;
18 57987 konstantin
import java.net.URLEncoder;
19 58978 konstantin
import java.util.*;
20 57671 konstantin
21
@RestController
22
@CrossOrigin(origins = "*")
23
public class IndicatorController {
24
    private final Logger log = Logger.getLogger(this.getClass());
25
26
    @Autowired
27 59814 konstantin
    private RolesUtils rolesUtils;
28
29
    @Autowired
30 57671 konstantin
    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 57964 konstantin
    private SectionDAO sectionDAO;
43
44
    @Autowired
45 57671 konstantin
    private IndicatorDAO indicatorDAO;
46
47
48 59814 konstantin
    @PreAuthorize("isAuthenticated()")
49 57964 konstantin
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/save", method = RequestMethod.POST)
50 57671 konstantin
    public Indicator saveIndicator(@PathVariable("stakeholderId") String stakeholderId,
51
                                   @PathVariable("topicId") String topicId,
52
                                   @PathVariable("categoryId") String categoryId,
53
                                   @PathVariable("subcategoryId") String subcategoryId,
54 57964 konstantin
                                   @PathVariable("sectionId") String sectionId,
55 57987 konstantin
                                   @RequestBody Indicator indicator) throws UnsupportedEncodingException {
56 57671 konstantin
        log.debug("save indicator");
57 57964 konstantin
        log.debug("Name: "+indicator.getName() + " - Id: "+indicator.getId() + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
58 57671 konstantin
59 57964 konstantin
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
60 57671 konstantin
61 59814 konstantin
        Date date = new Date();
62
        indicator.setUpdateDate(date);
63
64 58708 konstantin
        Indicator oldIndicator = null;
65
        if(indicator.getId() != null) {
66
            oldIndicator = indicatorDAO.findById(indicator.getId());
67 60107 konstantin
            if(oldIndicator == null) {
68
                // EXCEPTION - Indicator not found
69
                throw new EntityNotFoundException("save indicator: Indicator with id: " + indicator.getId() + " not found");
70
            }
71 59814 konstantin
        } else { // indicator does not exist in DB
72
            indicator.setCreationDate(date);
73 58708 konstantin
        }
74
75 57964 konstantin
        String indicatorId = indicator.getId();
76
77 57671 konstantin
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
78 57964 konstantin
        // this indicator belongs in default profile and it is new or it is updated
79
        if(stakeholder.getDefaultId() == null) {
80
            if(indicatorId == null) {
81 59814 konstantin
                indicatorDAO.save(indicator);
82 57964 konstantin
                onSaveDefaultIndicator(indicator, sectionId);
83
            }
84
            else {
85 58708 konstantin
                onUpdateDefaultIndicator(indicator, stakeholder, oldIndicator);
86 59814 konstantin
                indicatorDAO.save(indicator);
87 57964 konstantin
            }
88 59814 konstantin
        } else {
89
            indicatorDAO.save(indicator);
90 57964 konstantin
        }
91 57671 konstantin
92 57964 konstantin
        List<String> indicators = section.getIndicators();
93 57671 konstantin
94 57964 konstantin
        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 57671 konstantin
101
        return indicator;
102
    }
103
104 57987 konstantin
    public void onSaveDefaultIndicator(Indicator indicator, String defaultSectionId) throws UnsupportedEncodingException {
105 57923 konstantin
        log.debug("On save default indicator");
106
107
        // new indicator in default profile - add it on profiles of the same type
108 57964 konstantin
        List<Section> sections = sectionDAO.findByDefaultId(defaultSectionId);
109 57923 konstantin
110 59814 konstantin
       for (Section section : sections) {
111 57923 konstantin
            Indicator indicatorNew = new Indicator();
112
            indicatorNew.copyFromDefault(indicator);
113
            for (IndicatorPath indicatorPath : indicatorNew.getIndicatorPaths()) {
114 57964 konstantin
                Stakeholder stakeholder = stakeholderDAO.findByAlias(section.getStakeholderAlias());
115 57923 konstantin
                parameterMapping(indicatorPath, stakeholder);
116
            }
117
118
            indicatorDAO.save(indicatorNew);
119
120 57964 konstantin
            List<String> indicators = section.getIndicators();
121 57923 konstantin
            indicators.add(indicatorNew.getId());
122
123 57964 konstantin
            sectionDAO.save(section);
124 57923 konstantin
        }
125
    }
126
127 58708 konstantin
    public void onUpdateDefaultIndicator(Indicator indicator, Stakeholder stakeholder, Indicator oldIndicator) throws UnsupportedEncodingException {
128 57923 konstantin
        log.debug("On update default indicator");
129
130
        // indicator already exists - check if changed and update all indicators based on it
131
132 59814 konstantin
        boolean changed;
133 57923 konstantin
        List<Indicator> indicators = indicatorDAO.findByDefaultId(indicator.getId());
134
135
        for(Indicator indicatorBasedOnDefault : indicators) {
136 59814 konstantin
            changed = false;
137
138 60175 konstantin
//            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 58708 konstantin
                indicatorBasedOnDefault.setName(indicator.getName());
150
                changed = true;
151
            }
152
153 60175 konstantin
            if(indicator.getDescription() != null && !indicator.getDescription().equals(indicatorBasedOnDefault.getDescription())
154
                || indicator.getDescription() == null && indicatorBasedOnDefault.getDescription() != null) {
155 58708 konstantin
156 58992 konstantin
                indicatorBasedOnDefault.setDescription(indicator.getDescription());
157 58708 konstantin
                changed = true;
158
            }
159
160 60175 konstantin
//            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 59814 konstantin
                indicatorBasedOnDefault.setAdditionalDescription(indicator.getAdditionalDescription());
172
                changed = true;
173
            }
174
175 57923 konstantin
            int i = 0;
176
            List<IndicatorPath> indicatorPaths = indicatorBasedOnDefault.getIndicatorPaths();
177 59814 konstantin
            if(indicatorPaths == null && indicator.getIndicatorPaths() != null) {
178
                indicatorPaths = new ArrayList<>();
179
            }
180 57923 konstantin
181
            for (IndicatorPath indicatorPath : indicator.getIndicatorPaths()) {
182 59814 konstantin
                IndicatorPath indicatorPathBasedOnDefault = null;
183
                if(i < indicatorPaths.size()) {
184
                    indicatorPathBasedOnDefault = indicatorPaths.get(i);
185
                }
186 57923 konstantin
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 58708 konstantin
                    IndicatorPath oldIndicatorPath = oldIndicator.getIndicatorPaths().get(i);
195
196 57923 konstantin
                    // Check if there are changes in indicator path and update existing indicators if needed
197 59814 konstantin
                    log.debug("update indicator path: "+i + " (indicator id: "+indicatorBasedOnDefault.getId()+")");
198 58954 konstantin
199 60175 konstantin
//                    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 57923 konstantin
                        indicatorPathBasedOnDefault.setType(indicatorPath.getType());
212 58708 konstantin
                        changed = true; // parameter "type" needs to be changed as well
213 57923 konstantin
                    }
214 58708 konstantin
                    log.debug("After type check: "+changed);
215
216 60175 konstantin
//                    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 57923 konstantin
                        indicatorPathBasedOnDefault.setSource(indicatorPath.getSource());
229
                        changed = true;
230
                    }
231 58708 konstantin
                    log.debug("After source check: "+changed);
232
233 60175 konstantin
//                    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 57923 konstantin
                        indicatorPathBasedOnDefault.setUrl(indicatorPath.getUrl());
246
                        changed = true;
247
                    }
248 58708 konstantin
                    log.debug("After url check: "+changed);
249
250 60175 konstantin
                    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 58708 konstantin
260 57923 konstantin
                        indicatorPathBasedOnDefault.setChartObject(indicatorPath.getChartObject());
261
                        changed = true;
262
                    }
263 58708 konstantin
                    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 60960 konstantin
                        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 58708 konstantin
                                }
295 57923 konstantin
                            }
296 60960 konstantin
                        }
297 59814 konstantin
                        parameterMapping(indicatorPathBasedOnDefault, stakeholder);
298 58708 konstantin
                        //}
299 57923 konstantin
                    }
300 59814 konstantin
                    log.debug("After parameters check: " + changed);
301 58708 konstantin
302
                    if(indicatorPath.getJsonPath() != null) {
303 59814 konstantin
                        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 58708 konstantin
                                indicatorPathBasedOnDefault.setJsonPath(new ArrayList<>());
318
                            }
319
320 59814 konstantin
                            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 58708 konstantin
                                changed = true;
356
                            }
357 57923 konstantin
                        }
358 60960 konstantin
                        // TODO when deleting indicator path json path strings... --> is this done? (line 327)
359 57923 konstantin
                    }
360 59814 konstantin
                    log.debug("After jsonPath check: " + changed);
361 57923 konstantin
                }
362
                i++;
363
            }
364 59814 konstantin
            // TODO when deleting indicator paths...
365 58708 konstantin
366 57923 konstantin
            if(!changed) {
367 58708 konstantin
//                break;
368
                continue;
369 57923 konstantin
            }
370 58708 konstantin
371 59814 konstantin
            indicatorBasedOnDefault.setUpdateDate(indicator.getUpdateDate());
372 57923 konstantin
            indicatorDAO.save(indicatorBasedOnDefault);
373
        }
374
    }
375
376 57987 konstantin
    public void parameterMapping(IndicatorPath indicatorPath, Stakeholder stakeholder) throws UnsupportedEncodingException {
377 58954 konstantin
        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 57923 konstantin
        }
386 57987 konstantin
387 58954 konstantin
//        // 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 57923 konstantin
    }
397
398 57987 konstantin
    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 59814 konstantin
    @PreAuthorize("isAuthenticated()")
432 57964 konstantin
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{indicatorId}/delete", method = RequestMethod.DELETE)
433 57671 konstantin
    public boolean deleteIndicator(@PathVariable("stakeholderId") String stakeholderId,
434
                                   @PathVariable("topicId") String topicId,
435
                                   @PathVariable("categoryId") String categoryId,
436
                                   @PathVariable("subcategoryId") String subcategoryId,
437 57964 konstantin
                                   @PathVariable("sectionId") String sectionId,
438 58978 konstantin
                                   @PathVariable("indicatorId") String indicatorId,
439
                                   @RequestParam(required = false) String children) {
440 57671 konstantin
        log.debug("delete indicator");
441 57964 konstantin
        log.debug("Id: "+indicatorId + " - Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
442 57671 konstantin
443 57964 konstantin
        Indicator indicator = indicatorDAO.findById(indicatorId);
444
        if(indicator != null) {
445
            Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator.getType());
446 57671 konstantin
447 59814 konstantin
            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 60107 konstantin
                throw new ForbiddenException("Delete indicator: You are not authorized to delete a default Indicator in stakeholder with id: "+stakeholderId);
452 59814 konstantin
            }
453
454 57964 konstantin
            List<String> indicators = section.getIndicators();
455 57671 konstantin
456 57964 konstantin
            int index = indicators.indexOf(indicatorId);
457
            if (index != -1) {
458 58978 konstantin
459
                // this indicator belongs in default profile
460
                if(section.getDefaultId() == null && children != null) {
461
                    onDeleteDefaultIndicator(indicatorId, sectionId, children);
462
                }
463
464
465 57964 konstantin
                indicators.remove(index);
466
                sectionDAO.save(section);
467 57671 konstantin
468 57964 konstantin
                indicatorDAO.delete(indicatorId);
469
                log.debug("Indicator deleted!");
470 57671 konstantin
            } else {
471 57964 konstantin
                // 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 57671 konstantin
            }
474
        } else {
475 57964 konstantin
            // EXCEPTION - Indicator not found
476
            throw new EntityNotFoundException("Delete indicator: Indicator with id: "+indicatorId+" not found");
477 57671 konstantin
        }
478
        return true;
479
    }
480
481 58978 konstantin
    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 57964 konstantin
//    @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 57671 konstantin
624 59814 konstantin
    @PreAuthorize("isAuthenticated()")
625 57964 konstantin
    @RequestMapping(value = "/{stakeholderId}/{topicId}/{categoryId}/{subcategoryId}/{sectionId}/{type}/reorder", method = RequestMethod.POST)
626 57683 konstantin
    public List<Indicator> reorderIndicators(@PathVariable("stakeholderId") String stakeholderId,
627 57964 konstantin
                                             @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 60107 konstantin
                                             @RequestBody ReorderEvent reorderEvent) {
633 57923 konstantin
        log.debug("reorder indicators of type: "+type);
634 57964 konstantin
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId);
635 57671 konstantin
636 60107 konstantin
        List<String> indicators = reorderEvent.getIds();
637
        String actionType = reorderEvent.getAction();
638
        String targetId = reorderEvent.getTarget();
639
640 57964 konstantin
        Section<String> section = checkForExceptions(stakeholderId, topicId, categoryId, subcategoryId, sectionId, type);
641 57671 konstantin
642 60107 konstantin
        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 57964 konstantin
        section.setIndicators(indicators);
649 57671 konstantin
650 60107 konstantin
        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 57964 konstantin
        sectionDAO.save(section);
661
        log.debug("Indicators reordered!");
662 57671 konstantin
663 57683 konstantin
        return indicatorsFull;
664 57671 konstantin
    }
665 57923 konstantin
666 59814 konstantin
//    @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 57923 konstantin
710 59814 konstantin
    @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 57964 konstantin
        log.debug("Stakeholder: "+stakeholderId + " - Topic: "+topicId + " - Category: "+categoryId+ " - SubCategory: "+subcategoryId + " - Section: "+sectionId+ " - Indicator: "+indicatorId);
721 57923 konstantin
722
        Indicator indicator = indicatorDAO.findById(indicatorId);
723
        if (indicator == null) {
724
            // EXCEPTION - Indicator not found
725 59814 konstantin
            throw new EntityNotFoundException("Change indicator visibility: Indicator with id: "+indicatorId+" not found");
726 57923 konstantin
        }
727 59814 konstantin
        indicator.setVisibility(visibility);
728 57923 konstantin
729 57964 konstantin
        this.toggleIndicator(stakeholderId, topicId, categoryId, subcategoryId, sectionId, indicator);
730 57923 konstantin
731 59814 konstantin
        return indicator.getVisibility();
732 57923 konstantin
    }
733
734 57964 konstantin
    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 57923 konstantin
        Stakeholder<String> stakeholder = stakeholderDAO.findById(stakeholderId);
751
752 57964 konstantin
        if(stakeholder == null) {
753
            // EXCEPTION - Stakeholder not found
754
            throw new EntityNotFoundException("Save indicator: Stakeholder with id: " + stakeholderId + " not found");
755
        }
756 57923 konstantin
757 59814 konstantin
        List<String> roles = rolesUtils.getRoles();
758
        if(!rolesUtils.hasUpdateAuthority(roles, stakeholder.getType(), stakeholder.getAlias())) {
759
            // EXCEPTION - Access denied
760 60107 konstantin
            throw new ForbiddenException("CheckForExceptions Indicator: You are not authorized to update stakeholder with id: "+stakeholderId);
761 59814 konstantin
        }
762
763 57964 konstantin
        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 57923 konstantin
769 57964 konstantin
        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 57923 konstantin
774 57964 konstantin
        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 57934 konstantin
780 57964 konstantin
        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 57923 konstantin
            }
807 57964 konstantin
        } 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 57923 konstantin
        }
813 57964 konstantin
814
        return  section;
815 57923 konstantin
    }
816 58978 konstantin
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 57671 konstantin
}