Projekt

Obecné

Profil

Stáhnout (21.5 KB) Statistiky
| Větev: | Revize:
1
package vldc.aswi.web.controller;
2

    
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.stereotype.Controller;
5
import org.springframework.ui.ModelMap;
6
import org.springframework.validation.BeanPropertyBindingResult;
7
import org.springframework.validation.BindingResult;
8
import org.springframework.web.bind.WebDataBinder;
9
import org.springframework.web.bind.annotation.*;
10
import org.springframework.web.servlet.ModelAndView;
11
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
12
import vldc.aswi.domain.*;
13
import vldc.aswi.domain.parameter.Parameter;
14
import vldc.aswi.domain.parameter.ParameterInConfiguration;
15
import vldc.aswi.domain.parameter.ParameterType;
16
import vldc.aswi.model.ExportType;
17
import vldc.aswi.model.table.contingencyTable.ContingencyTableRow;
18
import vldc.aswi.service.*;
19
import vldc.aswi.service.parameter.ParameterManager;
20
import vldc.aswi.service.parameter.ParameterTypeManager;
21
import vldc.aswi.utils.AuthControl;
22
import vldc.aswi.validators.AssemblyValidator;
23
import vldc.aswi.utils.Utils;
24
import vldc.aswi.validators.ConfigurationValidator;
25
import javax.servlet.http.HttpServletResponse;
26
import javax.validation.Valid;
27
import java.util.ArrayList;
28
import java.util.Comparator;
29
import java.util.List;
30

    
31
/**
32
 * Controller for assemblies and configurations
33
 */
