Projekt

Obecné

Profil

Stáhnout (19.7 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.model.table.BooleanWrapper;
16
import vldc.aswi.model.table.contingencyTable.ContingencyTableRow;
17
import vldc.aswi.service.*;
18
import vldc.aswi.service.parameter.ParameterManager;
19
import vldc.aswi.service.parameter.ParameterTypeManager;
20
import vldc.aswi.utils.AuthControl;
21
import vldc.aswi.validators.AssemblyValidator;
22
import vldc.aswi.utils.Utils;
23
import vldc.aswi.validators.ConfigurationValidator;
24

    
25
import javax.validation.Valid;
26
import java.util.*;
27
import java.util.stream.Collectors;
28

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

    
35
    /** Autowired sql query manager. */
36
    @Autowired
37
    private SqlQueryManager sqlQueryManager;
38

    
39
    /** Autowired assembly manager. */
40
    @Autowired
41
    private AssemblyManager assemblyManager;
42

    
43
    /** Autowired parameter manager. */
44
    @Autowired
45
    private ParameterManager parameterManager;
46

    
47
    /** Autowired configuration manager */
48
    @Autowired
49
    private ConfigurationManager configurationManager;
50

    
51
    /** Autowired role manager. */
52
    @Autowired
53
    private RoleManager roleManager;
54

    
55
    /** Autowired parameterType manager. */
56
    @Autowired
57
    private ParameterTypeManager parameterTypeManager;
58

    
59
    /** Autowired operator manager. */
60
    @Autowired
61
    private OperatorManager operatorManager;
62

    
63
    /** Autowired function manager. */
64
    @Autowired
65
    private FunctionManager functionManager;
66

    
67
    /** Autowired location manager. */
68
    @Autowired
69
    private LocationManager locationManager;
70

    
71
    /** Autowired assembly validator */
72
    @Autowired
73
    private AssemblyValidator assemblyValidator;
74

    
75
    /** Autowired configuration validator */
76
    @Autowired
77
    private ConfigurationValidator configurationValidator;
78

    
79
    /** Name of thymeleaf parameter, which will contain text in assembly form. */
80
    private String assemblyTitleName = "title";
81

    
82
    /** Title text for assembly edit form.  */
83
    private String assemblyEditTitleText = "Editace - ";
84

    
85
    /** Title text for new assembly form. */
86
    private String assemblyNewTitleText = "Vytvoření nové sestavy";
87

    
88
    /** Title text for table generation form.  */
89
    private String generateTableTitleText = "Generování tabulky - ";
90

    
91
    /**
92
     * Bind assembly validator.
93
     * @param binder Binder.
94
     */
95
    @InitBinder("assembly")
96
    protected void userBinder(WebDataBinder binder) {
97
        binder.addValidators(this.assemblyValidator);
98
    }
99

    
100
    /**
101
     * Get method for form, where configuration is created from assembly.
102
     * @param id - ID of assembly.
103
     * @return ModelAndView for assembly.
104
     */
105
    @GetMapping("/assembly")
106
    public ModelAndView assemblyGet(@RequestParam("assemblyID") String id) {
107
        ModelAndView modelAndView = new ModelAndView("assembly");
108

    
109
        ModelMap modelMap = modelAndView.getModelMap();
110

    
111
        Assembly assembly = this.assemblyManager.getAssemblyById(Long.parseLong(id));
112

    
113
        // TODO: 04.05.2020 error page when id doesn't exist
114

    
115
        String roleName = AuthControl.getRoleName();
116

    
117
        if (roleName == null) {
118
            // TODO: 04.05.2020 error message, user not authenticated
119
        }
120

    
121
        Role role = roleManager.getRole(roleName);
122

    
123
        if (!assembly.getRoles().contains(role) && !role.getName().equals("Administrátor")) {
124
            // TODO: 04.05.2020 Error page, wrong role
125
            return new ModelAndView("redirect:/");
126
        }
127

    
128
        Configuration configuration = new Configuration();
129

    
130
        configuration.setAssembly(assembly);
131
        configuration.setTableName(assembly.getName());
132
        configuration.setParametersInConfiguration(new ArrayList<>());
133
        for(Parameter parameter : assembly.getParameters()) {
134
            ParameterInConfiguration parameterInConfiguration = new ParameterInConfiguration();
135
            parameterInConfiguration.setParameter(parameter);
136
            parameterInConfiguration.setConfiguration(configuration);
137
            parameterInConfiguration.setOperator(new Operator());
138
            parameterInConfiguration.setLocation(new Location());
139
            parameterInConfiguration.setParameterOrder(parameter.getParameterOrder());
140
            configuration.getParametersInConfiguration().add(parameterInConfiguration);
141
        }
142

    
143
        Comparator<ParameterInConfiguration> comparator = Comparator.comparingInt(o -> o.getParameter().getParameterOrder());
144

    
145
        boolean isNotRemoveEmpty = false;
146
        modelMap.addAttribute("isNotRemoveEmpty", isNotRemoveEmpty);
147
        modelMap.addAttribute("configuration", configuration);
148
        modelMap.addAttribute("comparator", comparator);
149
        modelMap.addAttribute("formAction", "/assembly?assemblyID=" + assembly.getId());
150

    
151
        return modelAndView;
152
    }
153

    
154

    
155
    /**
156
     * Post method for form, where configuration is created from assembly.
157
     * @param newConfiguration - Configuration values.
158
     * @param bindingResult - Error results from assembly validators.
159
     * @param atts - Redirect attributes.
160
     * @return ModelAndView for assembly.
161
     */
162
    @PostMapping("/assembly")
163
    public ModelAndView assemblyPost(Configuration newConfiguration,
164
                                     BindingResult bindingResult,
165
                                     RedirectAttributes atts,
166
                                     @RequestParam("isNotRemoveEmpty") String isNotRemoveEmptyString,
167
                                     @RequestParam("assemblyID") String id,
168
                                     @RequestParam(required=false, value="generateTable") String generateTable,
169
                                     @RequestParam(required=false, value="exportXls") String exportXls,
170
                                     @RequestParam(required=false, value="exportPdf") String exportPdf,
171
                                     @RequestParam(required=false, value="saveConfiguration") String saveConfiguration,
172
                                     RedirectAttributes redirectAttributes)
173
    {
174

    
175
        ModelAndView modelAndView = new ModelAndView();
176
        ModelMap modelMap = modelAndView.getModelMap();
177

    
178
        if (bindingResult.hasErrors()) {
179
            // TODO: 04.05.2020 Error message
180
            modelAndView.setViewName("redirect:/");
181

    
182
            return modelAndView;
183
        }
184

    
185
        if (generateTable != null)
186
        {
187
            Assembly assembly = this.assemblyManager.getAssemblyById(Long.parseLong(id));
188
            newConfiguration.setAssembly(assembly);
189
            newConfiguration.setTableName(assembly.getName());
190

    
191
            // If configuration name is empty, then replace it by assembly name.
192
            if (newConfiguration.getName().equals("")) {
193
                newConfiguration.setName(assembly.getName());
194
            }
195

    
196
            System.out.println("Generuj tabulku");
197
            prepareForTable(newConfiguration);
198
            BindingResult errors = new BeanPropertyBindingResult(newConfiguration, newConfiguration.getClass().getName());
199
            configurationValidator.validate(newConfiguration, errors);
200
            if (errors.hasErrors()) {
201
                addConfigurationDataIntoModelAndView(newConfiguration, modelAndView, modelMap);
202

    
203
                modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(errors));
204
                modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
205
            }
206
            else {
207
                boolean isNotRemoveEmpty = isNotRemoveEmptyString == null || !isNotRemoveEmptyString.equals("");
208
                List<ContingencyTableRow> rows = this.sqlQueryManager.getContingencyTableRow(newConfiguration.getAssembly(),
209
                        newConfiguration.getParametersInConfiguration(), isNotRemoveEmpty);
210

    
211
                System.out.println("Generuj tabulku");
212
                modelMap.addAttribute("configurationID", id);
213
                modelMap.addAttribute("contingencyTableRows", rows);
214
                modelMap.addAttribute("isNotRemoveEmpty", isNotRemoveEmpty);
215
                addConfigurationDataIntoModelAndView(newConfiguration, modelAndView, modelMap);
216
            }
217
        }
218
        else if (exportXls != null)
219
        {
220
            System.out.println("Generuj XLS");
221
        }
222
        else if (exportPdf != null)
223
        {
224
            System.out.println("Generuj PDF");
225
        }
226
        else if (saveConfiguration != null)
227
        {
228
            System.out.println("ulož konfiguraci");
229

    
230
            Configuration configuration = configurationManager.saveConfiguration(newConfiguration, "");
231

    
232
            initializeFields(configuration);
233

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

    
236
            modelAndView.setViewName("redirect:/configuration?configurationID=" + configuration.getId());
237
        }
238

    
239
        return modelAndView;
240
/*
241
        ModelMap modelMap = modelAndView.getModelMap();
242

    
243
        long assemblyID = assembly.getId();
244
        System.out.println(assemblyID);
245

    
246
        Assembly assembly2 = this.assemblyManager.getAssemblyById(assemblyID);
247

    
248
        modelMap.addAttribute("assemblies", this.assemblyManager.getAssemblies());
249
        modelMap.addAttribute("assembly", assembly2);
250
        modelMap.addAttribute("contingencyTableRows", this.sqlQueryManager.getContingencyTableRow(assembly2.getSQLQuery()));
251

    
252
        return modelAndView;
253

    
254
 */
255
    }
256

    
257
    /**
258
     * Adds configuration and other data to modelAndView.
259
     * @param newConfiguration Configuration to be added to the modelAndView.
260
     * @param modelAndView ModelAndView to which to which modelMap belongs.
261
     * @param modelMap ModelMap to which data is added.
262
     */
263
    private void addConfigurationDataIntoModelAndView(Configuration newConfiguration, ModelAndView modelAndView, ModelMap modelMap) {
264
        Comparator<ParameterInConfiguration> comparator = Comparator.comparingInt(o -> o.getParameter().getParameterOrder());
265
        initializeFields(newConfiguration);
266
        modelMap.addAttribute("configuration", newConfiguration);
267
        modelMap.addAttribute("comparator", comparator);
268
        modelMap.addAttribute("formAction", "/assembly?assemblyID=" + newConfiguration.getAssembly().getId());
269
        modelAndView.setViewName("assembly");
270
    }
271

    
272
    /**
273
     * Get method for assembly delete.
274
     * @param id - ID of assembly.
275
     * @return ModelAndView for index.
276
     */
277
    @GetMapping("/assembly_delete")
278
    public ModelAndView assemblyDeleteGet(@RequestParam("assemblyID") String id, RedirectAttributes redirectAttributes) {
279
        ModelAndView modelAndView = new ModelAndView("redirect:/");
280

    
281
        Long assemblyId = Utils.tryParseLong(id);
282

    
283
        if (assemblyId == null) {
284
            redirectAttributes.addFlashAttribute(assemblyErrorName, "Sestavu se nepodařilo odstranit.");
285
        }
286
        boolean success = this.assemblyManager.deleteAssembly(assemblyId);
287

    
288
        if (success)
289
        {
290
            redirectAttributes.addFlashAttribute(assemblySuccessName, "Sestava byla úspěšně odstraněna");
291
        }
292
        else
293
        {
294
            redirectAttributes.addFlashAttribute(assemblyErrorName, "Sestavu se nepodařilo odstranit");
295
        }
296

    
297
        return modelAndView;
298
    }
299

    
300
    /**
301
     * Get method for assembly edit.
302
     * @param id - Id of assembly.
303
     * @return ModelAndView for assembly edit.
304
     */
305
    @GetMapping("/assembly_edit")
306
    public ModelAndView assemblyEditGet(@RequestParam("assemblyID") String id) {
307
        long startTime = System.currentTimeMillis();
308
        ModelAndView modelAndView = new ModelAndView("assembly_manage");
309

    
310
        ModelMap modelMap = modelAndView.getModelMap();
311

    
312
        Assembly assembly = this.assemblyManager.getAssemblyById(Long.parseLong(id));
313

    
314
        modelMap.addAttribute("assembly", assembly);
315

    
316
        modelMap.addAttribute(assemblyTitleName, assemblyEditTitleText + " " + assembly.getName());
317

    
318
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
319
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
320
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
321
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
322
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
323
        long estimatedTime = System.currentTimeMillis() - startTime;
324
        System.out.println("EDIT GET estimated - " + ((double)estimatedTime / 1000) + " sekund ");
325

    
326
        return modelAndView;
327
    }
328

    
329
    /**
330
     * Post method for assembly edit.
331
     * @param assembly - Edited assembly values.
332
     * @param result - Validator results.
333
     * @param assemblyIsPublic - Attribute indicating if assembly is public or not.
334
     * @return ModelAndView for assembly edit.
335
     */
336
    @PostMapping("/assembly_edit")
337
    public ModelAndView assemblyEditPost(@Valid @ModelAttribute("assembly") Assembly assembly, BindingResult result,
338
                                              @Valid @ModelAttribute("checkboxPublic") String assemblyIsPublic) {
339
        long startTime = System.currentTimeMillis();
340
        ModelAndView modelAndView = new ModelAndView("assembly_manage");
341
        ModelMap modelMap = modelAndView.getModelMap();
342

    
343
        if (result.hasErrors()) {
344
            modelMap.addAttribute("assembly", assembly);
345

    
346
            modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(result));
347
            modelMap.addAttribute(assemblyTitleName, assemblyEditTitleText + " " + assembly.getName());
348
        }
349
        else {
350
            if (assemblyIsPublic.equals("on")) assembly.setIsPublic(1);
351
            else assembly.setIsPublic(0);
352

    
353
            // TODO: chybí defaultValue.
354
            Long assemblyID = this.assemblyManager.updateAssembly(assembly);
355

    
356
            this.parameterManager.updateParameters(assemblyID, assembly.getParameters());
357
            Assembly updatedAssembly = this.assemblyManager.getAssemblyById(assemblyID);
358

    
359
            modelMap.addAttribute("assembly", updatedAssembly);
360
            modelMap.addAttribute(assemblyTitleName, assemblyEditTitleText + " " + updatedAssembly.getName());
361
            modelMap.addAttribute(assemblySuccessName, "Úspěšně uloženo");
362
        }
363

    
364
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
365
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
366
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
367
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
368
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
369
        long estimatedTime = System.currentTimeMillis() - startTime;
370
        System.out.println("EDIT POST estimated - " + ((double)estimatedTime / 1000) + " sekund ");
371

    
372
        return modelAndView;
373
    }
374

    
375
    /**
376
     * Get method for new assembly form.
377
     * @return ModelAndView for new assembly.
378
     */
379
    @GetMapping("/assembly_new")
380
    public ModelAndView assemblyNewGet() {
381
        ModelAndView modelAndView = new ModelAndView("assembly_manage");
382

    
383
        ModelMap modelMap = modelAndView.getModelMap();
384

    
385
        modelMap.addAttribute("assembly", new Assembly());
386

    
387
        modelMap.addAttribute(assemblyTitleName, assemblyNewTitleText);
388

    
389
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
390
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
391
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
392
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
393
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
394

    
395
        return modelAndView;
396
    }
397

    
398
    /**
399
     * Post method for new assembly form.
400
     * @param assembly - Assembly values.
401
     * @param result - Validator results.
402
     * @return
403
     */
404
    @PostMapping("/assembly_new")
405
    public ModelAndView assemblyNewPost(@Valid @ModelAttribute("assembly") Assembly assembly, BindingResult result) {
406
        ModelAndView modelAndView = new ModelAndView();
407
        ModelMap modelMap = modelAndView.getModelMap();
408

    
409
        if (result.hasErrors()) {
410
            modelAndView.setViewName("assembly_manage");
411
            modelMap.addAttribute("assembly", assembly);
412

    
413
            modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(result));
414
            modelMap.addAttribute(assemblyTitleName, assemblyNewTitleText);
415
        }
416
        else {
417
            // TODO: chybí získání default value.
418
            Long assemblyId = this.assemblyManager.createAssembly(assembly);
419
            this.parameterManager.addParameters(assemblyId, assembly.getParameters());
420

    
421
            modelAndView.setViewName("redirect:/assembly_edit?assemblyID=" + assemblyId);
422
            modelMap.addAttribute(assemblySuccessName, "Sestava byla úspěšně vytvořena");
423
        }
424

    
425
        modelMap.addAttribute("allRoles", this.roleManager.getRoles());
426
        modelMap.addAttribute("allParameterTypes", this.parameterTypeManager.getParameterTypes());
427
        modelMap.addAttribute("allFunctions", this.functionManager.getFunctions());
428
        modelMap.addAttribute("allOperators", this.operatorManager.getOperators());
429
        modelMap.addAttribute("allLocations", this.locationManager.getLocations());
430

    
431
        return modelAndView;
432
    }
433

    
434
    /**
435
     * Initializes fields of a given configuration
436
     * @param configuration configuration which fields should be initialized
437
     */
438
    private void initializeFields(Configuration configuration) {
439
        for(ParameterInConfiguration parameterInConfiguration : configuration.getParametersInConfiguration()) {
440
            if(parameterInConfiguration.getLocation() == null) {
441
                parameterInConfiguration.setLocation(new Location());
442
            }
443
            if(parameterInConfiguration.getOperator() == null) {
444
                parameterInConfiguration.setOperator(new Operator());
445
            }
446
            if(parameterInConfiguration.getFunctions() == null) {
447
                parameterInConfiguration.setFunctions(new ArrayList<>());
448
            }
449
        }
450
    }
451

    
452
    /**
453
     * Prepares the configuration for contingency table generation. Initializes assembly and parameters of parameters in
454
     * configuration.
455
     * @param configuration configuration to be prepared.
456
     */
457
    private void prepareForTable(Configuration configuration) {
458
        Assembly assembly = assemblyManager.getAssemblyById(configuration.getAssembly().getId());
459
        configuration.setAssembly(assembly);
460

    
461
        for(int i = 0; i < configuration.getParametersInConfiguration().size(); i++) {
462
            ParameterInConfiguration parameterInConfiguration = configuration.getParametersInConfiguration().get(i);
463
            parameterInConfiguration.setParameter(parameterManager.getParameterById(parameterInConfiguration.getParameter().getId()));
464
            if (parameterInConfiguration.getLocation() != null) {
465
                parameterInConfiguration.setLocation(locationManager.getLocationById(parameterInConfiguration.getLocation().getId()));
466
            } else {
467
                parameterInConfiguration.setLocation(new Location());
468
            }
469
            parameterInConfiguration.setConfiguration(configuration);
470
        }
471

    
472
        Comparator<ParameterInConfiguration> comparator = Comparator.comparingInt(o -> o.getParameter().getParameterOrder());
473
        configuration.getParametersInConfiguration().sort(comparator);
474
    }
475
}
(1-1/5)