Kenmegne
7 days ago b3d0580439b9a00c7eb918085de1694151066004
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.megatim.fdxconvert.controller;
 
import com.megatim.module.compression.impl.JavaZipZip4Impl;
import com.megatim.module.encryption.impl.AESImpl;
import com.megatimfx.common.abstracts.AbstractEditDialogController;
import com.megatimfx.common.enums.TypeOperation;
import com.megatimfx.common.utils.ViewLoaderUtil;
import com.megatimfx.components.customdialogs.AlertMessageUtil;
import com.megatimfx.components.dialogs.NotificationDialog;
import com.megatimfx.components.dialogs.NotificationType;
import com.megatim.fdxconvert.dao.ValidateurDAO;
import com.megatim.fdxconvert.exceptions.ConfigException;
import com.megatim.fdxconvert.forms.ValidateurEditFormController;
import com.megatim.fdxconvert.model.Configuration;
import com.megatim.fdxconvert.model.TypeFichier;
import com.megatim.fdxconvert.model.Validateur;
import com.megatim.fdxconvert.service.ConfigurationService;
import com.megatim.fdxconvert.util.ParserUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
 
/**
 *
 * @author STEPHANIE
 */
public class ValidateurEditDialogController extends AbstractEditDialogController<Validateur> {
 
    private ValidateurEditFormController validateurEditFormController;
    private final String UNZIP_DIR = "UNZIP_DIR";
    Boolean result;
 
    @Override
    public String getTitle() {
        getEditButton().setText("Importer");
        return "Importer le validateur d'un type fichier";
    }
 
    @Override
    public Pane getContentFormPane() throws IOException {
        return ViewLoaderUtil.getPaneFromFxmlFile(validateurEditFormController.getClass().getResource("ValidateurEditForm.fxml"), validateurEditFormController);
 
    }
 
    @Override
    public Object getContentFormController() {
        return validateurEditFormController;
    }
 
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        validateurEditFormController = new ValidateurEditFormController();
        super.initialize(url, rb);
    }
 
    @Override
    public String getConfirmationMessage() {
        return "Validateur du typefichier " + getCurrentObject().getCodeTypeFichier() + " importé avec succès !";
    }
 
    @Override
    public boolean beforeSave(ActionEvent event) {
        result = false;
        boolean proceed = super.beforeSave(event);
 
        if (validateurEditFormController.getProtegeCheckBox().isSelected()) {
            proceed = proceed && validateurEditFormController.getKeyConfirmationField() != null
                    && validateurEditFormController.getKeyToDecryptField() != null;
        }
 
        if (proceed && getTypeOperation().equals(TypeOperation.ADD)) {
            Node source = (Node) event.getSource();
            Stage parentStage = (Stage) source.getScene().getWindow();
 
            Validateur validateur = getCurrentObject();
            Configuration config = ConfigurationService.getInstance().getCurrentConfig();
            File decryptedFile = null;
 
            try {
                if (validateur.isProtege()) {
                    Optional<Validateur> exist = ValidateurDAO.findByCodeTypeFichier(validateur.getCodeTypeFichier());
 
                    if (!exist.isPresent()) {
                        File fileToUnzip = new File(validateur.getFilePath());
                        unzip(fileToUnzip, config);
                        decryptedFile = decrypt(validateur, config, fileToUnzip);
                        validateur.setFilePath(decryptedFile.getAbsolutePath());
                        setContent(validateur);
 
                        decryptedFile.deleteOnExit();
                        result = true;
                    } else {
                        NotificationDialog notificationDialog = new NotificationDialog(
                                "Validateur du typefichier " + validateur.getCodeTypeFichier() + " déjà enregistré. Bien vouloir supprimer l'existant avant d'effectuer cette action",
                                NotificationType.WARNING, parentStage);
                        notificationDialog.showNotification();
                        result = false;
                    }
                } else {
                    setContent(validateur);
                    result = true;
                }
            } catch (Exception th) {
 
                if (th instanceof javax.crypto.BadPaddingException || th instanceof java.security.spec.InvalidKeySpecException
                        || th instanceof java.security.InvalidKeyException) {
 
                    decryptedFile.deleteOnExit();
 
                    NotificationDialog notificationDialog = new NotificationDialog(
                            "Echec décryptage : La clé fournie n'est pas la bonne ",
                            NotificationType.ERROR,
                            parentStage
                    );
                    notificationDialog.showNotification();
                } else if (th instanceof ConfigException) {
                    NotificationDialog notificationDialog = new NotificationDialog(
                            th.getMessage(), NotificationType.ERROR, parentStage);
                    notificationDialog.showNotification();
                } else {
                    AlertMessageUtil.showAlertException(th, "Une exception s'est produite pendant le décryptage du fichier", "Erreur");
                }
            } finally {
                if (config != null) {
                    File unzipDir = new File(config.getValidatorsDir(), UNZIP_DIR);
 
                    if (unzipDir.exists() && unzipDir.isDirectory()) {
                        List<File> liste = Arrays.asList(unzipDir.listFiles());
                        liste.forEach(f -> f.deleteOnExit());
                    }
                }
            }
        }
 
        return result;
    }
 
    private void unzip(File fileToUnzip, Configuration config) throws Exception {
        JavaZipZip4Impl zip4Impl = new JavaZipZip4Impl();
 
        if (config == null) {
            throw new ConfigException("Bien vouloir configurer les répertoires  avant avant d'effectuer cette action");
        }
 
        File unzipDir = new File(config.getValidatorsDir(), UNZIP_DIR);
 
        if (!unzipDir.exists()) {
            unzipDir.mkdir();
        }
 
        Arrays.asList(unzipDir.listFiles()).forEach(f -> f.deleteOnExit());
        zip4Impl.unZipFile(fileToUnzip, unzipDir);
    }
 
    private File decrypt(Validateur val, Configuration config, File fileToUnzip) throws Exception {
        AESImpl aes = new AESImpl();
        File unzipDir = new File(config.getValidatorsDir(), UNZIP_DIR);
        String fileName = fileNameWithoutExtension(fileToUnzip);
        File inputFile = new File(unzipDir.getAbsolutePath(), fileName + ".xml");
        File outputFile = new File(config.getValidatorsDir(), inputFile.getName());
        aes.decryptFile(val.getKeyToDecrypt(), val.getKeyLength(), inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
 
        inputFile.deleteOnExit();
 
        return outputFile;
    }
 
    private void setContent(Validateur validateur) throws Exception {
        TypeFichier typeFichier = getCurrentObject().getTypeFichier();
        getCurrentObject().setConvertDataBeforeValidation(ParserUtils.isConvertDataBeforeValidation(new File(validateur.getFilePath())));
        byte[] content = FileUtils.readFileToByteArray(new File(validateur.getFilePath()));
        getCurrentObject().setContent(content);
        getCurrentObject().setCodeTypeFichier(typeFichier.getCode());
    }
 
    private String fileNameWithoutExtension(File file) {
        String name = file.getName();
        int index = name.lastIndexOf(".");
        String fileName = name.substring(0, index);
 
        return fileName;
    }
 
    @Override
    public String getConfirmationDialogMessage() {
        return "Le validateur du typefichier " + getCurrentObject().getCodeTypeFichier() + " a été importé avec succès.";
    }
}