34
@Controller
35
public class AssemblyController extends BasicController {
36

    
37
    /** Autowired sql query manager. */
38
    @Autowired
39
    private SqlQueryManager sqlQueryManager;
40

    
41
    /** Autowired assembly manager. */
42
    @Autowired
43
    private AssemblyManager assemblyManager;
44

    
45
    /** Autowired parameter manager. */
46
    @Autowired
47
    private ParameterManager parameterManager;
48

    
49
    /** Autowired export manager. */
50
    @Autowired
51
    private ExportManager exportManager;
52

    
53
    /** Autowired configuration manager */
54
    @Autowired
55
    private ConfigurationManager configurationManager;
56

    
57
    /** Autowired role manager. */
58
    @Autowired
59
    private RoleManager roleManager;
60

    
61
    /** Autowired parameterType manager. */
62
    @Autowired
63
    private ParameterTypeManager parameterTypeManager;
64

    
65
    /** Autowired operator manager. */
66
    @Autowired
67
    private OperatorManager operatorManager;
68

    
69
    /** Autowired function manager. */
70
    @Autowired
71
    private FunctionManager functionManager;
72

    
73
    /** Autowired location manager. */
74
    @Autowired
75
    private LocationManager locationManager;
76

    
77
    /** Autowired assembly validator */
78
    @Autowired
79
    private AssemblyValidator assemblyValidator;
80

    
81
    /** Autowired configuration validator */
82
    @Autowired
83
    private ConfigurationValidator configurationValidator;
84

    
85
    /** Name of thymeleaf parameter, which will contain text in assembly form. */
86
    private String assemblyTitleName = "title";
87

    
88
    /** Title text for assembly edit form.  */
89
    private String assemblyEditTitleText = "Editace - ";
90

    
91
    /** Title text for new assembly form. */
92
    private String assemblyNewTitleText = "Vytvoření nové sestavy";
93

    
94
    /** Title text for table generation form.  */
95
    private String generateTableTitleText = "Generování tabulky - ";
96

    
97
    /**
98
     * Bind assembly validator.
99
     * @param binder Binder.
100
     */
101
    @InitBinder("assembly")
102
    protected void userBinder(WebDataBinder binder) {
103
        binder.addValidators(this.assemblyValidator);
104
    }
105

    
106
    /**
107
     * Get method for form, where configuration is created from assembly.
108
     * @param id - ID of assembly.
109
     * @return ModelAndView for assembly.
110
     */
111
    @GetMapping("/assembly")
112
    public ModelAndView assemblyGet(@RequestParam("assemblyID") String id) {
113
        ModelAndView modelAndView = new ModelAndView("assembly");
114

    
115
        ModelMap modelMap = modelAndView.getModelMap();
116

    
117
        Assembly assembly = this.assemblyManager.getAssemblyById(Long.parseLong(id));
118

    
119
        // TODO: 04.05.2020 error page when id doesn't exist
120

    
121
        String roleName = AuthControl.getRoleName();
122

    
123
        if (roleName == null) {
124
            // TODO: 04.05.2020 error message, user not authenticated
125
        }
126

    
127
        Role role = roleManager.getRole(roleName);
128

    
129
        if (!assembly.getRoles().contains(role) && !role.getName().equals("Administrátor")) {
130
            // TODO: 04.05.2020 Error page, wrong role
131
            return new ModelAndView("redirect:/");
132
        }
133

    
134
        List<Operator> operatorList = operatorManager.getOperators();
135

    
136
        Configuration configuration = new Configuration();
137
        configuration.setAssembly(assembly);
138
        configuration.setTableName(assembly.getName());
139
        configuration.setParametersInConfiguration(new ArrayList<>());
140
        for(Parameter parameter : assembly.getParameters()) {
141
            ParameterInConfiguration parameterInConfiguration = new ParameterInConfiguration();
142
            parameterInConfiguration.setParameter(parameter);
143
            parameterInConfiguration.setConfiguration(configuration);
144

    
145
            if (parameter.getParameterType().getName().toLowerCase().equals("výčet")) {
146

    
147
                for (Operator operator : operatorList) {
148

    
149
                    if (operator.getName().toLowerCase().equals("in")) {
150
                        parameterInConfiguration.setOperator(operator);
151
                    }
152
                }
153

    
154
            } else {
155
                parameterInConfiguration.setOperator(new Operator());
156
            }
157
            parameterInConfiguration.setLocation(new Location());
158
            parameterInConfiguration.setParameterOrder(parameter.getParameterOrder());
159
            configuration.getParametersInConfiguration().add(parameterInConfiguration);
160
        }
161

    
162
        boolean isNotRemoveEmpty = false;
163
        modelMap.addAttribute("isNotRemoveEmpty", isNotRemoveEmpty);
164
        modelMap.addAttribute("configuration", configuration);
165
        modelMap.addAttribute("formAction", "/assembly?assemblyID=" + assembly.getId());
166

    
167
        return modelAndView;
168
    }
169

    
170
    /**
171
     * Post method for form, where configuration is created from assembly.
172
     * @param newConfiguration - Configuration values.
173
     * @param bindingResult - Error results from assembly validators.
174
     * @param atts Attributes.
175
     * @param isNotRemoveEmptyString String that stores if switch to not remove empty rows and columns was set.
176
     * @param id ID of the assembly.
177
     * @param generateTable String used to check if generate table button was clicked.
178
     * @param exportPdf String used to check if export to PDF button was clicked.
179
     * @param exportXlsx String used to check if export to XLSX button was clicked.
180
     * @param redirectAttributes Attributes.
181
     * @param saveConfiguration String used to check if save configuration button was clicked.
182
     * @param response HTTP servlet response.
183
     * @return ModelAndView for assembly.
184
     */
185
    @PostMapping("/assembly")
186
    public ModelAndView assemblyPost(Configuration newConfiguration,
187
                                     BindingResult bindingResult,
188
                                     RedirectAttributes atts,
189
                                     @RequestParam("isNotRemoveEmpty") String isNotRemoveEmptyString,
190
                                     @RequestParam("assemblyID") String id,
191
                                     @RequestParam(required=false, value="generateTable") String generateTable,
192
                                     @RequestParam(required=false, value="exportXlsx") String exportXlsx,
193
                                     @RequestParam(required=false, value="exportPdf") String exportPdf,
194
                                     @RequestParam(required=false, value="saveConfiguration") String saveConfiguration,
195
                                     RedirectAttributes redirectAttributes,
196
                                     HttpServletResponse response
197
                                    )
198
    {
199

    
200
        ModelAndView modelAndView = new ModelAndView();
201
        ModelMap modelMap = modelAndView.getModelMap();
202
        boolean isNotRemoveEmpty = isNotRemoveEmptyString == null || !isNotRemoveEmptyString.equals("");
203

    
204
        if (bindingResult.hasErrors()) {
205
            // TODO: 04.05.2020 Error message
206
            modelAndView.setViewName("redirect:/");
207

    
208
            return modelAndView;
209
        }
210

    
211
        if (generateTable != null)
212
        {
213
            Assembly assembly = this.assemblyManager.getAssemblyById(Long.parseLong(id));
214
            newConfiguration.setAssembly(assembly);
215

    
216
            if (newConfiguration.getTableName() == null || newConfiguration.getTableName().equals("")) {
217
                newConfiguration.setTableName(assembly.getName());
218
            }
219

    
220
            // If configuration name is empty, then replace it by assembly name.
221
            if (newConfiguration.getName().equals("")) {
222
                newConfiguration.setName(assembly.getName());
223
            }
224

    
225
            prepareForTable(newConfiguration);
226
            BindingResult errors = new BeanPropertyBindingResult(newConfiguration, newConfiguration.getClass().getName());
227
            configurationValidator.validate(newConfiguration, errors);
228
            if (errors.hasErrors()) {
229
                addConfigurationDataIntoModelAndView(newConfiguration, modelAndView, modelMap);
230

    
231
                modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(errors));
232
                modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
233
            }
234
            else {
235
                List<ContingencyTableRow> rows = this.sqlQueryManager.getContingencyTableRow(newConfiguration.getAssembly(),
236
                        newConfiguration.getParametersInConfiguration(), isNotRemoveEmpty, newConfiguration.getTableName());
237

    
238
                if (rows != null) {
239
                    if (rows.isEmpty()) {
240
                        modelMap.addAttribute(assemblyErrorName, "Výsledná tabulka neobsahuje žádné hodnoty (" +
241
                                "SQL dotaz nevrátil žádné řádky)!");
242
                        modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
243
                    }
244
                    else {
245
                        modelMap.addAttribute("configurationID", id);
246
                        modelMap.addAttribute("contingencyTableRows", rows);
247
                        modelMap.addAttribute("isNotRemoveEmpty", isNotRemoveEmpty);
248
                        addConfigurationDataIntoModelAndView(newConfiguration, modelAndView, modelMap);
249
                    }
250
                }
251
                else {
252
                    modelMap.addAttribute(assemblyErrorName,  "Vyskytla se chyba v SQL dotazu! Prosím " +
253
                            "zkontrolujte zadané hodnoty filtrů nebo kontaktujte administrátora!");
254
                    modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
255
                }
256
            }
257
        }
258
        else if (exportXlsx != null)
259
        {
260
            prepareForTable(newConfiguration);
261
            this.exportManager.exportContingencyTable(newConfiguration, isNotRemoveEmpty, response, ExportType.XLSX);
262

    
263
            // Return null, because we want to continue on our page with selected parameters / attributes.
264
            return null;
265
        }
266
        else if (exportPdf != null)
267
        {
268
            prepareForTable(newConfiguration);
269
            this.exportManager.exportContingencyTable(newConfiguration, isNotRemoveEmpty, response, ExportType.PDF);
270

    
271
            // Return null, because we want to continue on our page with selected parameters / attributes.
272
            return null;
273

    
274
        }
275
        else if (saveConfiguration != null)
276
        {
277
            Configuration configuration = configurationManager.saveConfiguration(newConfiguration, "");
278

    
279
            initializeFields(configuration);
280

    
281
            redirectAttributes.addFlashAttribute(assemblySuccessName, "Šablona byla úspěšně uložena");
282

    
283
            modelAndView.setViewName("redirect:/configuration?configurationID=" + configuration.getId());
284
        }
285

    
286
        return modelAndView;
287
    }
288

    
289
    /**
290
     * Adds configuration and other data to modelAndView.
291
     * @param newConfiguration Configuration to be added to the modelAndView.
292
     * @param modelAndView ModelAndView to which to which modelMap belongs.
293
     * @param modelMap ModelMap to which data is added.
294
     */
295
    private void addConfigurationDataIntoModelAndView(Configuration newConfiguration, ModelAndView modelAndView, ModelMap modelMap) {
296
        initializeFields(newConfiguration);
297
        modelMap.addAttribute("configuration", newConfiguration);
298
        modelMap.addAttribute("formAction", "/assembly?assemblyID=" + newConfiguration.getAssembly().getId());
299
        modelAndView.setViewName("assembly");
300
    }
301

    
302
    /**
303
     * Get method for assembly delete.
304
     * @param id - ID of assembly.
305
     * @return ModelAndView for index.
306
     */
307
    @GetMapping("/assembly_delete")
308
    public ModelAndView assemblyDeleteGet(@RequestParam("assemblyID") String id, RedirectAttributes redirectAttributes) {
309
        ModelAndView modelAndView = new ModelAndView("redirect:/");
310

    
311
        Long assemblyId = Utils.tryParseLong(id);
312

    
313
        if (assemblyId == null) {
314
            redirectAttributes.addFlashAttribute(assemblyErrorName, "Sestavu se nepodařilo odstranit.");
315
        }
316
        boolean success = this.assemblyManager.deleteAssembly(assemblyId);
317

    
318
        if (success)
319
        {
320
            redirectAttributes.addFlashAttribute(assemblySuccessName, "Sestava byla úspěšně odstraněna");
321
        }
322
        else
323
        {
324
            redirectAttributes.addFlashAttribute(assemblyErrorName, "Sestavu se nepodařilo odstranit");
325
        }
326

    
327
        return modelAndView;
328
    }
329

    
330
    /**
331
     * Get method for assembly edit.
332
     * @param id - Id of assembly.
333
     * @return ModelAndView for assembly edit.
334
     */
335
    @GetMapping("/assembly_edit")
336
    public ModelAndView assemblyEditGet(@RequestParam("assemblyID") String id) {
337
        long startTime = System.currentTimeMillis();
338
        ModelAndView modelAndView = new ModelAndView("assembly_manage");
339

    
340
        ModelMap modelMap = modelAndView.getModelMap();
341

    
342
        Assembly assembly = this.assemblyManager.getAssemblyById(Long.parseLong(id));
343

    
344
        modelMap.addAttribute("assembly", assembly);
345

    
346
        modelMap.addAttribute(assemblyTitleName, assemblyEditTitleText + " " + assembly.getName());
347

    
348
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
349
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
350
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
351
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
352
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
353
        long estimatedTime = System.currentTimeMillis() - startTime;
354
        System.out.println("EDIT GET estimated - " + ((double)estimatedTime / 1000) + " sekund ");
355

    
356
        return modelAndView;
357
    }
358

    
359
    /**
360
     * Post method for assembly edit.
361
     * @param assembly - Edited assembly values.
362
     * @param result - Validator results.
363
     * @param assemblyIsPublic - Attribute indicating if assembly is public or not.
364
     * @return ModelAndView for assembly edit.
365
     */
366
    @PostMapping("/assembly_edit")
367
    public ModelAndView assemblyEditPost(@Valid @ModelAttribute("assembly") Assembly assembly, BindingResult result,
368
                                              @Valid @ModelAttribute("checkboxPublic") String assemblyIsPublic) {
369
        long startTime = System.currentTimeMillis();
370
        ModelAndView modelAndView = new ModelAndView("assembly_manage");
371
        ModelMap modelMap = modelAndView.getModelMap();
372

    
373
        if (result.hasErrors()) {
374
            modelMap.addAttribute("assembly", assembly);
375

    
376
            modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(result));
377
            modelMap.addAttribute(assemblyTitleName, assemblyEditTitleText + " " + assembly.getName());
378
        }
379
        else {
380
            if (assemblyIsPublic.equals("on")) assembly.setIsPublic(1);
381
            else assembly.setIsPublic(0);
382

    
383
            // TODO: chybí defaultValue.
384
            Long assemblyID = this.assemblyManager.updateAssembly(assembly);
385

    
386
            this.parameterManager.updateParameters(assemblyID, assembly.getParameters());
387
            Assembly updatedAssembly = this.assemblyManager.getAssemblyById(assemblyID);
388

    
389
            modelMap.addAttribute("assembly", updatedAssembly);
390
            modelMap.addAttribute(assemblyTitleName, assemblyEditTitleText + " " + updatedAssembly.getName());
391
            modelMap.addAttribute(assemblySuccessName, "Úspěšně uloženo");
392
        }
393

    
394
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
395
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
396
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
397
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
398
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
399
        long estimatedTime = System.currentTimeMillis() - startTime;
400
        System.out.println("EDIT POST estimated - " + ((double)estimatedTime / 1000) + " sekund ");
401

    
402
        return modelAndView;
403
    }
404

    
405
    /**
406
     * Get method for new assembly form.
407
     * @return ModelAndView for new assembly.
408
     */
409
    @GetMapping("/assembly_new")
410
    public ModelAndView assemblyNewGet() {
411
        ModelAndView modelAndView = new ModelAndView("assembly_manage");
412

    
413
        ModelMap modelMap = modelAndView.getModelMap();
414

    
415
        modelMap.addAttribute("assembly", new Assembly());
416

    
417
        modelMap.addAttribute(assemblyTitleName, assemblyNewTitleText);
418

    
419
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
420
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
421
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
422
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
423
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
424

    
425
        return modelAndView;
426
    }
427

    
428
    /**
429
     * Post method for new assembly form.
430
     * @param assembly - Assembly values.
431
     * @param result - Validator results.
432
     * @return
433
     */
434
    @PostMapping("/assembly_new")
435
    public ModelAndView assemblyNewPost(@Valid @ModelAttribute("assembly") Assembly assembly, BindingResult result) {
436
        ModelAndView modelAndView = new ModelAndView();
437
        ModelMap modelMap = modelAndView.getModelMap();
438

    
439
        if (result.hasErrors()) {
440
            modelAndView.setViewName("assembly_manage");
441
            modelMap.addAttribute("assembly", assembly);
442

    
443
            modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(result));
444
            modelMap.addAttribute(assemblyTitleName, assemblyNewTitleText);
445
        }
446
        else {
447
            // TODO: chybí získání default value.
448
            Long assemblyId = this.assemblyManager.createAssembly(assembly);
449
            this.parameterManager.addParameters(assemblyId, assembly.getParameters());
450

    
451
            modelAndView.setViewName("redirect:/assembly_edit?assemblyID=" + assemblyId);
452
            modelMap.addAttribute(assemblySuccessName, "Sestava byla úspěšně vytvořena");
453
        }
454

    
455
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
456
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
457
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
458
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
459
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
460

    
461
        return modelAndView;
462
    }
463

    
464
    /**
465
     * Initializes fields of a given configuration
466
     * @param configuration configuration which fields should be initialized
467
     */
468
    private void initializeFields(Configuration configuration) {
469
        for(ParameterInConfiguration parameterInConfiguration : configuration.getParametersInConfiguration()) {
470
            if(parameterInConfiguration.getLocation() == null) {
471
                parameterInConfiguration.setLocation(new Location());
472
            }
473
            if(parameterInConfiguration.getOperator() == null) {
474
                parameterInConfiguration.setOperator(new Operator());
475
            }
476
            if(parameterInConfiguration.getFunctions() == null) {
477
                parameterInConfiguration.setFunctions(new ArrayList<>());
478
            }
479
        }
480
    }
481

    
482
    /**
483
     * Prepares the configuration for contingency table generation. Initializes assembly and parameters of parameters in
484
     * configuration.
485
     * @param configuration configuration to be prepared.
486
     */
487
    private void prepareForTable(Configuration configuration) {
488
        Assembly assembly = assemblyManager.getAssemblyById(configuration.getAssembly().getId());
489
        configuration.setAssembly(assembly);
490

    
491
        for(int i = 0; i < configuration.getParametersInConfiguration().size(); i++) {
492
            ParameterInConfiguration parameterInConfiguration = configuration.getParametersInConfiguration().get(i);
493
            parameterInConfiguration.setParameter(parameterManager.getParameterById(parameterInConfiguration.getParameter().getId()));
494
            if (parameterInConfiguration.getLocation() != null) {
495
                parameterInConfiguration.setLocation(locationManager.getLocationById(parameterInConfiguration.getLocation().getId()));
496
            } else {
497
                parameterInConfiguration.setLocation(new Location());
498
            }
499
            parameterInConfiguration.setConfiguration(configuration);
500
        }
501

    
502
        Comparator<ParameterInConfiguration> comparator = Comparator.comparingInt(o -> o.getParameter().getParameterOrder());
503
        configuration.getParametersInConfiguration().sort(comparator);
504
    }
505
}
(1-1/5)