Projekt

Obecné

Profil

Stáhnout (13.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.annotation.*;
9
import org.springframework.web.servlet.ModelAndView;
10
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
11
import vldc.aswi.domain.Assembly;
12
import vldc.aswi.domain.Configuration;
13
import vldc.aswi.domain.Location;
14
import vldc.aswi.domain.Operator;
15
import vldc.aswi.domain.parameter.ParameterInConfiguration;
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.utils.AuthControl;
21
import vldc.aswi.utils.Utils;
22

    
23
import javax.servlet.http.HttpServletRequest;
24
import javax.servlet.http.HttpServletResponse;
25
import vldc.aswi.validators.ConfigurationValidator;
26

    
27
import javax.validation.Valid;
28
import java.util.ArrayList;
29
import java.util.Comparator;
30
import java.util.List;
31

    
32
/**
33
 * Manager for configuration.
34
 */
35
@Controller
36
public class ConfigurationController extends BasicController{
37

    
38
    /** Autowired location manager. */
39
    @Autowired
40
    private LocationManager locationManager;
41

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

    
46
    /** Autowired sql query manager. */
47
    @Autowired
48
    private SqlQueryManager sqlQueryManager;
49

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

    
54
    /** Autowired parameter manager. */
55
    @Autowired
56
    private ParameterManager parameterManager;
57

    
58
    /** Autowired configuration manager */
59
    @Autowired
60
    private ConfigurationManager configurationManager;
61

    
62
    /** Autowired configuration validator */
63
    @Autowired
64
    private ConfigurationValidator configurationValidator;
65

    
66
    /** Name of thymeleaf parameter, which will contain text in assembly form. */
67
    private String assemblyTitleName = "title";
68

    
69
    /** Title text for table generation form.  */
70
    private String generateTableTitleText = "Generování tabulky - ";
71

    
72
    /**
73
     * Opens an configuration page after configuration name was clicked
74
     * @param id ID of configuration
75
     * @param errorMsg Error message text.
76
     * @param successMsg Success message text.
77
     * @return modelAndView of page to be shown
78
     */
79
    @GetMapping("/configuration")
80
    public ModelAndView configurationGet(@RequestParam("configurationID") String id,
81
                                         @ModelAttribute("successText") String successMsg,
82
                                         @ModelAttribute("errorText") String errorMsg) {
83
        ModelAndView modelAndView = new ModelAndView("assembly");
84

    
85
        ModelMap modelMap = modelAndView.getModelMap();
86

    
87
        Configuration configuration = configurationManager.getConfigurationById(Long.parseLong(id));
88

    
89
        // TODO: 04.05.2020 error page when id doesn't exist
90

    
91
        String userName = AuthControl.getUserName();
92

    
93
        if (userName == null) {
94
            // TODO: 04.05.2020 error message, user not authenticated
95
        }
96
        else if (!userName.equals(configuration.getUser().getUsername())) {
97
            // TODO: 04.05.2020 error page wrong user
98
            return new ModelAndView("redirect:/");
99
        }
100

    
101
        List<ParameterInConfiguration> parametersInConfiguration = new ArrayList<>(configuration.getParametersInConfiguration());
102
        configuration.setParametersInConfiguration(parametersInConfiguration);
103

    
104
        initializeFields(configuration);
105

    
106
        modelMap.addAttribute("configuration", configuration);
107
        modelMap.addAttribute("formAction", "/configuration?configurationID=" + configuration.getId());
108

    
109
        modelMap.addAttribute(assemblySuccessName, successMsg);
110
        modelMap.addAttribute(assemblyErrorName, errorMsg);
111

    
112
        return modelAndView;
113
    }
114

    
115
    /**
116
     * Saves or edits configuration and redirects to the page with configuration
117
     * @param newConfiguration contained with configuration data
118
     * @param bindingResult - Error results from assembly validators.
119
     * @param isNotRemoveEmptyString String that stores if switch to not remove empty rows and columns was set.
120
     * @param id ID of the assembly.
121
     * @param generateTable String used to check if generate table button was clicked.
122
     * @param exportPdf String used to check if export to PDF button was clicked.
123
     * @param exportXlsx String used to check if export to XLSX button was clicked.
124
     * @param redirectAttributes Attributes.
125
     * @param saveConfiguration String used to check if save configuration button was clicked.
126
     * @param response HTTP servlet response.
127
     * @param request HTTP servlet request.
128
     * @return ModelAndView for assembly.
129
     */
130
    @PostMapping("/configuration")
131
    public ModelAndView configurationPost(@Valid Configuration newConfiguration,
132
                                           BindingResult bindingResult,
133
                                           @RequestParam("isNotRemoveEmpty") String isNotRemoveEmptyString,
134
                                           @RequestParam("configurationID") String id,
135
                                           @RequestParam(required=false, value="generateTable") String generateTable,
136
                                           @RequestParam(required=false, value="exportXlsx") String exportXlsx,
137
                                           @RequestParam(required=false, value="exportPdf") String exportPdf,
138
                                           @RequestParam(required=false, value="saveConfiguration") String saveConfiguration,
139
                                            RedirectAttributes redirectAttributes,
140
                                            HttpServletRequest request,
141
                                            HttpServletResponse response
142
                                          )
143
    {
144
        ModelAndView modelAndView = new ModelAndView();
145
        ModelMap modelMap = modelAndView.getModelMap();
146
        boolean isNotRemoveEmpty = isNotRemoveEmptyString == null || !isNotRemoveEmptyString.equals("");
147

    
148
        if (bindingResult.hasErrors()) {
149
            // TODO: 04.05.2020 Error message
150
            modelAndView.setViewName("redirect:/");
151

    
152
            return modelAndView;
153
        }
154

    
155
        if (generateTable != null)
156
        {
157
            prepareForTable(newConfiguration);
158
            BindingResult errors = new BeanPropertyBindingResult(newConfiguration, newConfiguration.getClass().getName());
159
            configurationValidator.validate(newConfiguration, errors);
160
            if (errors.hasErrors()) {
161
                addConfigurationDataIntoModelAndView(newConfiguration, modelAndView, modelMap);
162

    
163
                modelMap.addAttribute(assemblyErrorName, getFullErrorMessage(errors));
164
                modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
165
            }
166
            else {
167
                List<ContingencyTableRow> rows = this.sqlQueryManager.getContingencyTableRow(newConfiguration.getAssembly(),
168
                        newConfiguration.getParametersInConfiguration(), isNotRemoveEmpty, newConfiguration.getTableName());
169

    
170
                if (rows != null) {
171
                    if (rows.isEmpty()) {
172
                        modelMap.addAttribute(assemblyErrorName, "Výsledná tabulka neobsahuje žádné hodnoty (" +
173
                                "SQL dotaz nevrátil žádné řádky)!");
174
                        modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
175
                    }
176
                    else {
177
                        modelMap.addAttribute("configurationID", id);
178
                        modelMap.addAttribute("contingencyTableRows", rows);
179
                        modelMap.addAttribute("isNotRemoveEmpty", isNotRemoveEmpty);
180
                        addConfigurationDataIntoModelAndView(newConfiguration, modelAndView, modelMap);
181
                    }
182
                }
183
                else {
184
                    modelMap.addAttribute(assemblyErrorName, "Vyskytla se chyba v SQL dotazu! Prosím " +
185
                            "zkontrolujte zadané hodnoty filtrů nebo kontaktujte administrátora!");
186
                    modelMap.addAttribute(assemblyTitleName, generateTableTitleText + " " + newConfiguration.getName());
187
                }
188
            }
189
        }
190
        else if (exportXlsx != null)
191
        {
192
            prepareForTable(newConfiguration);
193
            this.exportManager.exportContingencyTable(newConfiguration, isNotRemoveEmpty, response, ExportType.XLSX);
194

    
195
            // Return null, because we want to continue on our page with selected parameters / attributes.
196
            return null;
197
        }
198
        else if (exportPdf != null)
199
        {
200
            prepareForTable(newConfiguration);
201
            this.exportManager.exportContingencyTable(newConfiguration, isNotRemoveEmpty, response, ExportType.PDF);
202

    
203
            // Return null, because we want to continue on our page with selected parameters / attributes.
204
            return null;
205
        }
206
        else if (saveConfiguration != null)
207
        {
208
            Configuration configuration = configurationManager.saveConfiguration(newConfiguration, id);
209

    
210
            initializeFields(configuration);
211

    
212
            redirectAttributes.addFlashAttribute(assemblySuccessName, "Šablona byla úspěšně uložena");
213
            modelAndView.setViewName("redirect:/configuration?configurationID=" + configuration.getId());
214

    
215
        }
216

    
217
        return modelAndView;
218
    }
219

    
220
    /**
221
     * Get method for configuration delete.
222
     * @param id - ID of configuration.
223
     * @param redirectAttributes Attributes.
224
     * @return ModelAndView for index.
225
     */
226
    @GetMapping("/configuration_delete")
227
    public ModelAndView configurationDeleteGet(@RequestParam("configurationID") String id, RedirectAttributes redirectAttributes) {
228
        ModelAndView modelAndView = new ModelAndView("redirect:/");
229

    
230
        Long configurationId = Utils.tryParseLong(id);
231

    
232
        if (configurationId == null) {
233
            redirectAttributes.addFlashAttribute(assemblyErrorName, "Sestavu se nepodařilo odstranit");
234
        }
235

    
236
        boolean success = this.configurationManager.deleteConfiguration(configurationId);
237

    
238
        if (success)
239
        {
240
            redirectAttributes.addFlashAttribute(assemblySuccessName, "Sestava byla úspěšně odstraněna");
241
        }
242
        else
243
        {
244
            redirectAttributes.addFlashAttribute(assemblyErrorName, "Sestavu se nepodařilo odstranit");
245
        }
246

    
247
        return modelAndView;
248
    }
249

    
250
    /**
251
     * Initializes fields of a given configuration
252
     * @param configuration configuration which fields should be initialized
253
     */
254
    private void initializeFields(Configuration configuration) {
255
        for(ParameterInConfiguration parameterInConfiguration : configuration.getParametersInConfiguration()) {
256
            if(parameterInConfiguration.getLocation() == null) {
257
                parameterInConfiguration.setLocation(new Location());
258
            }
259
            if(parameterInConfiguration.getOperator() == null) {
260
                parameterInConfiguration.setOperator(new Operator());
261
            }
262
            if(parameterInConfiguration.getFunctions() == null) {
263
                parameterInConfiguration.setFunctions(new ArrayList<>());
264
            }
265
        }
266
    }
267

    
268
    /**
269
     * Prepares the configuration for contingency table generation. Initializes assembly and parameters of parameters in
270
     * configuration.
271
     * @param configuration configuration to be prepared.
272
     */
273
    private void prepareForTable(Configuration configuration) {
274
        Assembly assembly = assemblyManager.getAssemblyById(configuration.getAssembly().getId());
275
        configuration.setAssembly(assembly);
276

    
277
        for(int i = 0; i < configuration.getParametersInConfiguration().size(); i++) {
278
            ParameterInConfiguration parameterInConfiguration = configuration.getParametersInConfiguration().get(i);
279
            parameterInConfiguration.setParameter(parameterManager.getParameterById(parameterInConfiguration.getParameter().getId()));
280
            parameterInConfiguration.setParameter(assembly.getParameters().get(i));
281
            if (parameterInConfiguration.getLocation() != null) {
282
                parameterInConfiguration.setLocation(locationManager.getLocationById(parameterInConfiguration.getLocation().getId()));
283
            } else {
284
                parameterInConfiguration.setLocation(new Location());
285
            }
286
            parameterInConfiguration.setConfiguration(configuration);
287
        }
288

    
289
        Comparator<ParameterInConfiguration> comparator = Comparator.comparingInt(o -> o.getParameter().getParameterOrder());
290
        configuration.getParametersInConfiguration().sort(comparator);
291
    }
292

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