IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Servlets/JSP Java Discussion :

Erreur lorsque le fichier est lourd


Sujet :

Servlets/JSP Java

  1. #1
    Membre actif
    Inscrit en
    Juin 2005
    Messages
    578
    Détails du profil
    Informations forums :
    Inscription : Juin 2005
    Messages : 578
    Points : 240
    Points
    240
    Par défaut Erreur lorsque le fichier est lourd
    Bonjour

    J'essaie d'insérer un fichier dans ma base de données en suivant l'exemple donné dans le tuto "Créez votre application web avec Java EE". L'insertion marche bien sauf que lorsque la taille du fichier dépasse les 2mo que j'ai spécifiés dans le web.xml, j'ai ce message d'erreur:

    janv. 20, 2015 4:46:03 PM org.apache.catalina.core.StandardWrapperValve invoke
    Grave: "Servlet.service()" pour la servlet FinaliserInscription a généré une exception
    java.lang.NullPointerException
    at forms.FinaliserInscriptionForm.validationCivilite(FinaliserInscriptionForm.java:338)
    at forms.FinaliserInscriptionForm.traiterCivilite(FinaliserInscriptionForm.java:167)
    at forms.FinaliserInscriptionForm.creerCandidat(FinaliserInscriptionForm.java:128)
    at servlets.FinaliserInscription.doPost(FinaliserInscription.java:50)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at filters.PrechargementFilter.doFilter(PrechargementFilter.java:66)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    Voici mes 2 méthodes de validation du fichier:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    public final class FinaliserInscriptionForm {
     
    ....
     
    private String validationPhoto( HttpServletRequest request, String chemin ) throws FormValidationException {
            /*
             * Récupération du contenu du champ image du formulaire. Il faut ici
             * utiliser la méthode getPart().
             */
            String nomFichier = null;
            InputStream contenuFichier = null;
            try {
                Part part = request.getPart( CHAMP_PHOTO );
                nomFichier = getNomFichier( part );
                /*
                 * Si la méthode getNomFichier() a renvoyé quelque chose, il s'agit
                 * donc d'un champ de type fichier (input type="file").
                 */
                if ( nomFichier != null && !nomFichier.isEmpty() ) {
     
                    nomFichier = nomFichier.substring( nomFichier.lastIndexOf( '/' ) + 1 )
                            .substring( nomFichier.lastIndexOf( '\\' ) + 1 );
                    /* Récupération du contenu du fichier */
                    contenuFichier = part.getInputStream();
                    /* Extraction du type MIME du fichier depuis l'InputStream */
                    MimeUtil.registerMimeDetector( "eu.medsea.mimeutil.detector.MagicMimeMimeDetector" );
                    Collection<?> mimeTypes = MimeUtil.getMimeTypes( contenuFichier );
                    /*
                     * Si le fichier est bien une image, alors son en-tête MIME
                     * commence par la chaîne "image"
                     */
                    if ( mimeTypes.toString().startsWith( "image" )  ) {
                        /* Écriture du fichier sur le disque */
                        ecrireFichier( contenuFichier, nomFichier, chemin );
                    } else {
                        throw new FormValidationException( "Le fichier envoyé doit être une image." );
                    }
                }
            } catch ( IllegalStateException e ) {
                /*
                 * Exception retournée si la taille des données dépasse les limites
                 * définies dans la section <multipart-config> de la déclaration de
                 * notre servlet d'upload dans le fichier web.xml
                 */
                e.printStackTrace();
                throw new FormValidationException( "Le fichier envoyé ne doit pas dépasser 2Mo." );
            } catch ( IOException e ) {
                /*
                 * Exception retournée si une erreur au niveau des répertoires de
                 * stockage survient (répertoire inexistant, droits d'accès
                 * insuffisants, etc.)
                 */
                e.printStackTrace();
                throw new FormValidationException( "Erreur de configuration du serveur." );
            } catch ( ServletException e ) {
                /*
                 * Exception retournée si la requête n'est pas de type
                 * multipart/form-data.
                 */
                e.printStackTrace();
                throw new FormValidationException(
                        "Ce type de requête n'est pas supporté, merci d'utiliser le formulaire prévu pour envoyer votre fichier." );
            }
            return nomFichier;
        }
     
        private String  validationCv( HttpServletRequest request, String chemin ) throws FormValidationException {
            /*
             * Récupération du contenu du champ image du formulaire. Il faut ici
             * utiliser la méthode getPart().
             */
            String nomFichier = null;
            InputStream contenuFichier = null;
            try {
                Part part = request.getPart( CHAMP_CV );
                nomFichier = getNomFichier( part );
                /*
                 * Si la méthode getNomFichier() a renvoyé quelque chose, il s'agit
                 * donc d'un champ de type fichier (input type="file").
                 */
                if ( nomFichier != null && !nomFichier.isEmpty() ) {
     
                    nomFichier = nomFichier.substring( nomFichier.lastIndexOf( '/' ) + 1 )
                            .substring( nomFichier.lastIndexOf( '\\' ) + 1 );
                    /* Récupération du contenu du fichier */
                    contenuFichier = part.getInputStream();
                    /* Extraction du type MIME du fichier depuis l'InputStream */
                    MimeUtil.registerMimeDetector( "eu.medsea.mimeutil.detector.MagicMimeMimeDetector" );
                    Collection<?> mimeTypes = MimeUtil.getMimeTypes( contenuFichier );
                    /*
                     * Si le fichier est bien une image, alors son en-tête MIME
                     * commence par la chaîne "image"
                     */
                    if ( mimeTypes.toString().startsWith( "image" ) || mimeTypes.toString().startsWith( "application/pdf" ) || mimeTypes.toString().startsWith( "application/msword" )  ) {
                        /* Écriture du fichier sur le disque */
                        ecrireFichier( contenuFichier, nomFichier, chemin );
                    } else {
                        throw new FormValidationException( "Le fichier envoyé doit être une image, un pdf ou un word." );
                    }
                }
            } catch ( IllegalStateException e ) {
                /*
                 * Exception retournée si la taille des données dépasse les limites
                 * définies dans la section <multipart-config> de la déclaration de
                 * notre servlet d'upload dans le fichier web.xml
                 */
                e.printStackTrace();
                throw new FormValidationException( "Le fichier envoyé ne doit pas dépasser 2Mo." );
            } catch ( IOException e ) {
                /*
                 * Exception retournée si une erreur au niveau des répertoires de
                 * stockage survient (répertoire inexistant, droits d'accès
                 * insuffisants, etc.)
                 */
                e.printStackTrace();
                throw new FormValidationException( "Erreur de configuration du serveur." );
            } catch ( ServletException e ) {
                /*
                 * Exception retournée si la requête n'est pas de type
                 * multipart/form-data.
                 */
                e.printStackTrace();
                throw new FormValidationException(
                        "Ce type de requête n'est pas supporté, merci d'utiliser le formulaire prévu pour envoyer votre fichier." );
            }
            return nomFichier;
        }
    ....
     
    }
    Et voici mon fichier web.xml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
     
    <servlet>
            <servlet-name>Image</servlet-name>
            <servlet-class>servlets.Image</servlet-class>
            <init-param>
                <param-name>chemin</param-name>
                <param-value>/fichiers/images/</param-value>
            </init-param>
        </servlet>
     
    <servlet>
            <servlet-name>FinaliserInscription</servlet-name>
            <servlet-class>servlets.FinaliserInscription</servlet-class>
            <init-param>
                <param-name>chemin</param-name>
                <param-value>/fichiers/images/</param-value>
            </init-param>
            <multipart-config>
                <location>c:/fichiers/images</location>
                <max-file-size>2097152</max-file-size>
                <!-- 2 Mo -->
                <max-request-size>10485760</max-request-size>
                <!-- 5 x 2Mo -->
                <file-size-threshold>1048576</file-size-threshold>
                <!-- 1 Mo -->
            </multipart-config>
        </servlet>
     
    <servlet-mapping>
            <servlet-name>Image</servlet-name>
            <url-pattern>/images/*</url-pattern>
        </servlet-mapping>
     
    </web-app>
    Et voici la servlet Image:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package servlets;
     
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLDecoder;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    public class Image extends HttpServlet {
     
        public static final int TAILLE_TAMPON = 10240; // 10ko
     
        public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
            /*
             * Lecture du paramètre 'chemin' passé à la servlet via la déclaration
             * dans le web.xml
             */
            String chemin = this.getServletConfig().getInitParameter( "chemin" );
            /*
             * Récupération du chemin du fichier demandé au sein de l'URL de la
             * requête
             */
            String fichierRequis = request.getPathInfo();
            /* Vérifie qu'un fichier a bien été fourni */
            if ( fichierRequis == null || "/".equals( fichierRequis ) ) {
                /*
                 * Si non, alors on envoie une erreur 404, qui signifie que la
                 * ressource demandée n'existe pas
                 */
                response.sendError( HttpServletResponse.SC_NOT_FOUND );
                return;
            }
            /*
             * Décode le nom de fichier récupéré, susceptible de contenir des
             * espaces et autres caractères spéciaux, et prépare l'objet File
             */
            fichierRequis = URLDecoder.decode( fichierRequis, "UTF-8" );
            File fichier = new File( chemin, fichierRequis );
            /* Vérifie que le fichier existe bien */
            if ( !fichier.exists() ) {
                /*
                 * Si non, alors on envoie une erreur 404, qui signifie que la
                 * ressource demandée n'existe pas
                 */
                response.sendError( HttpServletResponse.SC_NOT_FOUND );
                return;
            }
            /* Récupère le type du fichier */
            String type = getServletContext().getMimeType( fichier.getName() );
            /*
             * Si le type de fichier est inconnu, alors on initialise un type par
             * défaut
             */
            if ( type == null ) {
                type = "application/octet-stream";
            }
            /* Initialise la réponse HTTP */
            response.reset();
            response.setBufferSize( TAILLE_TAMPON );
            response.setContentType( type );
            response.setHeader( "Content-Length", String.valueOf( fichier.length() ) );
            response.setHeader( "Content-Disposition", "inline; filename=\"" + fichier.getName() + "\"" );
            /* Prépare les flux */
            BufferedInputStream entree = null;
            BufferedOutputStream sortie = null;
            try {
                /* Ouvre les flux */
                entree = new BufferedInputStream( new FileInputStream( fichier ), TAILLE_TAMPON );
                sortie = new BufferedOutputStream( response.getOutputStream(), TAILLE_TAMPON );
                /* Lit le fichier et écrit son contenu dans la réponse HTTP */
                byte[] tampon = new byte[TAILLE_TAMPON];
                int longueur;
                while ( ( longueur = entree.read( tampon ) ) > 0 ) {
                    sortie.write( tampon, 0, longueur );
                }
            } finally {
                try {
                    sortie.close();
                } catch ( IOException ignore ) {
                }
                try {
                    entree.close();
                } catch ( IOException ignore ) {
                }
            }
        }
    }
    Merci

  2. #2
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    Salut,
    et que voulais-tu qu´il affiche?
    peux-tu nous donner le contenu de la methode validationCivilite() dans la classe FinaliserInscriptionForm.java
    en precisant la ligne 338.

    Meric
    Eric

  3. #3
    Membre actif
    Inscrit en
    Juin 2005
    Messages
    578
    Détails du profil
    Informations forums :
    Inscription : Juin 2005
    Messages : 578
    Points : 240
    Points
    240
    Par défaut
    Je voudrais qu'il m'affiche:

    Le fichier envoyé ne doit pas dépasser 1Mo.
    En référence à ceci:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    ...
    catch ( IllegalStateException e ) {
                /*
                 * Exception retournée si la taille des données dépasse les limites
                 * définies dans la section <multipart-config> de la déclaration de
                 * notre servlet d'upload dans le fichier web.xml
                 */
                e.printStackTrace();
                throw new FormValidationException( "Le fichier envoyé ne doit pas dépasser 1Mo." );
    ...
    Voici le contenu de la méthode validationCivilite():

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     private void validationCivilite( String civilite ) throws FormValidationException {
            if ( civilite.equals("Votre choix") ) {
                throw new FormValidationException( "Merci de préciser votre civilité" );
     
            } 
        }
    La ligne 338 fait référence à:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    if ( civilite.equals("Votre choix") ) {
    Merci

  4. #4
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    salut,
    il te dit que le contenu de civilite est null au moment ou tu veux la valider, cela peut en decouler du fait de l´exception levée plus haut du au fichier depassant les 2M.
    et la on a que des bouts de code, donnes nous tout le code de FinaliserInscriptionForm.java, la on pourra suivre ensemble l´evolution et pourquoi il ya cette erreur la et non celle que tu voulais avoir.

    Eric

  5. #5
    Membre actif
    Inscrit en
    Juin 2005
    Messages
    578
    Détails du profil
    Informations forums :
    Inscription : Juin 2005
    Messages : 578
    Points : 240
    Points
    240
    Par défaut
    Ok voici la Class FinaliserInscriptionForm:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
     
    package forms;
     
     
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.Part;
    import beans.Candidat;
    import dao.CandidatDao;
    import dao.DAOException;
    import eu.medsea.mimeutil.MimeUtil;
    import org.jasypt.util.password.ConfigurablePasswordEncryptor;
     
    public final class FinaliserInscriptionForm {
        private static final String CHAMP_CIVILITE       = "civilite";
        private static final String CHAMP_NOM       = "nomCandidat";
        private static final String CHAMP_PRENOM    = "prenomCandidat";
        private static final String CHAMP_JOUR_NAISS       = "jourNaiss";
        private static final String CHAMP_MOIS_NAISS       = "moisNaiss";
        private static final String CHAMP_ANNEE_NAISS       = "anneeNaiss";
        private static final String CHAMP_PAYS       = "pays";
        private static final String CHAMP_ADRESSE   = "adresseCandidat";
        private static final String CHAMP_CODE_POSTAL   = "code_postal";
        private static final String CHAMP_TELEPHONE = "telephoneCandidat";
        private static final String CHAMP_AUTRE_TELEPHONE = "autre_telephone";
        private static final String CHAMP_EMAIL     = "emailCandidat"; 
        private static final String CHAMP_PASSWORD     = "pwdCandidat";
        private static final String CHAMP_CONF = "confirmPwdCandidat";
        private static final String CHAMP_SITUATION_MATR     = "situation";
        private static final String CHAMP_DISPO     = "dispo";
        private static final String CHAMP_DOMAINE     = "domaine";
        private static final String CHAMP_PROFIL     = "profil";
        private static final String CHAMP_AUTRE_DOMAINE_COMPTA     = "autre_domaine_compta";
        private static final String CHAMP_AUTRE_DOMAINE_INFO     = "autre_domaine_info";
        private static final String CHAMP_CDI     = "cdi";
        private static final String CHAMP_CDD     = "cdd";
        private static final String CHAMP_STAGE     = "stage";
        private static final String CHAMP_TEMPO     = "temporaire";
        private static final String CHAMP_PHOTO     = "photo";
        private static final String CHAMP_CV     = "cv";
        private static final int    TAILLE_TAMPON   = 10240;                        // 10ko
        private String              resultat;
        private Map<String, String> erreurs         = new HashMap<String, String>();
        private CandidatDao           candidatDao;
        private static final String ALGO_CHIFFREMENT = "SHA-256";
     
     
        public FinaliserInscriptionForm( CandidatDao candidatDao ) {
            this.candidatDao = candidatDao;
        }
     
        public Map<String, String> getErreurs() {
            return erreurs;
        }
        public String getResultat() {
            return resultat;
        }
        public Candidat creerCandidat( HttpServletRequest request, String chemin ) {
     
            String civilite = getValeurChamp( request, CHAMP_CIVILITE );
            String nom = getValeurChamp( request, CHAMP_NOM );
            String prenom = getValeurChamp( request, CHAMP_PRENOM );
            String jour_naiss = getValeurChamp( request, CHAMP_JOUR_NAISS );
            String mois_naiss = getValeurChamp( request, CHAMP_MOIS_NAISS );
            String annee_naiss = getValeurChamp( request, CHAMP_ANNEE_NAISS );
            String pays = getValeurChamp( request, CHAMP_PAYS );
            String adresse = getValeurChamp( request, CHAMP_ADRESSE );
            String code_postal = getValeurChamp( request, CHAMP_CODE_POSTAL );
            String telephone = getValeurChamp( request, CHAMP_TELEPHONE );
            String autre_tel = getValeurChamp( request, CHAMP_AUTRE_TELEPHONE );
            String email = getValeurChamp( request, CHAMP_EMAIL );
            String pwd = getValeurChamp( request, CHAMP_PASSWORD );
            String confPwd = getValeurChamp( request, CHAMP_CONF );
            String situation_matri = getValeurChamp( request, CHAMP_SITUATION_MATR );
            String dispo = getValeurChamp( request, CHAMP_DISPO );
            String domaine = getValeurChamp( request, CHAMP_DOMAINE );
            String profil = getValeurChamp( request, CHAMP_PROFIL );
            String autre_domaine_compta = getValeurChamp( request, CHAMP_AUTRE_DOMAINE_COMPTA );
            String autre_domaine_info = getValeurChamp( request, CHAMP_AUTRE_DOMAINE_INFO );
            String cdi = getValeurChamp( request, CHAMP_CDI );
            String cdd = getValeurChamp( request, CHAMP_CDD );
            String stage = getValeurChamp( request, CHAMP_STAGE );
            String tempo = getValeurChamp( request, CHAMP_TEMPO );
     
            Candidat candidat = new Candidat();
     
            traiterCivilite( civilite, candidat );
            traiterNom( nom, candidat );
            traiterPrenom( prenom, candidat );
            traiterDateNaiss( jour_naiss,mois_naiss,annee_naiss, candidat );
            traiterPays( pays, candidat );        
            traiterAdresse( adresse, candidat );
            traiterCodePostal(code_postal , candidat );
            traiterTelephone( telephone, candidat );
            traiterAutreTelephone( autre_tel, candidat );
            candidat.setEmail(email);
            traiterPassword(pwd ,confPwd, candidat );
            candidat.setStatutActivation("oui");
            traiterSituationMatri( situation_matri, candidat );
            traiterDispo(dispo , candidat );
            traiterDomaine( domaine, candidat );
            traiterProfil( profil, candidat );
            traiterAutreDomaine(autre_domaine_compta,autre_domaine_info, candidat);
            traiterContrat(cdi, cdd, stage, tempo, candidat); 
            traiterPhoto( candidat, request, chemin );
            traiterCv( candidat, request, chemin );
            try {
                if ( erreurs.isEmpty() ) {
                    candidatDao.creer( candidat,email );
                    System.out.println("lemail est:"+email);
                    candidat = candidatDao.trouver(email);
                    resultat = "Succès de la création de votre compte.";
                } else {
                    resultat = "<p class=\"resultat_echec\">Échec de la création de votre compte. Corrigez les erreurs ci-dessous!</p>";
                }
            } catch ( DAOException e ) {
                setErreur( "imprévu", "Erreur imprévue lors de la création." );
                resultat = "<p class=\"resultat_echec\">Échec de la création de votre profil : une erreur imprévue est survenue, merci de réessayer dans quelques instants.</p>";
                e.printStackTrace();
            }
            return candidat;
        }
     
        private void traiterCivilite( String civilite, Candidat candidat ) {
            try {
                validationCivilite( civilite );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_CIVILITE, e.getMessage() );
            }
            candidat.setCivilite( civilite );
        }
        private void traiterNom( String nom, Candidat candidat ) {
            try {
                validationNom( nom );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_NOM, e.getMessage() );
            }
            candidat.setNom( nom );
        }
        private void traiterPrenom( String prenom, Candidat candidat ) {
            try {
                validationPrenom( prenom );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_PRENOM, e.getMessage() );
            }
            candidat.setPrenom( prenom );
        }
        private void traiterDateNaiss( String jour_naiss, String mois_naiss,String annee_naiss,Candidat candidat ) {
            try {
                validationDateNaiss( jour_naiss,mois_naiss,annee_naiss );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_JOUR_NAISS, e.getMessage() );
            }
            candidat.setJourNaiss( jour_naiss );
            candidat.setMoisNaiss( mois_naiss );
            candidat.setAnneeNaiss( annee_naiss );
        }
     
     
        private void traiterPays( String pays, Candidat candidat ) {
            try {
                validationPays( pays );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_PAYS, e.getMessage() );
            }
            candidat.setPays( pays );
        }
     
        private void traiterAdresse( String adresse, Candidat candidat ) {
            try {
                validationAdresse( adresse );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_ADRESSE, e.getMessage() );
            }
            candidat.setAdresse( adresse );
        }
        private void traiterCodePostal( String code_postal, Candidat candidat ) {
            try {
                validationCodePostal( code_postal );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_CODE_POSTAL, e.getMessage() );
            }
            candidat.setCodePostal( code_postal );
        }
        private void traiterTelephone( String telephone, Candidat candidat ) {
            try {
                validationTelephone( telephone );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_TELEPHONE, e.getMessage() );
            }
            candidat.setTelephone( telephone );
        }
        private void traiterAutreTelephone( String autre_telephone, Candidat candidat ) {
            try {
                validationAutreTelephone( autre_telephone );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_AUTRE_TELEPHONE, e.getMessage() );
            }
            candidat.setAutreTelephone( autre_telephone );
        }
     
       private void traiterPassword( String password,String confirmation, Candidat candidat ) {
            try {
                validationPassword( password, confirmation );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_PASSWORD, e.getMessage() );
                setErreur( CHAMP_CONF, null);
            }
             /*
    *  Utilisation de la bibliothèque Jasypt pour chiffrer le mot de
    passe
    * efficacement.
    *
    * L'algorithme SHA-256 est ici utilisé, avec par défaut un salage* aléatoire et un grand nombre d'itérations de la fonction de hashage.
    *
    * La String retournée est de longueur 56 et contient le hash en
    Base64.
    */
        ConfigurablePasswordEncryptor passwordEncryptor = new    ConfigurablePasswordEncryptor();
        passwordEncryptor.setAlgorithm( ALGO_CHIFFREMENT );
        passwordEncryptor.setPlainDigest( false );
        String motDePasseChiffre = passwordEncryptor.encryptPassword(password );
            candidat.setPassword( motDePasseChiffre );
        }
     
         private void traiterSituationMatri( String situation_matri, Candidat candidat ) {
            try {
                validationSituationMatri( situation_matri );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_SITUATION_MATR, e.getMessage() );
            }
            candidat.setSituationMatr( situation_matri );
        }
         private void traiterDispo( String dispo, Candidat candidat ) {
            try {
                validationDispo( dispo );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_DISPO, e.getMessage() );
            }
            candidat.setDispo( dispo );
        }
          private void traiterDomaine( String domaine, Candidat candidat ) {
            try {
                validationDomaine( domaine );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_DOMAINE, e.getMessage() );
            }
            candidat.setDomaine( domaine );
        }
           private void traiterProfil( String profil, Candidat candidat ) {
            try {
                validationProfil( profil );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_PROFIL, e.getMessage() );
            }
            candidat.setProfil( profil );
        }
     
           private void traiterAutreDomaine( String autre_domaine_compta,String autre_domaine_info, Candidat candidat ) {
            candidat.setAutreDomaineCompta(autre_domaine_compta);
            candidat.setAutreDomaineInfo(autre_domaine_info);
        }
     
           private void traiterContrat( String cdi,String cdd,String stage,String tempo, Candidat candidat ) {
            try {
                validationContrat( cdi, cdd, stage, tempo );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_TEMPO, e.getMessage() );
            }
            candidat.setContratCdi(cdi);
            candidat.setContratCdd(cdd);
            candidat.setContratStage(stage);
            candidat.setContratTempo(tempo);
        }
     
        private void traiterPhoto( Candidat candidat, HttpServletRequest request, String chemin ) {
            String photo = null;
            try {
                photo = validationPhoto( request, chemin );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_PHOTO, e.getMessage() );
            }
            candidat.setPhoto( photo );
        }
     
        private void traiterCv( Candidat candidat, HttpServletRequest request, String chemin ) {
            String cv = null;
            try {
                cv = validationCv( request, chemin );
            } catch ( FormValidationException e ) {
                setErreur( CHAMP_CV, e.getMessage() );
            }
            candidat.setCv( cv );
        }
     
         private void validationCivilite( String civilite ) throws FormValidationException {
            if ( civilite.equals("Votre choix") ) {
                throw new FormValidationException( "Merci de préciser votre civilité" );
     
            } 
        }
         private void validationNom( String nom ) throws FormValidationException {
            if ( nom != null ) {
                if ( nom.length() < 2 ) {
                    throw new FormValidationException( "Le nom d'utilisateur doit contenir au moins 2 caractères." );
                }
            } else {
                throw new FormValidationException( "Merci d'entrer un nom d'utilisateur." );
            }
        }
        private void validationPrenom( String prenom ) throws FormValidationException {
            if ( prenom != null ) {
                if ( prenom.length() < 2 ) {
                    throw new FormValidationException( "Le prénom d'utilisateur doit contenir au moins 2 caractères." );
                }
            } else {
                throw new FormValidationException( "Merci d'entrer un prénom d'utilisateur." );
            }
        }
     
        private void validationDateNaiss( String jour_naiss,String mois_naiss,String annee_naiss ) throws FormValidationException {
            if ( jour_naiss.equals("Jour")) {
                throw new FormValidationException( "Merci de préciser le jour!" );
     
            } else
            {
             if ( mois_naiss.equals("Mois") ) {
                throw new FormValidationException( "Merci de préciser le mois!" );
     
                }
                 else
            {
             if ( annee_naiss.equals("Annee") ) {
                throw new FormValidationException( "Merci de préciser l'année!" );
     
                }
            }
            }
        }
     
        private void validationPays( String pays ) throws FormValidationException {
            if ( pays.equals("Votre choix") ) {
                throw new FormValidationException( "Merci de préciser votre pays" );
     
            } 
        }
        private void validationAdresse( String adresse ) throws FormValidationException {
            if ( adresse != null ) {
                if ( adresse.length() < 10 ) {
                    throw new FormValidationException( "Votre adresse doit contenir au moins 10 caractères." );
                }
            } else {
                throw new FormValidationException( "Merci d'entrer une adresse." );
            }
        }
        private void validationCodePostal( String code_postal ) throws FormValidationException {
            if ( code_postal != null ) {
                if ( code_postal.length() < 3 ) {
                    throw new FormValidationException( "Votre code postal doit contenir au moins 3 caractères." );
                }
            } 
        }
        private void validationTelephone( String telephone ) throws FormValidationException {
            if ( telephone != null ) {
                if ( !telephone.matches( "^\\d+$" ) ) {
                    throw new FormValidationException( "Le numéro de téléphone doit uniquement contenir des chiffres." );
                } else if ( telephone.length() < 4 ) {
                    throw new FormValidationException( "Le numéro de téléphone doit contenir au moins 4 chiffres." );
                }
            } else {
                throw new FormValidationException( "Merci d'entrer un numéro de téléphone." );
            }
        }
        private void validationAutreTelephone( String autre_telephone ) throws FormValidationException {
            if ( autre_telephone != null ) {
                if ( !autre_telephone.matches( "^\\d+$" ) ) {
                    throw new FormValidationException( "Le numéro de téléphone doit uniquement contenir des chiffres." );
                } else if ( autre_telephone.length() < 4 ) {
                    throw new FormValidationException( "Le numéro de téléphone doit contenir au moins 4 chiffres." );
                }
            } 
        }
     
         private void validationPassword( String password, String confirmation ) throws FormValidationException {
            if ( password != null ) {
                        if ( confirmation != null )
                            {
                         if ( !password.equals( confirmation ) ) {
                             throw new FormValidationException( "Les mots de passe entrés sont différents, merci de les saisir à nouveau." );
                                 }
                                 else if ( password.length() < 5 ) {
                                   throw new FormValidationException( "Votre mot de passe doit contenir au moins 5 caractères." );
                                            }
                         }
                        else {
                throw new FormValidationException( "Vous n'avez pas confirmé votre mot de passe." );
            }
            } else {
                throw new FormValidationException( "Merci d'entrer un mot de passe." );
            }
        }
     
        private void validationSituationMatri( String situation_matri ) throws FormValidationException {
            if ( situation_matri.equals("Votre choix") ) {
                throw new FormValidationException( "Merci de préciser votre situation matrimoniale" );
     
            } 
        }
        private void validationDispo( String dispo ) throws FormValidationException {
            if ( dispo.equals("Votre choix") ) {
                throw new FormValidationException( "Merci de préciser votre disponibilité" );
     
            } 
        }
        private void validationDomaine( String domaine ) throws FormValidationException {
            if ( domaine.equals("Votre choix") ) {
                throw new FormValidationException( "Merci de préciser votre domaine" );
     
            } 
        }
         private void validationProfil( String profil ) throws FormValidationException {
            if ( profil != null ) {
                if ( profil.length() < 2 ) {
                    throw new FormValidationException( "Votre profil doit contenir au moins 2 caractères." );
                }
            } else {
                throw new FormValidationException( "Merci d'entrer votre profil." );
            }
        }
         private void validationContrat( String cdi, String cdd, String stage, String tempo ) throws FormValidationException {
            if ( cdi == null && cdd == null && stage == null && tempo == null) {
                throw new FormValidationException( "Merci de préciser au moins un type de contrat" );
     
            } 
     
        }
     
         private String validationPhoto( HttpServletRequest request, String chemin ) throws FormValidationException {
            /*
             * Récupération du contenu du champ image du formulaire. Il faut ici
             * utiliser la méthode getPart().
             */
            String nomFichier = null;
            InputStream contenuFichier = null;
            try {
                Part part = request.getPart( CHAMP_PHOTO );
                nomFichier = getNomFichier( part );
                /*
                 * Si la méthode getNomFichier() a renvoyé quelque chose, il s'agit
                 * donc d'un champ de type fichier (input type="file").
                 */
                if ( nomFichier != null && !nomFichier.isEmpty() ) {
     
                    nomFichier = nomFichier.substring( nomFichier.lastIndexOf( '/' ) + 1 )
                            .substring( nomFichier.lastIndexOf( '\\' ) + 1 );
                    /* Récupération du contenu du fichier */
                    contenuFichier = part.getInputStream();
                    /* Extraction du type MIME du fichier depuis l'InputStream */
                    MimeUtil.registerMimeDetector( "eu.medsea.mimeutil.detector.MagicMimeMimeDetector" );
                    Collection<?> mimeTypes = MimeUtil.getMimeTypes( contenuFichier );
                    /*
                     * Si le fichier est bien une image, alors son en-tête MIME
                     * commence par la chaîne "image"
                     */
                    if ( mimeTypes.toString().startsWith( "image" )  ) {
                        /* Écriture du fichier sur le disque */
                        ecrireFichier( contenuFichier, nomFichier, chemin );
                    } else {
                        throw new FormValidationException( "Le fichier envoyé doit être une image." );
                    }
                }
            } catch ( IllegalStateException e ) {
                /*
                 * Exception retournée si la taille des données dépasse les limites
                 * définies dans la section <multipart-config> de la déclaration de
                 * notre servlet d'upload dans le fichier web.xml
                 */
                e.printStackTrace();
                throw new FormValidationException( "Le fichier envoyé ne doit pas dépasser 1Mo." );
            } catch ( IOException e ) {
                /*
                 * Exception retournée si une erreur au niveau des répertoires de
                 * stockage survient (répertoire inexistant, droits d'accès
                 * insuffisants, etc.)
                 */
                e.printStackTrace();
                throw new FormValidationException( "Erreur de configuration du serveur." );
            } catch ( ServletException e ) {
                /*
                 * Exception retournée si la requête n'est pas de type
                 * multipart/form-data.
                 */
                e.printStackTrace();
                throw new FormValidationException(
                        "Ce type de requête n'est pas supporté, merci d'utiliser le formulaire prévu pour envoyer votre fichier." );
            }
            return nomFichier;
        }
     
        private String  validationCv( HttpServletRequest request, String chemin ) throws FormValidationException {
            /*
             * Récupération du contenu du champ image du formulaire. Il faut ici
             * utiliser la méthode getPart().
             */
            String nomFichier = null;
            InputStream contenuFichier = null;
            try {
                Part part = request.getPart( CHAMP_CV );
                nomFichier = getNomFichier( part );
                /*
                 * Si la méthode getNomFichier() a renvoyé quelque chose, il s'agit
                 * donc d'un champ de type fichier (input type="file").
                 */
                if ( nomFichier != null && !nomFichier.isEmpty() ) {
     
                    nomFichier = nomFichier.substring( nomFichier.lastIndexOf( '/' ) + 1 )
                            .substring( nomFichier.lastIndexOf( '\\' ) + 1 );
                    /* Récupération du contenu du fichier */
                    contenuFichier = part.getInputStream();
                    /* Extraction du type MIME du fichier depuis l'InputStream */
                    MimeUtil.registerMimeDetector( "eu.medsea.mimeutil.detector.MagicMimeMimeDetector" );
                    Collection<?> mimeTypes = MimeUtil.getMimeTypes( contenuFichier );
                    /*
                     * Si le fichier est bien une image, alors son en-tête MIME
                     * commence par la chaîne "image"
                     */
                    if ( mimeTypes.toString().startsWith( "image" ) || mimeTypes.toString().startsWith( "application/pdf" ) || mimeTypes.toString().startsWith( "application/msword" )  ) {
                        /* Écriture du fichier sur le disque */
                        ecrireFichier( contenuFichier, nomFichier, chemin );
                    } else {
                        throw new FormValidationException( "Le fichier envoyé doit être une image, un pdf ou un word." );
                    }
                }
            } catch ( IllegalStateException e ) {
                /*
                 * Exception retournée si la taille des données dépasse les limites
                 * définies dans la section <multipart-config> de la déclaration de
                 * notre servlet d'upload dans le fichier web.xml
                 */
                e.printStackTrace();
                throw new FormValidationException( "Le fichier envoyé ne doit pas dépasser 1Mo." );
            } catch ( IOException e ) {
                /*
                 * Exception retournée si une erreur au niveau des répertoires de
                 * stockage survient (répertoire inexistant, droits d'accès
                 * insuffisants, etc.)
                 */
                e.printStackTrace();
                throw new FormValidationException( "Erreur de configuration du serveur." );
            } catch ( ServletException e ) {
                /*
                 * Exception retournée si la requête n'est pas de type
                 * multipart/form-data.
                 */
                e.printStackTrace();
                throw new FormValidationException(
                        "Ce type de requête n'est pas supporté, merci d'utiliser le formulaire prévu pour envoyer votre fichier." );
            }
            return nomFichier;
        }
        /*
         * Ajoute un message correspondant au champ spécifié à la map des erreurs.
         */
        private void setErreur( String champ, String message ) {
            erreurs.put( champ, message );
        }
        /*
         * Méthode utilitaire qui retourne null si un champ est vide, et son contenu
         * sinon.
         */
        private static String getValeurChamp( HttpServletRequest request, String nomChamp ) {
            String valeur = request.getParameter( nomChamp );
            if ( valeur == null || valeur.trim().length() == 0 ) {
                return null;
            } else {
                return valeur;
            }
        }
        /*
         * Méthode utilitaire qui a pour unique but d'analyser l'en-tête
         * "content-disposition", et de vérifier si le paramètre "filename" y est
         * présent. Si oui, alors le champ traité est de type File et la méthode
         * retourne son nom, sinon il s'agit d'un champ de formulaire classique et
         * la méthode retourne null.
         */
        private static String getNomFichier( Part part ) {
            /* Boucle sur chacun des paramètres de l'en-tête "content-disposition". */
            for ( String contentDisposition : part.getHeader( "content-disposition" ).split( ";" ) ) {
                /* Recherche de l'éventuelle présence du paramètre "filename". */
                if ( contentDisposition.trim().startsWith( "filename" ) ) {
                    /*
                     * Si "filename" est présent, alors renvoi de sa valeur,
                     * c'est-à-dire du nom de fichier sans guillemets.
                     */
                    return contentDisposition.substring( contentDisposition.indexOf( '=' ) + 1 ).trim().replace( "\"", "" );
                }
            }
            /* Et pour terminer, si rien n'a été trouvé... */
            return null;
        }
        /*
         * Méthode utilitaire qui a pour but d'écrire le fichier passé en paramètre
         * sur le disque, dans le répertoire donné et avec le nom donné.
         */
        private void ecrireFichier( InputStream contenuFichier, String nomFichier, String chemin )
                throws FormValidationException {
            /* Prépare les flux. */
            BufferedInputStream entree = null;
            BufferedOutputStream sortie = null;
            try {
                /* Ouvre les flux. */
                entree = new BufferedInputStream( contenuFichier, TAILLE_TAMPON );
                sortie = new BufferedOutputStream( new FileOutputStream( new File( chemin + nomFichier ) ),
                        TAILLE_TAMPON );
                /*
                 * Lit le fichier reçu et écrit son contenu dans un fichier sur le
                 * disque.
                 */
                byte[] tampon = new byte[TAILLE_TAMPON];
                int longueur = 0;
                while ( ( longueur = entree.read( tampon ) ) > 0 ) {
                    sortie.write( tampon, 0, longueur );
                }
            } catch ( Exception e ) {
                throw new FormValidationException( "Erreur lors de l'écriture du fichier sur le disque." );
            } finally {
                try {
                    sortie.close();
                } catch ( IOException ignore ) {
                }
                try {
                    entree.close();
                } catch ( IOException ignore ) {
                }
            }
        }
    }

Discussions similaires

  1. événement lorsqu'un fichier est ouvert.
    Par minirop dans le forum Windows
    Réponses: 2
    Dernier message: 01/08/2011, 21h04
  2. Que faire lorsque le fichier est vide?
    Par bsangoku dans le forum Débuter
    Réponses: 6
    Dernier message: 18/01/2010, 13h46
  3. [mySQL 5] Eviter l'erreur lorsqu'un champ est inexistant
    Par fanfouer dans le forum Requêtes
    Réponses: 2
    Dernier message: 11/03/2008, 10h10
  4. Une msgBox lorsque le fichier est en lecture seule..
    Par ncazanav dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 26/01/2008, 12h47
  5. instruction SaveAs : plantage de l'application lorsque le fichier est créé
    Par Aimé_Lacapelle dans le forum Macros et VBA Excel
    Réponses: 5
    Dernier message: 31/08/2007, 19h43

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo