Kenmegne
7 days ago 23a46b4be35277e06ec89f48730eeb694e686be8
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package com.megatim.fdxconsultation.tools;
 
import com.megatim.export.excel.Export;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.lang.annotation.Annotation;
import com.megatim.fdxconsultation.tools.context.AppCommonContext;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author ABEGA
 */
public class CommonTools {
 
    /**
     * Permet de generer des nomre aleatorement
     *
     * @return
     */
    public static synchronized String genererChaineAleatoire() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String nombre = format.format(new Date()) + String.valueOf((int) (Math.random() * 1000000000));
        return nombre;
    }
    
    /**
     * Permet d'exporter en excel dans repertoire donn�
     *
     * @param datas
     * @param repertoireGeneration
     * @return
     */
    public static File exporterEnExcel(List datas, File fichier) {
 
        try {
 
            //On effectue l'export
            Export.exportExcel(datas, fichier.getAbsolutePath());
 
        } catch (Exception ex) {
 
            //On affiche l'erreur
            ex.printStackTrace();
 
        }
 
        return fichier;
    }
    
    /**
     * Methode permettant de
     * @param headers
     * @param request
     * @return 
     */
    public static Map<String, String> recupererInfosRequete(HttpHeaders headers, @Context HttpServletRequest request) {
        
        //Variables
        Map<String, String> map = new HashMap<String, String>();
        
        // Adresse IP du client
        String clientIp = request.getRemoteAddr();
 
        // En-tête User-Agent
        String userAgent = headers.getHeaderString("User-Agent");
        
        // Methode
        String methode = request.getMethod();
        
        // Path
        String path = request.getRequestURI();
        
        //On ajoute les informations dans la map
        map.put(AppCommonContext.REQUETE_HTTP_ADRESSE_IP, clientIp);
        map.put(AppCommonContext.REQUETE_HTTP_CLIENT, userAgent);
        map.put(AppCommonContext.REQUETE_HTTP_METHODE, methode);        
        map.put(AppCommonContext.REQUETE_HTTP_PATH, path.toLowerCase().replaceAll(AppCommonContext.PATH_BASE_MODULE_CONSULTATION.toLowerCase(), ""));
        
        //On retourne la map
        return map;
        
    }
    
    /**
     * Permet d'ajouter des jours à une date donnée
     * @param date
     * @param nbreJour
     * @return 
     */
    public static Date addDay(Date date, int nbreJour){
        
        //Varaibles
        Calendar cal = Calendar.getInstance();
        
        //On ajoute la date
        cal.setTime(date);
        
        //On ajoute la date
        cal.add(Calendar.DATE, nbreJour);
        
        // convert calendar to date
        Date modifiedDate = cal.getTime();
        
        return modifiedDate;
    }
    
    /**
     * Permet de formater les chiffres avec un zero devant
     * @return 
     */
    public static String formaterChiffreAvecZeroDevant(long chiffre) {
        
        //Si nombre
        if(chiffre >= 10){
            return String.valueOf(chiffre);
        }else{
            return "0"+String.valueOf(chiffre);
        }
        
    }
    
    /**
     * Renvoie les champs de la liste qui n'appartiennent pas à l'entité
     *
     * @param classe
     * @param fieldsToCheck
     * @return
     */
    public static List<String> checkIfEntityField(Class<?> classe, List<String> fieldsToCheck) {
        List<String> fieldsNotFound = new ArrayList<>();
       Set<String> fieldsSet = Arrays.asList(classe.getDeclaredFields()).stream().map(f ->f.getName()).collect(Collectors.toSet());
        
        fieldsToCheck.stream().forEach(s -> {
            System.out.println("field to check "+s);
            if (!fieldsSet.contains(s)) {
                fieldsNotFound.add(s);
            }
        });
        return fieldsNotFound;
    }
 
    /**
     * Permet de hacher le mot de passe
     *
     * @param password
     * @return
     */
    public static String encryptPassword(String password) {
 
        try {
 
            int iterations = 1000;
            char[] chars = password.toCharArray();
            byte[] salt = getSalt();
 
            PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8);
            SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
 
            byte[] hash = skf.generateSecret(spec).getEncoded();
            return iterations + ":" + toHex(salt) + ":" + toHex(hash);
 
        } catch (Exception ex) {
 
            //On affiche le message d'errreur
            ex.printStackTrace();
 
        }
 
        return null;
    }
 
    /**
     * Permet de charger des classes qui ont une annotation pr�cise
     *
     * @param pkgName
     * @param annotation
     * @return
     */
    public static List<Annotation> getAnnotations(final String pkgName, String annotation) {
 
        //Variables
        List<Class<?>> classRefs = new ArrayList<>();
 
        List<Annotation> annotations = new ArrayList<>();
 
        try ( ScanResult scanResult = new ClassGraph().acceptPackages(pkgName).enableAllInfo().scan()) {
 
            //On recup�re les classes annot�es
            ClassInfoList liste = scanResult.getClassesWithAnnotation(annotation);
 
            //On charge les classes
            classRefs = liste.loadClasses();
 
            //On parcourt les classes
            for (Class<?> classe : classRefs) {
 
                //On parcourt les annotations
                for (Annotation annotationDeclaree : classe.getDeclaredAnnotations()) {
 
                    //On ajoute l'annotation
                    annotations.add(annotationDeclaree);
 
                }
 
            }
 
        } catch (Exception e) {
 
            //On affiche les traces
            e.printStackTrace();
 
        }
 
        return annotations;
    }
 
    /**
     * Permet de charger des classes qui ont une annotation pr�cise
     *
     * @param pkgName
     * @param annotation
     * @return
     */
    public static List<Class<?>> getAnnotatedClasses(final String pkgName, String annotation) {
 
        //Variables
        List<Class<?>> classRefs = new ArrayList<>();
 
        try ( ScanResult scanResult = new ClassGraph().acceptPackages(pkgName).enableAllInfo().scan()) {
 
            //On recup�re les classes annot�es
            ClassInfoList liste = scanResult.getClassesWithAnnotation(annotation);
 
            //On charge les classes
            classRefs = liste.loadClasses();
 
        } catch (Exception e) {
 
            //On affiche les traces
            e.printStackTrace();
 
        }
 
        return classRefs;
    }
 
    /**
     * Permet de valider le mot de passe
     *
     * @param originalPassword
     * @param storedPassword
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static boolean validerMotDePasse(String originalPassword, String storedPassword)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        String[] parts = storedPassword.split(":");
        int iterations = Integer.parseInt(parts[0]);
 
        byte[] salt = fromHex(parts[1]);
        byte[] hash = fromHex(parts[2]);
 
        PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(),
                salt, iterations, hash.length * 8);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] testHash = skf.generateSecret(spec).getEncoded();
 
        int diff = hash.length ^ testHash.length;
        for (int i = 0; i < hash.length && i < testHash.length; i++) {
            diff |= hash[i] ^ testHash[i];
        }
        return diff == 0;
    }
 
    /**
     * Retourne le chemin du serveur
     *
     * @return
     */
    public static String getCurrentDirectoryOfServer() {
 
        //On recup�re le chemin du repertoire
        AppCommonContext.REPERTOIRE_SERVEUR = getCurrentDirectory().getParent() + File.separator + "standalone" + File.separator + "data" + File.separator + "donnees";
 
        return AppCommonContext.REPERTOIRE_SERVEUR;
    }
 
    /**
     * Retourne le chemin du serveur
     *
     * @return
     */
    public static String getCurrentTempDirectoryOfServer() {
 
        //On recup�re le chemin du repertoire
        AppCommonContext.REPERTOIRE_SERVEUR = getCurrentDirectory().getParent() + File.separator + "standalone" + File.separator + "tmp";
 
        return AppCommonContext.REPERTOIRE_SERVEUR;
    }
 
    /**
     * Retourn le chemin courant
     *
     * @return
     */
    public static File getCurrentDirectory() {
        String fileName = (String) System.getProperties().get("user.dir");
        return new File(fileName);
    }
 
    public static Properties loadProperties(String filename) {
        Properties properties = new Properties();
 
        try {
 
            //On charge le fichier de config
            properties.load(new FileInputStream(filename));
 
        } catch (Exception ex) {
 
            //On affiche l'erreur
            ex.printStackTrace();
 
        }
 
        return properties;
    }
 
    /**
     * Permet de convertir un hexadeicmal en tableau de byte
     *
     * @param hex
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static byte[] fromHex(String hex) throws NoSuchAlgorithmException {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }
 
    /**
     *
     * @param array
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String toHex(byte[] array) throws NoSuchAlgorithmException {
        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
 
        int paddingLength = (array.length * 2) - hex.length();
        if (paddingLength > 0) {
            return String.format("%0" + paddingLength + "d", 0) + hex;
        } else {
            return hex;
        }
    }
 
    /**
     *
     * @return @throws NoSuchAlgorithmException
     */
    public static byte[] getSalt() throws NoSuchAlgorithmException {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[16];
        sr.nextBytes(salt);
        return salt;
    }
 
}