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

Format d'échange (XML, JSON...) Java Discussion :

Page Sources Java libres - participez ici [Sources]


Sujet :

Format d'échange (XML, JSON...) Java

  1. #21
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Voici maintenant un encrypteur beaucoup plus puissant et sécurisé que le chiffrement de César.

    Ce cryptage est dit symétrique, c'est-à-dire que la même clé sert à crypter et à décrypter. La faiblesse de ces chiffres symétriques réside dans la distribution des clés. Je vous épargne les détails, sachez néanmoins que c'est un algorithme très puissant, et que même s'il présente une faiblesse pratique, il est théoriquement incassable.

    [EDIT]
    Dernière mise à jour le 16/10/2007 (modélisatio et sécurité). Vous avez besoin des classes FileEncryptor et CipherEcryptor pour la faire fonctionner.
    [/EDIT]

    Voici l'encrypteur :

    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
     
    package org.cosmopol.crypto;
     
    import java.io.EOFException;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Provider;
    import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.ShortBufferException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.BadPaddingException;
     
    /**
     * This class provides methods to generate keys, crypt or decrypt stream and
     * files with a symetric-key algorithm such as the AES, DES and so on.
     * @author Absil Romain
     */
    public class SymetricEncryptor extends FileEncryptor
    {
        private SecretKey key;
        private String algorithm;
     
        /**
         * The constant for the AES symetric-key algorithm.
         **/
        public static final String AES = "AES";
     
        /**
         * The constant for the DES symetric-key algorithm.
         **/
        public static final String DES = "DES";
     
        /**
         * The constant for the triple DES (DES-EDE) symetric-key algorithm.
         **/
        public static final String DES_EDE = "DESede";
     
        /**
         * The constant for the Blowfish symetric-key algorithm.
         **/
        public static final String BLOWFISH = "Blowfish";
     
        /**
         * The constant for the RC2 symetric-key algorithm.
         **/
        public static final String RC2 = "RC2";
     
        /**
         * The constant for the Arcfour symetric-key algorithm.
         **/
        public static final String ARCFOUR = "RC4";
     
        /**
         * Constructs a new symetric encryptor with the specified key.<br>
         * @param key the secret key to crypt or decrypt datas.
         **/
        public SymetricEncryptor(SecretKey key)
        {
            this.key = key;
            this.algorithm = key.getAlgorithm();
        }
     
        /**
         * Constructs a new symetric encryptor with the specified key file name 
         * containing the secret key.
         * @param keyFileName the name of the file containing the secret key.
         * @throws java.io.FileNotFoundException if the file containing the secret
         * key doesn't exist.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * key.
         * @throws java.lang.ClassNotFoundException if the class of the key is
         * unknown.
         **/
        public SymetricEncryptor(String keyFileName)
            throws FileNotFoundException, IOException, ClassNotFoundException
        {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyFileName));
            this.key = (SecretKey)in.readObject();
            this.algorithm = key.getAlgorithm();
            in.close();
        }
     
        /**
         * Constructs a new symetric encryptor with the specified key file 
         * containing the secret key.
         * @param keyFile the file containing the secret key.
         * @throws java.io.FileNotFoundException if the file containing the secret
         * key doesn't exist.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * key.
         * @throws java.lang.ClassNotFoundException if the class of the key is
         * unknown.
         */
        public SymetricEncryptor(File keyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException
        {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyFile));
            this.key = (SecretKey)in.readObject();
            this.algorithm = key.getAlgorithm();
            in.close();
        }
     
        /**
         * Returns the secret key of the underlying symetric encryptor.
         * @return the secret key of the underlying symetric encryptor.
         **/
        public SecretKey getSecretKey()
        {
            return this.key;
        }
     
        /**
         * Returns the algorithm's name of the underlying symetric encryptor.
         * @return the algorithm's name of the underlying symetric encryptor.
         **/
        public String getAlgorithm()
        {
            return this.algorithm;
        }
     
        /**
         * Returns a new instance of SymetricEncryptor generated with the specified
         * algorithm.
         * @param algorithm the algorithm of the symetric encryptor you want to be
         * returned.
         * @return a new instance of SymetricEncryptor generated with the specified
         * algorithm.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         */
        public static SymetricEncryptor getInstance(String algorithm) 
            throws NoSuchAlgorithmException
        {
            return new SymetricEncryptor(generateKey(algorithm));
        }
     
        /**
         * Returns a new instance of SymetricEncryptor generated with the specified
         * algorithm and provider name.
         * @param algorithm the algorithm of the symetric encryptor you want to be
         * returned.
         * @param provider the provider's name of the algorithm of the symetric
         * encryptor you want to be returned.
         * @return a new instance of SymetricEncryptor generated with the specified
         * algorithm.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.security.NoSuchProviderException if the given provider
         * is invalid.
         */
        public static SymetricEncryptor getInstance(String algorithm, String provider) 
            throws NoSuchAlgorithmException, NoSuchProviderException
        {
            return new SymetricEncryptor(generateKey(algorithm, provider));
        }
     
        /**
         * Returns a new instance of SymetricEncryptor generated with the specified
         * algorithm and provider.
         * @param algorithm the algorithm of the symetric encryptor you want to be
         * returned.
         * @param provider the provider of the algorithm of the symetric
         * encryptor you want to be returned.
         * @return a new instance of SymetricEncryptor generated with the specified
         * algorithm.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         */
        public static SymetricEncryptor getInstance(String algorithm, Provider provider) 
            throws NoSuchAlgorithmException
        {
            return new SymetricEncryptor(generateKey(algorithm, provider));
        }
     
        /**
         * Returns a secret key generated with the specified algorithm.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * returned.
         * @return a secret key generated with the specified algorithm.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         */
        public static SecretKey generateKey(String algorithm) 
            throws NoSuchAlgorithmException
        {
            KeyGenerator keygen = KeyGenerator.getInstance(algorithm);
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
            return key;
        }
     
        /**
         * Returns a secret key generated with the specified algorithm and provider
         * name.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * returned.
         * @param provider the provider's name of the algorithm of the symetric
         * secret key you want to be returned.
         * @return a secret key generated with the specified algorithm and provider
         * name.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.security.NoSuchProviderException if the given provider
         * is invalid.
         */
        public static SecretKey generateKey(String algorithm, String provider)
            throws NoSuchAlgorithmException, NoSuchProviderException
        {
            KeyGenerator keygen = KeyGenerator.getInstance(algorithm, provider);
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
            return key;
        }
     
        /**
         * Returns a secret key generated with the specified algorithm and provider.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * returned.
         * @param provider the provider of the algorithm of the symetric
         * secret key you want to be returned.
         * @return a secret key generated with the specified algorithm and provider.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         */
        public static SecretKey generateKey(String algorithm, Provider provider)
            throws NoSuchAlgorithmException
        {
            KeyGenerator keygen = KeyGenerator.getInstance(algorithm, provider);
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
            return key;
        }
     
        /**
         * Writes a secret key generated with the specified algorithm to the 
         * specified output file.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * written.
         * @param outputFileName the name of the file you want the key to be
         * written.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.io.IOException if an I/O error occurs during writing the 
         * key.
         */
        public static void generateAndSaveKey(String algorithm, String outputFileName)
            throws NoSuchAlgorithmException, IOException
        {
            SecretKey key = generateKey(algorithm);
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(outputFileName));
            out.writeObject(key);
            out.close();
        }
     
        /**
         * Writes a secret key generated with the specified algorithm and provider 
         * to the specified output file.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * written.
         * @param provider the provider's name of the algorithm.
         * @param outputFileName the name of the file you want the key to be
         * written.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.security.NoSuchProviderException if the given provider
         * is invalid.
         * @throws java.io.IOException if an I/O error occurs during writing the 
         * key.
         */
        public static void generateAndSaveKey(String algorithm, String provider, 
                String outputFileName)
            throws NoSuchAlgorithmException, NoSuchProviderException, IOException
        {
            SecretKey key = generateKey(algorithm, provider);
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(outputFileName));
            out.writeObject(key);
            out.close();
        }
     
        /**
         * Writes a secret key generated with the specified algorithm and provider 
         * to the specified output file.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * written.
         * @param provider the provider's name of the algorithm.
         * @param outputFileName the name of the file you want the key to be 
         * written.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.io.IOException if an I/O error occurs during writing the 
         * key.
         */
        public static void generateAndSaveKey(String algorithm, Provider provider,
                String outputFileName)
            throws NoSuchAlgorithmException, IOException
        {
            SecretKey key = generateKey(algorithm, provider);
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(outputFileName));
            out.writeObject(key);
            out.close();
        }
     
        /**
         * Writes a secret key generated with the specified algorithm to the 
         * specified output file.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * written.
         * @param outputFile the file you want the key to be written.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.io.IOException if an I/O error occurs during writing the 
         * key.
         */
        public static void generateAndSaveKey(String algorithm, File outputFile)
            throws NoSuchAlgorithmException, IOException
        {
            SecretKey key = generateKey(algorithm);
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(outputFile));
            out.writeObject(key);
            out.close();
        }
     
        /**
         * Writes a secret key generated with the specified algorithm and provider 
         * to the specified output file.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @param algorithm the algorithm of the symetric secret key you want to be
         * written.
         * @param provider the provider's name of the algorithm.
         * @param outputFile the file you want the key to be written.
         * @throws java.security.NoSuchProviderException if the given provider is invalid.
         * @throws java.security.NoSuchAlgorithmException if the given algorithm is invalid.
         * @throws java.io.IOException if an I/O error occurs during writing the 
         * key.
         */
        public static void generateAndSaveKey(String algorithm, String provider, File outputFile)
            throws NoSuchAlgorithmException, NoSuchProviderException, IOException
        {
            SecretKey key = generateKey(algorithm, provider);
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(outputFile));
            out.writeObject(key);
            out.close();
        }
     
        /**
         * Writes a secret key generated with the specified algorithm and provider 
         * to the specified output file.
         * @param algorithm the algorithm of the symetric secret key you want to be
         * written.
         * @param provider the provider's name of the algorithm.
         * @param outputFile the file you want the key to be written.
         * @see org.cosmopol.crypto.SymetricEncryptor#AES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES
         * @see org.cosmopol.crypto.SymetricEncryptor#DES_EDE
         * @see org.cosmopol.crypto.SymetricEncryptor#BLOWFISH
         * @see org.cosmopol.crypto.SymetricEncryptor#RC2
         * @see org.cosmopol.crypto.SymetricEncryptor#ARCFOUR
         * @throws java.security.NoSuchAlgorithmException if the given algorithm
         * is invalid.
         * @throws java.io.IOException if an I/O error occurs during writing the 
         * key.
         */
        public static void generateAndSaveKey(String algorithm, Provider provider, File outputFile)
            throws NoSuchAlgorithmException, IOException
        {
            SecretKey key = generateKey(algorithm, provider);
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(outputFile));
            out.writeObject(key);
            out.close();
        }
     
        /**
         * Encrypts the specified input stream to the specified output stream with 
         * the underlying symetric encryptor.
         * 
         * @param in the input stream you want to be encrypted.
         * @param out the output stream where you want the encrypted datas to be 
         * written.
         * @throws IOException if an I/O error occurs during reading the input stream
         * or writting the decrypted datas to the output stream.
         * @throws InvalidKeyException if the key of the underlying symetric
         * encryptor is not a valid key for this operation.
         */
        public void encryptStream(InputStream in, OutputStream out)
            throws IOException, InvalidKeyException
        {
            Cipher cipher = null;
            try
            {
                cipher = Cipher.getInstance(algorithm);
            } 
            catch(NoSuchAlgorithmException ex)//never launched
            {
                ex.printStackTrace();
            }
            catch(NoSuchPaddingException ex)
            {
                ex.printStackTrace();
            }
     
            cipher.init(Cipher.ENCRYPT_MODE, key);
     
            super.crypt(in, out, cipher);
            in.close();
            out.close();
        }
     
        /**
         * Decrypts the specified input stream to the specified output stream with 
         * the underlying symetric encryptor.
         * 
         * @param in the input stream you want to be decrypted.
         * @param out the output stream where you want the decrypted datas to be 
         * written.
         * @throws IOException if an I/O error occurs during reading the input stream
         * or writting the decrypted datas to the output stream.
         * @throws InvalidKeyException if the key of the underlying symetric
         * encryptor is not a valid key for this operation.
         */
        public void decryptStream(InputStream in, OutputStream out)
            throws IOException, InvalidKeyException
        {
            Cipher cipher = null;
            try
            {
                cipher = Cipher.getInstance(algorithm);
            } 
            catch(NoSuchAlgorithmException ex)//never launched
            {
                ex.printStackTrace();
            }
            catch(NoSuchPaddingException ex)
            {
                ex.printStackTrace();
            }
     
            cipher.init(Cipher.DECRYPT_MODE, key);
     
            super.crypt(in, out, cipher);
            in.close();
            out.close();
        }
     
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  2. #22
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Voici un dernier encrypteur (je commence à faire ch*** avec mes encrypteurs je sais lol), qui utilise cette fois un chifrement non-symétrique, et qui est également très performant. L'inconvéniant d'un tel algorithme (non symétrique) est qu'il possède une complexité assez élevée (i.e. il va tourner beaucoup plus lentement pour de grandes quantités de données qu'un algorihme symétrique), et donc qu'il est peu pratique à utilsier dans ce cas, mais une petite asctuce permet de s'en sortir facilement de combinaisaond e cryptage symétriques et non symétriques permet d'utiliser efficacement l'algorithme.

    J'utilise pour l'encrypteur suivant l'algorithme RSA, inventé par Rivest, Shamir et Eddleman.

    [EDIT]
    Dernière mise à jour le 16/10/2007 (modélisatio et sécurité). Vous avez besoin des classes FileEncryptor et CipherEcryptor pour la faire fonctionner.
    [/EDIT]

    Le voici :

    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
     
    /*
     * RSAEncryptor.java
     *
     * Created on 17 juin 2006, 15:58
     * 
     */
     
    package org.cosmopol.crypto;
     
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import java.util.ArrayList;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.ShortBufferException;
    import javax.crypto.BadPaddingException;
     
    /**
     * This class provides methods to generate keys, encrypt or decrypt files and
     * streams with the RSA crypting algorithm.
     * @author Absil Romain
     */
    public class RSAEncryptor extends FileEncryptor
    {
        private Key publicKey;
        private Key privateKey;
        private boolean isEncryptInitialized;
        private boolean isDecryptInitialized;
     
        /**
         * Constructs a new RSA encryptor with the specified file containing one 
         * of the keys, in encrypt or decrypt mode (depends on the type of stored
         * key, if the key is public, then the encryptor is in encrypt mode,
         * otherwise it is in decrypt mode.
         * @param keyFileName the name of the file containing a RSA key.
         * @throws java.io.FileNotFoundException if the file containing the key doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * containing the key.
         * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
         * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
         */
        public RSAEncryptor(String keyFileName) 
            throws FileNotFoundException, IOException, ClassNotFoundException, 
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(keyFileName));
            Object key = keyIn.readObject();
            keyIn.close();
     
            if(key instanceof PublicKey)
            {
                publicKey = (Key)key;
                isEncryptInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (Key)key;
                isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new RSA encryptor with the specified file containing one 
         * of the keys, in encrypt or decrypt mode (depends on the type of stored
         * key, if the key is public, then the encryptor is in encrypt mode,
         * otherwise it is in decrypt mode.
         * @param keyFile the file containing a RSA key.
         * @throws java.io.FileNotFoundException if the file containing the key doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * containing the key.
         * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
         * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
         */
        public RSAEncryptor(File keyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException, InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(keyFile));
            Object key = keyIn.readObject();
            keyIn.close();
     
            if(key instanceof PublicKey)
            {
                publicKey = (Key)key;
                isEncryptInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (Key)key;
                isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt mode with the specified
         * public key.
         * @param key the public key (used to encrypt files and streams).
         **/
        public RSAEncryptor(PublicKey key)
        {
            this.publicKey = key;
            this.isEncryptInitialized = true;
        }
     
        /**
         * Constructs a new RSA encryptor in decrypt mode with the specified
         * private key.
         * @param key the private key (used to decrypt files and streams).
         **/
        public RSAEncryptor(PrivateKey key)
        {
            this.privateKey = key;
            this.isDecryptInitialized = true;
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt and decrypt mode with the
         * specified files containing the public and private key.
         * @param publicKeyFileName the name of the file containing the public key.
         * @param privateKeyFileName the name of the file containing the private key.
         * @throws java.io.FileNotFoundException if one of the files containing a key 
         * doen't exist.
         * @throws java.io.IOException if an error occurs during reading one of the keys.
         * @throws java.lang.ClassNotFoundException if one of the class of the keys is
         * unknown.
         * @throws java.security.InvalidKeyException if the files containing the keys don't
         * contain valid keys.
         */
        public RSAEncryptor(String publicKeyFileName, String privateKeyFileName) 
            throws FileNotFoundException, IOException, ClassNotFoundException,
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFileName));
            Object puKey = keyIn.readObject();
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFileName));
            Object prKey = keyIn.readObject();
            keyIn.close();
     
            if(puKey instanceof PublicKey && prKey instanceof PrivateKey)
            {
                this.publicKey = (Key)puKey;
                this.isEncryptInitialized = true;
                this.privateKey = (Key)prKey;
                this.isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("Some of the files don't contains" +
                        " a valid key");
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt and decrypt mode with the
         * specified files containing the public and private key.
         * @param publicKeyFile the file containing the public key.
         * @param privateKeyFile the file containing the private key.
         * @throws java.io.FileNotFoundException if one of the files containing a key 
         * doen't exist.
         * @throws java.io.IOException if an error occurs during reading one of the keys.
         * @throws java.lang.ClassNotFoundException if one of the class of the keys is
         * unknown.
         */
        public RSAEncryptor(File publicKeyFile, File privateKeyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFile));
            this.publicKey = (Key) keyIn.readObject();
            this.isEncryptInitialized = true;
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFile));
            this.privateKey = (Key) keyIn.readObject();
            this.isDecryptInitialized = true;
            keyIn.close();
        }
     
        /**
         * Construct a new RSA encryptor in encrypt and decrypt mode with the
         * specified public and private key.
         * @param publicKey the public key (used to encrypt files and streams).
         * @param privateKey the private key (used to decrypt files and streams).
         **/
        public RSAEncryptor(PublicKey publicKey, PrivateKey privateKey)
        {
            this.publicKey = publicKey;
            this.isEncryptInitialized = true;
            this.privateKey = privateKey;
            this.isDecryptInitialized = true;
        }
     
        /**
         * Construct a new RSA encryptor in encrypt and decrypt mode with the
         * specified pair of keys.
         * @param keyPair the pair of keys used to encrypt and decrypt files and
         * streams.
         **/
        public RSAEncryptor(KeyPair keyPair)
        {
            this(keyPair.getPublic(), keyPair.getPrivate());
        }
     
        /**
         * Returns the public key of the underlying encryptor.
         * @return the public key of the underlying encryptor.
         **/
        public PublicKey getPublicKey()
        {
            return (PublicKey) publicKey;
        }
     
        /**
         * Sets the public key of the underlying encryptor.
         * @param key the public key to set.
         **/
        public void setPublicKey(PublicKey key)
        {
            this.publicKey = key;
        }
     
        /**
         * Returns the private key of the underlying encryptor.
         * @return the private key of the underlying encryptor.
         **/
        public PrivateKey getPrivateKey()
        {
            return (PrivateKey) privateKey;
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys.
         * @param size the size of the generated keys.
         * @return a new instance of RSAEncryptor.
         **/
        public static RSAEncryptor getInstance(int size)
        {
            return new RSAEncryptor(generateKeys(size));
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of RSAEncryptor.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich youw ant to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich youw ant to write
         * the private key.
         * @throws java.io.IOException if an error occurs during writing one of the keys.
         */
        public static RSAEncryptor getInstance(int size, String publicKeyFileName,
                String privateKeyFileName) throws IOException
        {
            return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFileName, privateKeyFileName));
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of RSAEncryptor.
         * @param size the size of the generated keys.
         * @param publicKeyFile the file in wich youw ant to write the public key.
         * @param privateKeyFile the file in wich youw ant to write the private key.
         * @throws java.io.IOException if an error occurs during writing one of the keys.
         */
        public static RSAEncryptor getInstance(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFile, privateKeyFile));
        }
     
        /**
         * Returns a pair of keys generated with the specified size.
         * @return a pair of keys generated with the specified size.
         * @param size the size of the generated key.
         */
        public static KeyPair generateKeys(int size)
        {
            KeyPairGenerator pairgen = null;
            try
            {
                pairgen = KeyPairGenerator.getInstance("RSA");
            } 
            catch (NoSuchAlgorithmException ex)//never launched
            {
                ex.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            pairgen.initialize(size, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            return keyPair;
        }
     
        /**
         * Returns a pair of keys generated with the specified size and writes 
         * them into the specified files.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich youw ant to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich youw ant to write
         * the private key.
         * @return a pair of keys with the specified size.
         * @throws java.io.IOException if an error occurs during writing the keys.
         **/
        public static KeyPair generateAndSaveKeys(int size, String publicKeyFileName, 
                String privateKeyFileName) throws IOException
        {
            return generateAndSaveKeys(size, new File(publicKeyFileName), new File(privateKeyFileName));
        }
     
        /**
         * Returns a pair of keys generated with the specified size and writes 
         * them into the specified files.
         * @param size the size of the generated keys.
         * @param publicKeyFile the file in wich you want to write the public key.
         * @param privateKeyFile the file in wich you want to write the private key.
         * @return a pair of keys with the specified size.
         * @throws java.io.IOException if an error occurs during writing the keys.
         **/
        public static KeyPair generateAndSaveKeys(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            KeyPair keyPair = generateKeys(size);
     
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            out.writeObject(keyPair.getPublic());
            out.close();
     
            out = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            out.writeObject(keyPair.getPrivate());
            out.close();
     
            return keyPair;
        }
     
        /**
         * Encrypts the specified input stream to the specified output stream.
         * 
         * @param in the stream to encrypt.
         * @param out the stream where you want to write the encrypted stream.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void encryptStream(InputStream in, OutputStream out) 
            throws InvalidKeyException, IOException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in encrypt mode. You must specify a " +
                        "public key.");
            KeyGenerator keygen = null;
            Cipher cipherRsa = null;
            Cipher cipherAes= null;
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
            }
            catch(NoSuchAlgorithmException e)//never launched
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
     
            cipherRsa.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = null;
            try
            {
                wrappedKey = cipherRsa.wrap(key);
            } 
            catch (InvalidKeyException ex)
            {
                ex.printStackTrace();
            } 
            catch (IllegalBlockSizeException ex)
            {
                ex.printStackTrace();
            }
     
            Integer length = wrappedKey.length;
            DataOutputStream writer = new DataOutputStream(out);
            writer.writeInt(length);
            writer.write(wrappedKey);
     
            cipherAes.init(Cipher.ENCRYPT_MODE, key);
            super.crypt(in, writer, cipherAes);
    //        in.close();
    //        out.close();
            //writer.close();
        }
     
        /**
         * Decrypts the specified input stream to the specified output stream.
         * @param in the stream to decrypt.
         * @param out the stream where you want to write the decrypted stream.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void decryptStream(InputStream in, OutputStream out) 
            throws IOException, InvalidKeyException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in decrypt mode. You must specify a " +
                        "private key.");
            DataInputStream reader = new DataInputStream(in);
            int length = reader.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
            Cipher cipherRsa = null;
            Cipher cipherAes = null;
            Key key = null;
            try
            {
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
                cipherRsa.init(Cipher.UNWRAP_MODE, privateKey); 
                key = cipherRsa.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
            }
            catch(NoSuchAlgorithmException e)//never thrown
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
     
            cipherAes.init(Cipher.DECRYPT_MODE, key);
     
            super.crypt(reader, out, cipherAes);
    //        in.close();
    //        out.close();
            //reader.close();
        }
     
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  3. #23
    Candidat au Club
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2006
    Messages : 2
    Points : 2
    Points
    2
    Par défaut code Open Source du "Brouillamineur" de l'association GONIC
    Bonjour,
    notre association GONIC vous propose, ici, l'Open Source d'un utilitaire multi-fonctions, servant à :
    * gérer/ expérimenter des bases de données sous HSQLDB
    * combiner, par l'instruction XOR, deux fichiers en un troisième :
    * éditer des courriers, CV, ou autres textes à partir de canevas-modèles et d'éléments de personnalisations pré-enregistrés ou suggérés ...
    * ... créer de nouvelles fonctionnalités en profitant d'une interface déjà en place et pré-gérée ...
    Vous pourrez ainsi bénéficier du puissant complément d' IHM que constituent les "CLICs TORDUs" ( ... les "clics Biscornus" viendront compléter l'idée .. )

    (le but du jeu est moins dans les fonctionalités du code que dans l'expérimentation du code lui-même - une nouvelle extension majeure pourrait se méditer ... )

    - lire et accepter la "licence morale" SVP, et trouver le source en :
    http://gonic.lyon.free.fr/xor/testOpenSource.html


    Quelqu'un(e) pourra certainement nous donner la solution au petit problème rencontré : changer dynamiquement les fontes du label ou des zônes de saisie (en tenant compte des fontes disponibles de l'utilisateur) ? (... quelle est La meilleure solution ? ) ...

    D'autre part, nous aimerions recueillir des conseils avertis en matière de ... tout ce qui n'est pas propre dans ce qui est en cours ...
    (Pb pour HSQLDB : erreur sur SELECT avec LIMIT ) ... Help !

    Merci
      0  0

  4. #24
    Membre éprouvé
    Avatar de thecaptain
    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Décembre 2003
    Messages
    919
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Architecte de système d'information

    Informations forums :
    Inscription : Décembre 2003
    Messages : 919
    Points : 1 210
    Points
    1 210
    Par défaut
    Hello à tous,

    Suite à un projet sur SharePoint Portal Server 2007, j'ai développé rapidement une petite classe Java qui sert à déployer une webpart (donc une dll) dans un site en utilise le GAC (Global Assembly Cache)

    La classe (bon le code est pas méga-top ) :
    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
    import java.io.*;
    import java.util.*;
     
    public class WebPartDeployer
    {
    	public static void main(String[] args) throws Exception
    	{
    		//explication des paramètres
    		if (args.length != 2)
    		{
    			System.out.println("Utilisation :");
    			System.out.println("java -cp . WebPartDeployer nomDeWebPart.dll webConfig.config");
    			return;
    		}
     
    		String wp = args[0];
    		String wc = args[1];
    		File wpf = new File(wp);
    		File wcf = new File(wc);
     
    		//test l'existence du fichier
    		if (!wpf.exists())
    		{
    			throw new RuntimeException("Le fichier "+wpf.getAbsolutePath()+" n'existe pas !");
    		}
     
    		if (!wcf.exists())
    		{
    			throw new RuntimeException("Le fichier "+wcf.getAbsolutePath()+" n'existe pas !");
    		}
     
    		savePublicToken(wpf);
    		installWebPart(wpf, wcf);
     
    	}
     
    	private static String publicKeyToken;
    	private static void savePublicToken(File f) throws Exception
    	{
    		final String dataPath = "data.txt";
     
    		File d = new File(dataPath);
     
    		BufferedReader br = new BufferedReader(new FileReader(d));
    		StringBuffer sb = new StringBuffer();
    		String line;
     
    		while((line = br.readLine()) != null)
    		{
    			sb.append(line+"\n");
    		}
     
    		//récupération du public key token
    		String data = sb.toString();
    		int index = data.indexOf("PublicKeyToken=");
    		publicKeyToken = data.substring(index+15, index+31);
     
    		br.close();
    	}
     
    	private static void installWebPart(File wpf, File wcf) throws Exception
    	{
    		String nodeToAdd = getNode(wpf);
     
    		FileReader fr = new FileReader(wcf);
    		BufferedReader br = new BufferedReader(fr);
    		StringBuffer sb = new StringBuffer();
     
     
    		//lecture du fichier ligne par ligne
    		String line;
    		boolean isInLine = false;
    		boolean finished = false;
    		while ((line = br.readLine()) != null)
    		{
    			//on check si on rentre dans la balise
    			if (!isInLine)
    			{
    				if (line.indexOf("<SafeControls>") != -1)
    				{
    					isInLine = true;
    				}
    			}
    			else if (!finished)
    			{
    				if (line.indexOf("</SafeControls>") != -1)
    				{
    					finished = true;
    					sb.append(nodeToAdd+"\n");
    				}
    			}
     
    			sb.append(line+"\n");	
    		}
     
    		fr.close();
    		br.close();
     
    		//réécriture du fichier
    		FileWriter fw = new FileWriter(wcf);
    		PrintWriter pw = new PrintWriter(fw);
     
    		String[] lines = sb.toString().split("\n");
    		for (int i=0 ; i<lines.length ; i++)
    		{
    			pw.println(lines[i]);
    		}
     
    		fw.close();
    		pw.close();
    	}
     
    	private static String getNode(File wpf)
    	{
    		String name = getNameOnly(wpf);
    		return "<SafeControl Assembly=\""+name+", Version=1.0.0.0, Culture=neutral, PublicKeyToken="+publicKeyToken+"\" Namespace=\""+name+"\" TypeName=\"*\" Safe=\"True\" />";
    	}
     
    	private static String getNameOnly(File wpf)
    	{
    		String name = wpf.getName();
    		int id = name.lastIndexOf(".");
     
    		return name.substring(0, id);
    	}
    }
    pour l'utiliser, il faut le lauch.bat correspondant :
    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
    @echo off
     
    SET assembly=WPSubscription
    SET config=web.config
     
    echo Enregistrement de %assembly% dans le GAC...
    "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -i %assembly%.dll
     
    echo.
    echo Enregistrement des donnees dans data.txt...
    "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" /l %assembly% > data.txt
     
    echo.
    echo Generation du fichier xml %assembly%.dll
    "C:\Program Files\Java\jdk1.5.0_07\bin\java" -cp "." WebPartDeployer %assembly%.dll %config%
    cmd
    Ensuite il suffit de remplacer les 2 ligne suivantes par
    - le nom de la webpart
    - l'url du web.config à modifier (pour enregistrer la webpart)
    SET assembly=WPSubscription
    SET config=web.config
    Il faut juste au préalable mettre le dll de la webpart dans le même dossier que le lauch.bat. D'autre part, l'utilisation de cette méthode nécessite d'avoir visual studio 2005 installé (ou du moins l'utilitaire gacutil). Vous l'aurez compris, c'est pour du windows only

    En espérant que ca serve à quelqun !

    @++
    Libzippp (C++)
    Lost in AStorm
      0  0

  5. #25
    Membre confirmé
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Octobre 2005
    Messages
    244
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Philippines

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Octobre 2005
    Messages : 244
    Points : 609
    Points
    609
    Par défaut
    J'ai pas eu l'impression d'avoir vu cette classe dans la J2SE... Bah c'est juste une associations entre deux classes (le nom semble parlant )

    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
    public final class Pair<A, B> {
     
    	private A aVal;
    	private B bVal;
     
    	public Pair ( A first, B second) {
    		aVal = first;
    		bVal = second;
    	}
     
    	public void setFirst(A first) {
    		aVal = first;
    	}
     
    	public void setSecond(B second) {
    		bVal = second;
    	}
     
    	public A getFirst() {
    		return aVal;
    	}
     
    	public B getSecond() {
    		return bVal;
    	}
     
            public boolean equals(Object o) {
                    if(o instanceof Pair) {
                       return (aVal.equals((Pair)o.getFirst()) && bVal.equals((Pair)o.getSecond());
                    } else return false;
    }

    Et voici une petite classe permettant de savoir ou se situe un thread (necessite tout de meme un appel de "mise à jour" des informations de "positions")

    La classe principale:
    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
     
    import java.util.WeakHashMap;
     
    public class ThreadDescriptor {
     
    	static WeakHashMap < Thread, ThreadLineInfo> map;
     
    	static {
    		map = new WeakHashMap < Thread, ThreadLineInfo>();
    	}
     
    	static final public void notify (Thread t, String s ) {
     
    		Exception e = new Exception();
    		StackTraceElement[] traces = e.getStackTrace();
     
    		if(traces.length > 1) {
    			StackTraceElement trace = traces[1];
    			map.put(t, new ThreadLineInfo(s, trace) );
    		}
     
    	}
     
     
    	static final public void notify ( String s ) {
    		notify(Thread.currentThread(), s);
    	}
     
    	static final public ThreadLineInfo getInfo(Thread t) {
    		if(!map.containsKey(t))
    			return null;
    		return map.get(t);
    	}
     
    	public ThreadDescriptor() {
    		super();
    	}
     
    }
    Et voici la classe "donnée"

    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
    public final class ThreadLineInfo {
     
    	String  comment		;
    	int 	line		;
    	String 	fileName	;
    	String 	className	;
    	String 	methodName	;
     
    	public String getClassName() {
    		return className;
    	}
     
    	public String getComment() {
    		return comment;
    	}
     
    	public String getFileName() {
    		return fileName;
    	}
     
    	public int getLine() {
    		return line;
    	}
     
    	public String getMethodName() {
    		return methodName;
    	}
     
    	protected ThreadLineInfo(String comment, StackTraceElement e) {
    		this.comment 	= comment;
    		this.line 		= e.getLineNumber();
    		this.fileName	= e.getFileName();
    		this.className	= e.getClassName();
    		this.methodName	= e.getMethodName();
    	}
     
    }
      0  0

  6. #26
    Membre confirmé
    Avatar de link256
    Profil pro
    Développeur Java
    Inscrit en
    Février 2003
    Messages
    596
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Février 2003
    Messages : 596
    Points : 642
    Points
    642
    Par défaut Filtre pour JTextField et autre composant
    Voila une petite classe permettant de poser un filtre sur un JTextFiled , ce qui permet d'evite d'avoir a analyser le texte saisie apres la validation et ainsi alleger votre code.

    ce filtre sur les nombres a 2 parametres , le premier etant la taille(nb de digit)
    et le second la valeur numerique a ne pas depasser.

    elle est tres facilement modifiable ce qui permet de faire des filtres a toutes les sauces , j'ai enlevé la plupart des "sysout" au profit de bip sonore.

    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
     
    import java.awt.Toolkit;
     
     
    /****
     * Classe DDocumentNumber : permet de personnaliser la gestion du "model" des composants Texte
     *        proposee dans l'api de swing 
     *
     ****/
     
     
    public class Filtre extends PlainDocument
    {
    	private int longueur;
     
    	private double valeur; 
    	public Filtre(int taille,Double valeur)
    	{	
    		super ();
    		this.longueur = taille; // represente le nombre de digit maximum
    		this.valeur = valeur; // represente la valeur limite a ne pas depasser par le champ a saisir
     
    	}
     
    	/**
             * Redefini la methode de la classe PlainDocument permettant ainsi d'autoriser 
             * uniquement les caracteres desires
             */
    	public void insertString (int offs, String str, AttributeSet a) throws BadLocationException
    	{
    		StringBuffer sb = new StringBuffer ();
    		char car;
    		if(this.getLength()<longueur)
    		{
     
    			for (int i=0; i<str.length(); i++)
    			{	
    				car = str.charAt(i);
     
     
    				if (Character.isDigit (car))
    				{
     
    					sb.append(car);	
     
    				}
    				else
    				{
    					Toolkit.getDefaultToolkit().beep();
    					System.out.println("la caractere saisie n'est pas un chiffre");
    				}
    			}
                                          //ajout du digit a la position off
    			super.insertString(offs, sb.toString(), a);
     
                                           //on test si le nombre saisie depasse la valeur maximale
    			//si oui on annule l'ajout qui vient d'etre fait
    			if (Double.parseDouble(this.getText(0,this.getLength()))>valeur)
    			{
    				super.remove(offs, sb.length());
    				Toolkit.getDefaultToolkit().beep();
    			}
     
    		}
    		else
    		{
    			Toolkit.getDefaultToolkit().beep();
    			System.out.println("taille depasser");
    		}
    	}
     
    }
    dans le cadre d'utilisation de double il y a plusieur appel possible
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    toto= Double.parseDouble("0699999999");
    monJTextField = new JTextField(new Filtre(10,toto),"",TAILLE_MAX);

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    double toto = 121456;
    monJTextField = new JTextField(new Filtre(10,toto),"",TAILLE_MAX);
    je rajoute ici un ".0" pour que ce soit pris en double et non en int
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    monJTextField = new JTextField(new Filtre(10,9000.0),"",TAILLE_MAX);

    voilu en esperant que cela vous sera utile
      0  0

  7. #27
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Points : 5 943
    Points
    5 943
    Par défaut
    Voici une petite classe qui ne possède que des méthodes static permettants de travailler sur les adresses IP.
    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
    import java.net.InetAddress;
    import java.net.UnknownHostException;
     
     
    /**
     * Cette classe fournie diverse methodes pour travailler avec les adresses IP
     * @author Yann D'ISANTO
     */
    public final class NetTools {
     
        private NetTools() {};
     
     
        /**
         * Retourne une chaine de caracteres representant l'adresse IP specifiee
         * 
         * @param rawIp adresse IP
         * @return Chaine de caracteres representant l'adresse IP specifiee
         */
        static public final String getIpString(byte[] rawIp) {
            StringBuilder IP = new StringBuilder("");
            int i;
            for(i = 0; i < 4; i++) {
                byte b = rawIp[i];
                IP.append(String.valueOf((b < 0) ? (256 + b) : b));
                IP.append((i != 3) ? "." : "");
            }
            return(IP.toString());
        }
     
        /**
         * Retourne une chaine de caracteres representant l'adresse IP 
         * de l'InetAddress specifiee
         *
         * @param address InetAddress
         * @return Chaine de caracteres representant l'adresse IP de 
         * l'InetAddress specifiee
         */
        static public final String getIpString(InetAddress address) {
            StringBuilder IP = new StringBuilder("");
            return getIpString(address.getAddress());
        }
     
        /**
         * Retourne une chaine de caracteres representant l'adresse IP 
         * du host specifie
         *
         * @param host host
         * @return Chaine de caracteres representant l'adresse IP du 
         * host specifie
         */
        static public final String getIpString(String host)
        throws UnknownHostException {
            InetAddress address = InetAddress.getByName(host);
            return getIpString(address);
        }
     
        /**
         * Retourne un tableau de chaines de caracteres representant 
         * les differentes adresses IP du host specifie
         *
         * @param host host
         * @return tableau de chaines de caracteres representant 
         * les differentes adresses IP du host specifie
         */
        static public final String[] getAllIpString(String host)
        throws UnknownHostException {
            InetAddress[] allRawIP = InetAddress.getAllByName(host);
            int size = allRawIP.length;
            String[] allIP = new String[size];
            for(int i = 0; i < size; i ++) {
                allIP[i] = getIpString(allRawIP[i]);
            }
            return allIP;
        }
     
        /**
         * Verifie si la chaine de caracteres specifiee correspond au
         * pattern d'une addresse IP
         *
         * @param ip chaine de caracteres
         * @return true si la chaine de caracteres specifiee correspond
         * au pattern d'une addresse IP
         */
        static public final Boolean isIpString(String ip) {
            Boolean b = java.util.regex.Pattern.
                    matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", ip);
            if(b) {
                String[] fields = ip.split("\\.");
                for(String field : fields) {
                    int value = Integer.parseInt(field);
                    if((value < 0) || (value > 255)) {
                        b = false;
                        break;
                    }
                }
            }
            return b;
        }
     
        /**
         * Retourne un tableau de byte representant l'adresse IP d'une 
         * chaine de caracteres verifiant le pattern d'une adresse IP
         *
         * @param ip chaine de caracteres
         * @return tableau de byte representant l'adresse IP
         */
        static public final byte[] getRawIp(String ip) {
            if(!isIpString(ip)) {
                throw new IllegalArgumentException(ip + " is an invalid IP string");
            }
            byte[] rawIp = new byte[4];
            String[] fields = ip.split("\\.");
            for(int i = 0; i < 4; i ++) {
                rawIp[i] = (byte) Integer.parseInt(fields[i]);
            }
            return rawIp;
        }
     
        /**
         * Calcul l'adresse du reseau defini par l'adresse IP et le 
         * masque specifies
         *
         * @param ip adresse IP
         * @param mask masque
         * @return adresse du reseau
         */
        static public final byte[] getNetId(byte[] ip, byte[] mask) {
            byte[] netId = new byte[4];
            for(int i = 0; i < 4; i ++) {
                int iIp = (ip[i] < 0) ? (256 + ip[i]) : ip[i];
                int iMask = (mask[i] < 0) ? (256 + mask[i]) : mask[i];
                netId[i] = (byte) (iIp & iMask);
            }
            return netId;
        }
     
        /**
         * Calcul l'adresse de getBroadcast defini par l'adresse de reseau 
         * et le masque specifies
         * 
         * 
         * @param getNetId adresse du reseau
         * @param mask masque
         * @return adresse de getBroadcast
         */
        static public final byte[] getBroadcast(byte[] netId, byte[] mask) {
            byte[] broadcast = new byte[4];
            byte[] wildcard = getWildcard(mask);
            for(int i = 0; i < 4; i ++) {
                int iLan = (netId[i] < 0) ? (256 + netId[i]) : netId[i];
                int iWildcard = (wildcard[i] < 0) ? (256 + wildcard[i]) : wildcard[i];
                broadcast[i] = (byte) (iLan | iWildcard);
            }
            return broadcast;
        }
     
        /**
         * Calcul le getWildcard du masque specifie
         * 
         * @param mask masque
         * @return getWildcard
         */
        static public final byte[] getWildcard(byte[] mask) {
            byte[] wildcard = new byte[4];
            for(int i = 0; i < 4; i ++) {
                wildcard[i] = (byte) (255 - ((mask[i] < 0) ? (256 + mask[i]) : mask[i]));
            }
            return wildcard;
        }
    }
    Enjoy
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr
      0  0

  8. #28
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Points : 5 943
    Points
    5 943
    Par défaut
    Voilà la suite, pour une approche plus "objet".
    Une classe Ip représentant une adresse ip et une classe Lan représentant un réseau.
    J'ai aussi rajouté le calcul du nombre de postes maximal pour un réseau donné (je dois avouer que ça fait un moment que j'ai plus fait ce genre de calcul donc il se peut qu'il soit erroné , n'hésitez pas à me corriger ).

    classe Ip
    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
    /*
     * Ip.java
     *
     * Created on 26 juin 2006, 14:10
     *
     */
     
    /**
     *
     * @author Yann D'ISANTO
     */
    public class Ip {
     
        private byte[] rawIp;
     
        public Ip(byte[] rawIp) {
            if(rawIp.length != 4) {
                throw new IllegalArgumentException(
                        "Unavailable raw IP, must be a 4 elements byte array");
            }
            this.rawIp = rawIp;
        }
     
        public Ip(String ip) {
            if(!isIpString(ip)) {
                throw new IllegalArgumentException(ip + " is an invalid IP string");
            }
            rawIp = new byte[4];
            String[] fields = ip.split("\\.");
            for(int i = 0; i < 4; i ++) {
                rawIp[i] = (byte) Integer.parseInt(fields[i]);
            }
        }
     
        /**
         * Verifie si la chaine de caracteres specifiee correspond au
         * pattern d'une addresse Ip
         * 
         * 
         * @param ip chaine de caracteres
         * @return true si la chaine de caracteres specifiee correspond
         * au pattern d'une addresse Ip
         */
        static public final Boolean isIpString(String ip) {
            Boolean b = java.util.regex.Pattern.
                    matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", ip);
            if(b) {
                String[] fields = ip.split("\\.");
                for(String field : fields) {
                    int value = Integer.parseInt(field);
                    if((value < 0) || (value > 255)) {
                        b = false;
                        break;
                    }
                }
            }
            return b;
        }
     
     
        public String toString() {
            StringBuilder sb = new StringBuilder("");
            int i;
            for(i = 0; i < 4; i++) {
                byte b = this.rawIp[i];
                sb.append(String.valueOf((b < 0) ? (256 + b) : b));
                sb.append((i != 3) ? "." : "");
            }
            return(sb.toString());
        }
     
     
        public byte[] getRawIp() {
            return rawIp;
        }
     
        public void setRawIp(byte[] rawIp) {
            if(rawIp.length != 4) {
                throw new IllegalArgumentException(
                        "Unavailable raw IP, must be a 4 elements byte array");
            }
            this.rawIp = rawIp;
        }
    }
    classe Lan
    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
    /*
     * Lan.java
     *
     * Created on 26 juin 2006, 14:30
     *
     */
     
    /**
     *
     * @author Yann D'ISANTO
     */
    public class Lan {
     
        private Ip ip;
        private Ip mask;
        private Ip wildcard;
        private Ip netId;
        private Ip broadcast;
        private long maxHostCount;
     
        public Lan(Ip ip, Ip mask) {
            this.ip = ip;
            setMask(mask);
            update();
        }
        public Lan(String ip, String mask) {
            this(new Ip(ip), new Ip(mask));
        }
        public Lan(byte[] ip, byte[] mask) {
            this(new Ip(ip), new Ip(mask));
        }
        public void update() {
            byte[] ip = this.ip.getRawIp();
            byte[] mask = this.mask.getRawIp();
            byte[] netId = new byte[4];
            byte[] wildcard = new byte[4];
            byte[] broadcast = new byte[4];
            for(int i = 0; i < 4; i ++) {
                int iIp = (ip[i] < 0) ? (256 + ip[i]) : ip[i];
                int iMask = (mask[i] < 0) ? (256 + mask[i]) : mask[i];
                netId[i] = (byte) (iIp & iMask);
                wildcard[i] = (byte) (255 - ((mask[i] < 0) ? 
                    (256 + mask[i]) : mask[i]));
                int iLan = (netId[i] < 0) ? (256 + netId[i]) : netId[i];
                int iWildcard = (wildcard[i] < 0) ? (256 + wildcard[i]) : wildcard[i];
                broadcast[i] = (byte) (iLan | iWildcard);
            }
            this.maxHostCount = 1L;
            for(int i = 3; i >= 0; i --) {
                int iNetId = (netId[i] < 0) ? (256 + netId[i]) : netId[i];
                int iBroadcast = (broadcast[i] < 0) ? (256 + broadcast[i]) : broadcast[i];
                int b = iBroadcast - iNetId;
                maxHostCount *= (b + 1);
            }
            maxHostCount -= 2;
            this.netId = new Ip(netId);
            this.wildcard = new Ip(wildcard);
            this.broadcast = new Ip(broadcast);
        }
     
        public Ip getIp() {
            return ip;
        }
        public void setIp(Ip ip) {
            this.ip = ip;
            update();
        }
        public Ip getMask() {
            return mask;
        }
        public final void setMask(Ip mask) {
            byte[] rawMask = mask.getRawIp();
            for(byte b : rawMask) {
                if((b != 0) && (b != -1) && (b != -2) && (b != -4) && (b != -8) && 
                   (b != -16) && (b != -32) && (b != -64) && (b != -128)) {
                    throw new IllegalArgumentException("Invalid mask : " + mask);
                }
            }
            this.mask = mask;
            update();
        }
        public Ip getWildcard() {
            return wildcard;
        }
        public Ip getNetId() {
            return netId;
        }
        public Ip getBroadcast() {
            return broadcast;
        }
        public long getMaxHostCount() {
            return maxHostCount;
        }
     
        public String toString() {
            byte[] mask = this.mask.getRawIp();
            int nullBitCount = 0;
            for(int i = 3; i >= 0; i --) {
                if(mask[i] == 0) {
                    nullBitCount += 8;
                    continue;
                } else if(mask[i] == -128) {
                    nullBitCount += 7;
                } else if(mask[i] == -64) {
                    nullBitCount += 6;
                } else if(mask[i] == -32) {
                    nullBitCount += 5;
                } else if(mask[i] == -16) {
                    nullBitCount += 4;
                } else if(mask[i] == -8) {
                    nullBitCount += 3;
                } else if(mask[i] == -4) {
                    nullBitCount += 2;
                } else if(mask[i] ==  -2) {
                    nullBitCount += 1;
                }
                break;
            }
            return this.netId + "/" + (32 - nullBitCount);
        }
     
    }
    Enjoy
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr
      0  0

  9. #29
    Membre émérite
    Avatar de mavina
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2004
    Messages
    1 812
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : Chine

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2004
    Messages : 1 812
    Points : 2 411
    Points
    2 411
    Par défaut
    Salut,

    Une ptite classe super courte et simple pour utiliser facilement le logger log4j dans un 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
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
     
    package logger;
     
    import org.apache.log4j.Logger; // importation de la classe Logger de log4j
    import org.apache.log4j.Level; // importation de la classe de Levels de log4j
    import org.apache.log4j.FileAppender; // importation du FileAppender pour la sortie standard
    import org.apache.log4j.PatternLayout;
    import java.util.HashMap;
     
    /**
     * Cette classe vous permet d'effectuer toutes les opperations sur un Logger, à savoir : 
     * En récupérer une instance, changer son level, changer son path.<br><br>
     * Un exemple d'utilisation : <br><br>
     * logger=MyLogger.getLogger("c:/Annuaire.log",getClass().toString()); // Logger pret a etre utilise<br>
     */
    public class MyLogger 
    {
      private static HashMap getHashMap()
      {
        HashMap temp=new HashMap();
        /* ALL < DEBUG < INFO < WARN < ERROR < FATAL */
        temp.put("ALL",Level.ALL);
        temp.put("DEBUG",Level.DEBUG);
        temp.put("INFO",Level.INFO);
        temp.put("WARN",Level.WARN);
        temp.put("ERROR",Level.ERROR);
        temp.put("FATAL",Level.FATAL);
     
        return temp;
      }
     
      /**
       * Cette fonction renvoie un logger initialise pour ecrire dans un fichier dont le nom est passé en paramètre et dont le path sera : /oracleas/0904/oapcp00/opmn/logs/ .
       * Par defaut, le level est ALL.
       * @return Un objet Logger initialise pour ecrire les logs dans le fichier fileName si tout se passe bien, null sinon.
       * @param fileName Le nom du fichier dans lequel ecrire.
       * @param className Le nom de la classe dans laquelle il est appele.
       */
      public static Logger getLogger(String fileName, String className)
      {
        Logger l=Logger.getLogger(className);
        FileAppender fa=new FileAppender();
        PatternLayout monLayout=new PatternLayout("%-5p [%C{1} -> %M]: %m%n");
        l.removeAllAppenders();
        try
        {
           fa=new FileAppender(monLayout,"/oracleas/0904/oapcp00/opmn/logs/"+fileName,true);
           fa.activateOptions();
           l.addAppender(fa);
           l.setLevel(Level.ALL);
        }catch(Exception e)
        {
           System.out.println("Erreur lors de la création du FileAppender : "+e.getMessage());
           e.printStackTrace();
           l=null;
        }
        return l;
      }
     
      /**
       * Cette fonction renvoie un Logger.
       * @return Cette fonction renvoie un Logger initialise pour ecrire les logs dans le fichier fileName si tout se passe bien, null si le Level n'existe pas ou si la creation du Logger se passe mal.   
       * @param level Le level du logger : ALL < DEBUG < INFO < WARN < ERROR < FATAL 
       * @param className Le nom de la classe dans laquelle il est appele.
       * @param fileName Le nom du fichier dans lequel ecrire.
       */
      public static Logger getLogger(String fileName, String className, String level)
      {
        Logger l=Logger.getLogger(className);
        FileAppender fa=new FileAppender();
        PatternLayout monLayout=new PatternLayout("%-5p [%C{1} -> %M]: %m%n");
        l.removeAllAppenders();
     
        try
        {
           fa=new FileAppender(monLayout,"/oracleas/0904/oapcp00/opmn/logs/"+fileName,true);
           fa.activateOptions();
           l.addAppender(fa);
           HashMap levels=getHashMap();
           Level lev=(Level)levels.get(level);
     
           if(l==null)
            return null;
     
           l.setLevel(lev);
        }catch(Exception e)
        {
           System.out.println("Erreur lors de la création du FileAppender : "+e.getMessage());
           e.printStackTrace();
           l=null;
        }
        return l;
      }
     
     
      /**
       * Fonction qui change le level d'un logger par le level passe en parametre.<br>
       * Il convient d'expliquer les levels.<br>
       * Si l'on défini un level, on peut filtrer les logs affichés. Ainsi, tous les levels >= au level defini pourront être affichés.<br>
       * Par exemple, si je définit mon level en ERROR, logger.error(String) s'affichera alors que logger.debug(String) ne s'affichera pas.<br>
       * Hierarchie des levels : ALL < DEBUG < INFO < WARN < ERROR < FATAL<br>
       * Pour désactiver les logs en prod, on met en FATAL pour garder les erreurs irrécupérables.
       * @return true si le level existe, faise sinon
       * @param level Le level a appliquer : ALL < DEBUG < INFO < WARN < ERROR < FATAL 
       * @param log le Logger sur lequel on change le level
       */
      public static boolean setLevel(Logger log, String level)
      {
        Level l=(Level)getHashMap().get(level);
        if(l==null)
          return false;
        log.setLevel(l);
        return true;
      }
     
      /**
       * Fonction qui change le fichier de log par le fichier passe en parametre. 
       * @return true si tout se passe bien, false sinon.
       * @param fileName le nom du fichier.
       * @param log le Logger sur lequel changer le fichier
       */
      public static boolean setFile(Logger log,String fileName)
      {
          FileAppender fa=new FileAppender();
          PatternLayout monLayout=new PatternLayout("%-5p [%C{1} -> %M]: %m%n");
          try
          {
             fa=new FileAppender(monLayout,fileName,true);
             fa.activateOptions();
             log.removeAllAppenders();
             log.addAppender(fa);
             return true;
          }catch(Exception e)
          {
              System.out.println("Erreur lors de la création du FileAppender : "+e.getMessage());
              e.printStackTrace();
              return false;
          }
      }
    }
    Hop, pour initialiser un logger :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Logger logger=MyLogger.getLogger("c:/log.log",getClass().toString());
    Et pour changer son level :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    MyLogger.setLevel(logger,"WARN");
    Voilà voilà

    Fred

    P.S. : je vous conseille de désactiver les logs lorsque vous n'en avez plus besoin (le mettre en fatal quoi) car le pattern que j'utilise est un peu gourmand en ressources
    Apres vous pouvez changer le pattern si ca vous tente ;p
    Développeur Java / Flex à Shanghai, Chine
    mes publications
    Mon dernier tutoriel : Messages Quit IRC : explications

    La rubrique IRC recrute des redacteurs : contactez moi

    Ce flim n'est pas un flim sur le cyclimse. Merci de votre compréhension.[/SIZE]
      0  0

  10. #30
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Points : 5 943
    Points
    5 943
    Par défaut
    Voila une petite classe basée sur le javax.swing.Timer qui permet de connaitre le temps réel écoulé entre chaque interval
    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
    /*
     * Timer.java
     *
     */
     
     
    /**
     * Timer base sur le javax.swing.Timer et permet de connaitre le temps reel 
     * ecoule. Quand le Timer est lance, la methode run() est appelee successivement 
     * selon le delai specifie.
     *
     * @author Yann D'ISANTO
     */
    abstract public class Timer {
     
        public static final int DEFAULT_DELAY = 100;
        private javax.swing.Timer timer;
        private long start;
        private long previousTop;
        private long totalElapsed;
        private boolean reset;
        private boolean running;
     
        /**
         * Instancie un Timer avec un delai par defaut de 100 millisecondes.
         */
        public Timer() {
            this(DEFAULT_DELAY);
        }
     
        /**
         * Instancie un Timer avec le delai specifie.
         * @param delay delai en milliseconde.
         */
        public Timer(int delay) {
            reset = false;
            running = false;
            timer = new javax.swing.Timer(delay,
                    new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    long newTop = System.currentTimeMillis();
                    long elapsed = newTop - previousTop;
                    totalElapsed += elapsed;
                    run(elapsed);
                    previousTop = newTop;
                }
            });
        }
     
        /**
         * Retourne le temps du compteur.
         * @return le temps du compteur.
         */
        public long getTime() {
            return totalElapsed;
        }
     
        /**
         * Methode appelee par le timer quand celui-ci tourne. 
         * @param delay delai reel depuis le precedent appel.
         */
        abstract public void run(long delay);
     
        /**
         * Demarre le Timer et le compteur de temps.
         */
        public void start() {
            if(!running) {
                start = System.currentTimeMillis();
                previousTop = start;
                timer.start();
                reset = false;
                running = true;
            }
        }
     
        /**
         * Arrete le Timer et le compteur de temps.
         */
        public void stop() {
            if(running) {
                timer.stop();
                running = false;
            }
        }
     
        /**
         * Arrete le Timer et remet le compteur de temps a zero.
         */
        public void reset() {
            if(!reset) {
                stop();
                totalElapsed = 0;
                reset = true;
            }
        }
     
        /**
         * Indique si le Timer tourne.
         * @return true si le Timer tourne.
         */
        public boolean isRunning() {
            return running;
        }
        /**
         * Indique si le compteur de temps a ete remis a zero et 
         * n'a pas ete redemarre.
         * @return true si le compteur de temps a ete remis a zero 
         * et n'a pas ete redemarre.
         */
        public boolean isReset() {
            return reset;
        }
     
        /**
         * Retourne le delai du timer, le nombre de milliseconde entre 
         * deux appels a la methode run().
         *@return delai.
         */
        public int getDelay() {
            return timer.getDelay();
        }
     
        /**
         * Fixe le delai du timer, le nombre de milliseconde entre 
         * deux appels a la methode run().
         *@param delay delai.
         */
        public void setDelay(int delay) {
            timer.setDelay(delay);
        }
    }
    Enjoy
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr
      0  0

  11. #31
    Membre averti Avatar de soad
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    520
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2004
    Messages : 520
    Points : 439
    Points
    439
    Par défaut
    Voici une classe qui dérive de JFrame qui sauvegarde sa position, sa taille, ... automatiquement pour sa prochaine ouverture

    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
     
    package ui;
    import java.awt.Dimension;
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.prefs.Preferences;
    import javax.swing.JFrame;
     
     
     
     
    @SuppressWarnings("serial")
    public class JLFrame extends JFrame {
     
     
    	private Preferences prefs = Preferences.userNodeForPackage(getClass());
     
    	public final String PREF_X 		= "x";
    	public final String PREF_Y 		= "y";
    	public final String PREF_WIDTH 	= "l";
    	public final String PREF_HEIGHT = "h";
    	public final String PREF_STATE	= "state";
     
     
     
     
     
    	public JLFrame(String titre, int posXDefault, int posYDefault, int widthDefault, int heightDefault) {
    		super(titre);
     
     
    		// Récupère la dimension de l'écran (zone affichable)
    		GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    		Insets marge = Toolkit.getDefaultToolkit().getScreenInsets(gd.getDefaultConfiguration());
    		Dimension dimScreen = Toolkit.getDefaultToolkit().getScreenSize();
    		dimScreen.height -= (marge.top   + marge.bottom);
    		dimScreen.width  -= (marge.right + marge.left);
     
     
    		// Ajout de la taille de la fenêtre (par défaut: widthDefault*heightDefault et au maximun la taille de l'écran)
    		widthDefault  = prefs.getInt(PREF_WIDTH,  widthDefault);
    		heightDefault = prefs.getInt(PREF_HEIGHT, heightDefault);
    		if(widthDefault  > dimScreen.width)  widthDefault  = dimScreen.width;
    		if(heightDefault > dimScreen.height) heightDefault = dimScreen.height;
    		setSize(widthDefault, heightDefault);
     
     
    		// Ajout de la location de la fenêtre
    		posXDefault = prefs.getInt(PREF_X, posXDefault);
    		posYDefault = prefs.getInt(PREF_Y, posYDefault);
    		if(posXDefault+widthDefault  > dimScreen.width)  posXDefault -= (posXDefault+widthDefault)  - dimScreen.width;
    		if(posYDefault+heightDefault > dimScreen.height) posYDefault -= (posYDefault+heightDefault) - dimScreen.height;
    		if(posXDefault < marge.left) posXDefault = marge.left;
    		if(posYDefault < marge.top)  posYDefault = marge.top;
    		setLocation(posXDefault, posYDefault);
     
     
    		// Ajout du state de la fenêtre (soit NORMAL ou MAXIMIZED_BOTH)
    		int state = prefs.getInt(PREF_STATE, JFrame.NORMAL);
    		if(state != JFrame.MAXIMIZED_BOTH  &&  state != JFrame.NORMAL) state = JFrame.NORMAL;
    		setExtendedState(state);
     
     
    		// Ajout d'un listener pour sauvegarder les propriétées la fenêtre lorque celle ci se ferme
    		addWindowListener(new WindowAdapter() {
    			public void windowClosing(WindowEvent e) {
    				saveProperties();
    			}
    		});
    	}
     
     
    	public void saveProperties() {
     
    		// Sauvegarde le statut de la fenêtre (NORMAL ou MAXIMIZED_BOTH)
    		// (Uniquement si la fenêtre est maximisée ou normal sinon par défaut se sera normal)
    		int state = getExtendedState();
    		if(state != JFrame.MAXIMIZED_BOTH  &&  state != JFrame.NORMAL) state = JFrame.NORMAL;
    		prefs.putInt(PREF_STATE, state);
     
     
     
    		// Uniquement si la fenêtre n'est pas MAXIMIZED_BOTH
    		if(state != JFrame.MAXIMIZED_BOTH) {
     
     
    			// Récupère taille et position de la fenêtre
    			Rectangle bounds = getBounds();
     
     
    			// Sauvegarde de la taille de la fenêtre
    			prefs.putInt(PREF_WIDTH,  bounds.width);
    			prefs.putInt(PREF_HEIGHT, bounds.height);
     
    			// Sauvegarde de la location de la fenêtre
    			prefs.putInt(PREF_X, bounds.x);
    			prefs.putInt(PREF_Y, bounds.y);
    		}
    	}
    }
      0  0

  12. #32
    Membre expert
    Avatar de ®om
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    2 815
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 2 815
    Points : 3 080
    Points
    3 080
    Par défaut Supprimer les accents d'une chaîne de caractères
    Pour supprimer les accents et caractères spéciaux d'une chaîne de caractères, ou encore supprimer les espaces en trop, une classe StringUtilities qui définit deux méthodes statiques String cleanSpecialCharacters(String) et String removeExtraSpaces(String).

    Le tableau de correspondance entre un caractère et sa chaîne de remplacement est chargé lors du premier besoin de remplacement, et si par la suite l'utilisation de la mémoire par le logiciel est trop importante, le GarbageCollector supprimera d'abord le tableau de correspondance grâce à l'utilisation d'une SoftReference, ce tableau sera rechargé plus tard si besoin.

    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
    import java.lang.ref.SoftReference;
     
    /**
     * Cette classe n'est composée que de méthodes statiques, utiles pour certains traitements de chaînes de caractères.
     * 
     * @author rom1v
     */
    public final class StringUtilities {
     
        /** Contient à l'indice (int)c - 192 la chaîne par lequel remplacer le caractère c. */
        private static SoftReference<String[]> charMap;
     
        /** Interdiction d'instancier. */
        private StringUtilities() {}
     
        /**
         * Nettoie la chaîne de caractères des caractères spéciaux (accents, etc...).
         * 
         * @param source
         *            Chaîne de caractères à nettoyer.
         * @return Chaîne de caractères nettoyée.
         */
        public static String cleanSpecialCharacters(String source) {
            String[] map = null;
     
            StringBuilder build = new StringBuilder();
            for(char c : source.toCharArray()) {
                if(c < 192 || c >= 256) {
                    /* Si le caractère n'est pas un caractère spécial, on l'ajoute tel quel. */
                    build.append(c);
                } else {
                    if(map == null) {
                        /* Si le tableau n'est pas encore chargé dans la méthode, on le récupère en mémoire. */
                        if(charMap != null)
                            map = charMap.get();
                        if(map == null) {
                            /* Si le tableau n'est pas disponible en mémoire, on le charge. */
                            map = makeCharMap();
                            charMap = new SoftReference<String[]>(map);
                        }
                    }
                    /* On ajoute à la chaîne de caractère la chaîne qui doit remplacer le caractère spécial. */
                    build.append(map[c - 192]);
                }
            }
            return new String(build);
        }
     
        /**
         * Retourne une chaîne de caractères correspondant à la source dans laquelle les espaces de début et de fin sont
         * supprimés, et où les espaces consécutifs sont remplacés par un seul espace.<p> Par exemple,
         * <code>removeExtraSpaces("   a bcd  e f    g   ")</code> retourne <code>a bcd e f g</code>.
         * 
         * @param source
         *            Chaîne de caractère source.
         * @return Chaîne de caractères dans laquelle les espaces en trop ont été supprimés.
         */
        public static String removeExtraSpaces(String source) {
            assert source != null : "La source ne doit pas être null";
            return source.trim().replaceAll("\\s{2,}", " ");
        }
     
        /**
         * Construit le tableau de correspondance de remplacement.
         * 
         * @return Tableau de correspondance de remplacement.
         */
        private static String[] makeCharMap() {
            String[] result = new String[64];
            String s;
     
            /* On remplit le tableau des correspondances des caractères 192 à 255. */
            int i = 0;
            s = "A";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "AE";
            result[i++] = "C";
            s = "E";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "I";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "D";
            result[i++] = "N";
            s = "O";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "*";
            result[i++] = "0";
            s = "U";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "Y";
            result[i++] = "D";
            result[i++] = "B";
            s = "a";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "ae";
            result[i++] = "c";
            s = "e";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "i";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "o";
            result[i++] = s;
            result[i++] = "n";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "/";
            result[i++] = "0";
            s = "u";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "y";
            result[i++] = s;
            result[i++] = "D";
            result[i++] = s;
            return result;
        }
     
    }
      0  0

  13. #33
    Membre éclairé
    Avatar de bbclone
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    537
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mai 2006
    Messages : 537
    Points : 704
    Points
    704
    Par défaut
    c'est quoi la classe ParameterUI?

    Citation Envoyé par GENERYS
    Voici le code d'un composant maison VerticalLabel.
    Si quelqu'un y voit des améliorations... je suis preneur...

    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
     
    public class VerticalLabel extends JLabel {
      /**
       * Nom à afficher.
       */
      private String          name;
     
      /**
       * Constructeur.
       * Initialise les valeurs de la classe.
       * 
       * @param name
       */
      public VerticalLabel(String name) {
        super();
        this.name = name;
      }
     
      /*
       *  (non-Javadoc)
       * @see javax.swing.JLabel#setText(java.lang.String)
       */
      public void setText(String text) {
        name = text;
        repaint();
      }
     
      /*
       *  (non-Javadoc)
       * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
       */
      protected void paintComponent(Graphics graphics) {
        Graphics2D graphics2D = (Graphics2D) graphics;
     
        super.paintComponent(graphics);
     
        graphics2D.setColor(ParameterUI.FONT_BORDER_COLOR);
        graphics2D.translate(0, getHeight());
        graphics2D.rotate(-Math.PI/2);
        graphics2D.setFont(ParameterUI.CHART_NAME_FONT);
        graphics2D.drawString(name, 0 , (getHeight()-getStringHeight())/2);
      }
     
      /*
       *  (non-Javadoc)
       * @see java.awt.Component#getPreferredSize()
       */
      public Dimension getPreferredSize() {
        Dimension dimension = new Dimension(getStringHeight(), getStringWidth());
        return dimension; 
      }
     
      /*
       *  (non-Javadoc)
       * @see java.awt.Component#getMinimumSize()
       */
      public Dimension getMinimumSize() {
        return getPreferredSize();
      }
     
      private int getStringWidth() {
        FontMetrics metrics = getFontMetrics(ParameterUI.CHART_NAME_FONT);
        int width = metrics.stringWidth(name);
     
        return width;
      }
     
      private int getStringHeight() {
        FontMetrics metrics = getFontMetrics(ParameterUI.CHART_NAME_FONT);
        int height = metrics.getHeight();
     
        return height;
      }
    }
      0  0

  14. #34
    Membre éclairé Avatar de g_rare
    Profil pro
    Inscrit en
    Novembre 2005
    Messages
    608
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2005
    Messages : 608
    Points : 683
    Points
    683
    Par défaut Validation XML par schéma XSD externe avec Xerces-J 1.4(.4) [sans JAXP]
    C'est ici qui faut regarder.

    Par contre un conseil pour éviter beaucoup de désagréments : utiliser une version 2.1.0+ de Xerces-J (actuellement 2.8.0), et respecter la norme de développement JAXP (pour passer à un parseur Crimson de manière transparente par exemple) !

    " Jag blev dömd för fildelning och allt jag fick var en sketen t-shirt. " (tankafritt.nu)
    PAS DE REPONSE PAR MESSAGE PRIVE ! Penser au bouton Résolu en bas de la discussion...
      0  0

  15. #35
    Membre expert
    Avatar de ®om
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    2 815
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 2 815
    Points : 3 080
    Points
    3 080
    Par défaut Comment supprimer les accents et autres caractères spéciaux d'une String?
    C'est peut-être un peu long pour être intégré à la FAQ, mais ça peut être utile

    Comment supprimer les accents et autres caractères spéciaux d'une String?

    Pour supprimer les accents et autres caractères spéciaux d'une chaîne de caractères, rien n'est prévu dans la class String.

    Voici donc une classe qui permet de faire ceci:

    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
    /**
     * Cette classe n'est composée que de méthodes statiques, utiles pour certains traitements de chaînes de caractères.
     * 
     * @author rom1v
     */
    public final class StringUtilities {
     
        /** Contient à l'indice (int)c - 192 la chaîne par lequel remplacer le caractère c. */
        private static SoftReference<String[]> charMap;
     
        /** Interdiction d'instancier. */
        private StringUtilities() {}
     
        /**
         * Nettoie la chaîne de caractères des caractères spéciaux (accents, etc...).
         * 
         * @param source
         *            Chaîne de caractères à nettoyer.
         * @return Chaîne de caractères nettoyée.
         */
        public static String cleanSpecialCharacters(String source) {
            String[] map = null;
     
            StringBuilder build = new StringBuilder();
            for(char c : source.toCharArray()) {
                if(c < 192 || c >= 256) {
                    /* Si le caractère n'est pas un caractère spécial, on l'ajoute tel quel. */
                    build.append(c);
                } else {
                    if(map == null) {
                        /* Si le tableau n'est pas encore chargé dans la méthode, on le récupère en mémoire. */
                        if(charMap != null)
                            map = charMap.get();
                        if(map == null) {
                            /* Si le tableau n'est pas disponible en mémoire, on le charge. */
                            map = buildCharMap();
                            charMap = new SoftReference<String[]>(map);
                        }
                    }
                    /* On ajoute à la chaîne de caractère la chaîne qui doit remplacer le caractère spécial. */
                    build.append(map[c - 192]);
                }
            }
            return new String(build);
        }
     
        /**
         * Construit le tableau de correspondance de remplacement.
         * 
         * @return Tableau de correspondance de remplacement.
         */
        private static String[] buildCharMap() {
            String[] result = new String[64];
            String s;
     
            /* On remplit le tableau des correspondances des caractères 192 à 255. */
            int i = 0;
            s = "A";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "AE";
            result[i++] = "C";
            s = "E";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "I";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "D";
            result[i++] = "N";
            s = "O";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "*";
            result[i++] = "0";
            s = "U";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "Y";
            result[i++] = "D";
            result[i++] = "B";
            s = "a";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "ae";
            result[i++] = "c";
            s = "e";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "i";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "o";
            result[i++] = s;
            result[i++] = "n";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = "/";
            result[i++] = "0";
            s = "u";
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            result[i++] = s;
            s = "y";
            result[i++] = s;
            result[i++] = "D";
            result[i++] = s;
            return result;
        }
     
    }
    L'utilisation de SoftReference pour stocker le tableau de correspondance permet au GarbageCollector de pouvoir supprimer ce tableau s'il a besoin de place.
      0  0

  16. #36
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    194
    Détails du profil
    Informations personnelles :
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations forums :
    Inscription : Juin 2006
    Messages : 194
    Points : 234
    Points
    234
    Par défaut
    Une classe d'une très grande simplicité et qui trouve d'intérêt dans le concept qu'elle apporte d'avantage que dans son aspect technique. Il s'agit d'un tampon de lecture FIFO, mais plus simple et plus rapide à utiliser que les Queue.

    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
     
    /**
     * Un Tube peut être utilisé comme tampon de lecture FIFO (first in first out)
     * tout comme les Queue, mais elle a une taille fixe. Ce tampon fonctionne comme
     * un tube : il se remplit avec la méthode fill(), ce qui fait sortir l'élément
     * le plus ancien si le tube est plein.
     * 
     * Il est possible, en fin d'utilisation, de vider le tube avec drain(). Cette
     * méthode ne devrait être appelée que pour vider complètement le tube afin de
     * ne pas créer de "bulle" dans le tube.
     * 
     * @author Had35
     * 
     * @param <T>
     */
    public class Tube<T> {
    	private Object[] temp;
    	private int cursor;
     
    	/**
             * Un Tube a une taille fixe.
             * @param size La capacité du tube
             */
    	public Tube(int size) {
    		temp = new Object[size];
    		cursor = 0;
    	}
     
    	/**
             * Remplit le tube. Celui-ci ayant une capacité fixe, la méthode de remplissage
             * retourne l'élément le plus ancien pour laisser la place au plus récent.
             * 
             * @param element Un nouvel élément
             * @return L'élément le plus ancien, null si le tube n'est pas encore remplit
             */
    	public T push(T element) {
    		return fill(element);
    	}
     
    	/**
             * Remplit le tube. Celui-ci ayant une capacité fixe, la méthode de remplissage
             * retourne l'élément le plus ancien pour laisser la place au plus récent.
             * 
             * @param element Un nouvel élément
             * @return L'élément le plus ancien, null si le tube n'est pas encore remplit
             * @deprecated
             */
    	@deprecated
    	public T fill(T element) {
    		if(cursor == temp.length)
    			cursor = 0;
     
    		Object firstIn = temp[cursor];
    		temp[cursor++] = element;
     
    		return (T)firstIn;
    	}
     
    	/**
             * Vide le tube en respectant le principe FIFO. Cette méthode est conçue pour
             * récupérer les éléments restant dans le tampon après son utilisation.
             * Le vidage du tube en cours de remplissage crée des "bulles d'air" qui ne
             * porte pas atteinte au principe FIFO mais qui peut poser problème lors du
             * vidage complet.
             * 
             * @return L'élément le plus ancien
             */
    	public T drain() {
    		if(cursor == temp.length)
    			cursor = 0;
     
    		Object firstIn = temp[cursor];
    		temp[cursor++] = null;
     
    		return (T)firstIn;
    	}
    }
    J'ai réédité le code pour modifier la signature de la méthode d'ajout. push() me parait finalement plus clair que fill() à l'utilisation.
      0  0

  17. #37
    Membre du Club
    Inscrit en
    Octobre 2004
    Messages
    50
    Détails du profil
    Informations forums :
    Inscription : Octobre 2004
    Messages : 50
    Points : 48
    Points
    48
    Par défaut
    Dans un programme j'avais une JComboBox qui contenait plus de 200 items, pour simplifier la sélection j'ai voulu faire l'autocomplete lors de la saisie.
    Apres qq recherche sur le net , j ai trouver très peu d'info sur des JComboBox editable avec autocomplete.
    Après quelques heure j'ai réalisé cette fonctionalité qui à l'aire de marcher plustot bien. toutes les critiques sont les bienvenue.

    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
     
    /**
     * @author Damien IELSCH
     *
     */
    public class AutoCompleteCombo extends JComboBox implements KeyListener
    {
     
    	  public AutoCompleteCombo() 
    	  {
    	    super(new DefaultComboBoxModel());
    	    setEditable(true);
    	    getEditor().getEditorComponent().addKeyListener(this);
    	  }
     
    	public void keyPressed(KeyEvent e) {
    	}
     
    	public void keyTyped(KeyEvent e) {
    	}
    /**
    *controle et recherche lors du keyReleased
    */
    	public void keyReleased(KeyEvent e) {
     
    		JTextField editor=(JTextField)getEditor().getEditorComponent();
    		if(e.getKeyCode()!=KeyEvent.VK_LEFT&&e.getKeyCode()!=KeyEvent.VK_RIGHT&&e.getKeyCode()!=KeyEvent.VK_UP&&e.getKeyCode()!=KeyEvent.VK_DOWN&&e.getKeyCode()!=36 )//36= debut de ligne
    		{//on evite de faire le traitement sur les touche fleche de deplacement
     
     
                            if(getItemCount()==0)
    			{
    				editor.setText("");
    				return;
    			}
    			int caretpos=editor.getCaretPosition();
    			if(!editor.getText().equalsIgnoreCase(""))
    			{//si on saisie qq chose
    				String debut=editor.getText().substring(0, caretpos);
    				if(!debut.equalsIgnoreCase(""))// si debut n est pas vide=> on fesait un saisie
    				{
    					int index=getindex(debut);
    					while(index==-1)//si plusieurs lettres on ete saisie avant le relachement de la touche, il fau tous supprimer jusqua ce que l'on trouve un item qui correspond
    					{	
    						if(debut.length()>=2)//on avai saisi plus d'une lettre on supprime la derniere saisie
    						{
    							editor.setText(debut.substring(0, debut.length()-1));
    							debut=debut.substring(0, debut.length()-1);
                                                            index=getindex(debut);
    						}
    						else//on avait saisi 1 lettres, rien ne corespond=> on efface
    						{
    							index=0;
    						}
     
    					}
    					// on a trouver  un item correspondant à la saisie
    					{
    						setSelectedIndex(index);
    						editor.setText(getSelectedItem().toString());
    						editor.setCaretPosition(debut.length());	
     
    					}
     
    				}
    				else// debut est vide, on fesait une suppression
    				{
    					setSelectedIndex(0);
    					editor.setText(getModel().getElementAt(0).toString());
    					editor.setCaretPosition(0);
    				}
    			}
    			else//si rien n est saisi on se positionne sur le 1er element
    			{
    				setSelectedIndex(0);
    			}
    		}
    	}
    	/**
            *on cherche à quel item la string debut correspond
            */
    	private int getindex(String debut)
    	{
    		int res=-1;
    		DefaultComboBoxModel dtm=(DefaultComboBoxModel)getModel();
    		for(int i=0;i<dtm.getSize();i++)
    		{
    			if(dtm.getElementAt(i).toString().toUpperCase().startsWith(debut))
    				return i;
    		}
    		return res;
    	}
     
    }
      0  0

  18. #38
    Expert éminent sénior
    Avatar de Baptiste Wicht
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2005
    Messages
    7 431
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Suisse

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2005
    Messages : 7 431
    Points : 21 324
    Points
    21 324
    Par défaut
    Je propose une petite classe qui permet de gérer une liste de données en relation avec un id. Elle est générique, les données peuvent donc être de n'importe quel type et en plus, elle est employable dans les boucles foreach vu qu'elle implémente Iterable.

    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
    package utils;
     
    import java.util.ArrayList;
    import java.util.Iterator;
     
    /**
     * Cette classe permet la gestion d'une liste de couple clé-valeur. On peut récupérer soit la valeur soit 
     * l'id via l'autre partie du couple et récupérer le valeur en fonction de sa place dans la liste.
     * @author Wichtounet
     *
     */
    public class Stock<T> implements Iterable<T>{
    	/* Listes contentants les ids et les objets*/
    	private ArrayList<T> datas = null;
    	private ArrayList<Integer> ids = null;
     
    	//Position actuelle de lecture
    	private int position = -1;
     
    	/**
             * Constructeur de la classe, il initialise les deux listes de données
             *
             */
    	public Stock(){
    		super();
     
    		ids = new ArrayList<Integer>();
    		datas = new ArrayList<T>();
    	}
     
    	/**
             * Méthode pour ajouter un nouveau couple dans la collection
             * @param id, l'id du couple
             * @param value, la valeur du couple
             */
    	public void put(int id, T value){
    		ids.add(id);
          	datas.add(value);
    	}
     
    	/**
             * Cette méthode permet de récupérer une valeur à partir d'un id
             * @param id, id de la valeur à récupérer
             * @return La valeur correspondant à l'id
             */
    	public T getValueOf(int id){
    		int index = ids.indexOf(id);
     
    		if (index >= 0){
    			return (T)datas.get(index);          
    		}
     
    		return null;
    	}
     
    	/**
             * Cette méthode permet de récupérer un id à partir d'une valeur
             * @param value, valeur dont on recherche l'id
             * @return L'id
             */
    	public Integer getIdOf(T value){
    		int index = datas.indexOf(value);
     
    		if(index > 0){
    			return (Integer)ids.get(index);
    		}
     
    		return null;
    	}
     
    	/**
             * Méthode qui retourne le nombre d'éléments du tableau
             * @return Le nombre d'éléments de la collection
             */
    	public int getItemCount(){
    		return datas.size();
    	}
     
    	/**
             * Méthode qui dit s'l reste encore des éléments avant la fin du parcous
             * @return true ou false
             */
    	public boolean hasNext(){		
    		return position < datas.size() -1;
    	}
     
    	/**
             * Méthode qui retourne l'élément suivant dans la collection
             * @return La valeur de l'élément
             */
    	public T next(){
    		position++;
    		return datas.get(position);
    	}
     
    	/**
             * Méthode qui retourne l'id de l'élément courant
             * @return id de l'élément courant
             */
    	public int getCurrentId(){
    		return ids.get(position);
    	}
     
    	/**
             * Méthode qui revient au début de la collection pour permettre un deuxième parcours
             *
             */
    	public void first(){
    		position = -1;
    	}
     
    	/**
             * Cette méthode permet de vérifier si un id est déja contenu ou non dans la liste
             * @param id L'id à rechercher
             * @return true si l'id est trouvé et false s'il ne l'est pas
             */
    	public boolean containsID(Integer id){
    		return ids.contains(id);
    	}
     
    	/**
             * Cette méthode permet de vérifier si une valeur est déja contenu ou non dans la liste
             * @param value La valeur à rechercher
             * @return true si la valeur est trouvée et false s'elle ne l'est pas
             */
    	public boolean containsValue(T value){
    		return datas.contains(value);
    	}
     
    	/**
             * Cette méthode permet de générer un itérateur des données contenues dans le classe
             */
    	public Iterator<T> iterator() {
    		return datas.iterator();
    	}
    }
    Si vous des commentaires ou des idées d'amélioration, n'hésitez pas

    Je l'utilise dans plusieurs de mes projets, vous pouvez donc normalement (on n'est jamais à l'abri d'une erreur) y aller sans trop de risques
      0  0

  19. #39
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Points : 5 943
    Points
    5 943
    Par défaut
    Voici des AbstractTableModel qui permettent de créer des JTables en fonction des propriétés d'un javabean. Ces classes utilisent la réflexion pour générer les colonnes en fonction des getters/setters du javabean considéré.

    Il y a troid classes,
    • une classe abstraite : AutoTableModel
    • une classe pour générer une table en lecture seule (uniquement les getters sont pris en compte) : ReadAutoTableModel
    • une classe en pour générer une table en lecture/écriture : ReadWriteAutoTableModel
    Remarque : Les deux dernières utilisent une méthode getWrapper() que vous trouverez dans un code que j'avais posté ici.

    Remarque2 : Ce code date de mes débuts en Java, il y a surement des choses à redire , de plus il n'est pas commenté.

    AutoTableModel.java
    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
    /*
     * AutoTableModel.java
     */
     
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Hashtable;
    import java.util.List;
    import javax.swing.table.AbstractTableModel;
     
    /**
     * @author Yann D'ISANTO
     */
    abstract public class AutoTableModel extends AbstractTableModel {
        private static final long serialVersionUID = 2097121494L;
     
        protected Class type;
        protected List<?> list;
        protected List<String> columnsName;
        protected List<Class<?>> columnsClass;
     
     
        public AutoTableModel(Class clazz) {
            type = clazz;
            list = new ArrayList();
            columnsName = new ArrayList<String>();
            columnsClass = new ArrayList<Class<?>>();
        }
     
        public void setData(List<?> list) {
            this.list = list;
            this.fireTableDataChanged();
        }
     
        public Class getType() {
            return this.type;
        }
     
        public String getColumnName(int columnIndex) {
            return columnsName.get(columnIndex);
        }
     
        public Class<?> getColumnClass(int columnIndex) {
            return columnsClass.get(columnIndex);
        }
     
    }
    ReadAutoTableModel.java
    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
    /*
     * ReadAutoTableModel.java
     */
     
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Hashtable;
    import java.util.List;
    import static ReflectTools.getWrapper;
     
    /**
     *
     * @author Yann D'ISANTO
     */
    public class ReadAutoTableModel extends AutoTableModel {
        private static final long serialVersionUID = 558231968L;
     
        private Hashtable<String, Method> columnsGetters;
     
        /** Creates a new instance of ReadAutoTableModel */
        public ReadAutoTableModel(Class clazz) {
            super(clazz);
            columnsGetters = new Hashtable<String, Method>();
            Method[] methods = clazz.getMethods();
            for(Method m : methods) {
                if((m.getName().length() > 3) && !m.getName().equals("getClass")) {
                    String name = "";
                    if(m.getName().startsWith("get")) {
                        name = m.getName().substring(3, m.getName().length());
                        columnsGetters.put(name, m);
                        int index = columnsName.indexOf(name);
                        if(index == -1) {
                            columnsName.add(name);
                            columnsClass.add(getWrapper(m.getReturnType()));
                        }
                    }
                    else if(m.getName().startsWith("is")) {
                        name = m.getName().substring(2, m.getName().length());
                        columnsGetters.put(name, m);
                        int index = columnsName.indexOf(name);
                        if(index == -1) {
                            columnsName.add(name);
                            columnsClass.add(getWrapper(m.getReturnType()));
                        }
                    }
                }
            }
        }
     
     
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object ret = null;
            if((columnIndex >= 0) && (columnIndex < columnsName.size())) {
                Object o = type.cast(list.get(rowIndex));
                String name = columnsName.get(columnIndex);
                Method m = columnsGetters.get(name);
                try {
                    ret = m.invoke(o);
                } catch(IllegalAccessException iae) {
                    iae.printStackTrace();
                } catch(InvocationTargetException ite) {
                    ite.printStackTrace();
                }
            }
            return ret;
        }
     
        public int getColumnCount() {
            return columnsName.size();
        }
        public int getRowCount() {
            return list.size();
        }
        public String getColumnName(int column) {
            return columnsName.get(column);
        }
    }
    ReadWriteAutoTableModel.java
    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
    /*
     * ReadWriteAutoTableModel.java
     */
     
    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Hashtable;
    import java.util.List;
    import static ReflectTools.getWrapper;
    /**
     *
     * @author Yann D'ISANTO
     */
    public class ReadWriteAutoTableModel extends ReadAutoTableModel {
        private static final long serialVersionUID = 939106509L;
     
        private Hashtable<String, Method> columnsSetters;
     
        /** Creates a new instance of ReadWriteAutoTableModel */
        public ReadWriteAutoTableModel(Class clazz) {
            super(clazz);
            columnsSetters = new Hashtable<String, Method>();
            Method[] methods = clazz.getMethods();
            for(Method m : methods) {
                if((m.getName().length() > 3) && 
                        m.getName().startsWith("set")) {
                    String name = m.getName().substring(3, m.getName().length());
                    columnsSetters.put(name, m);
                    int index = columnsName.indexOf(name);
                    Class c = getWrapper(m.getParameterTypes()[0]);
                    if(index == -1) {
                        columnsClass.add(c);
                    } else {
                        columnsClass.add(index, c);
                    }
                }
            }
        }
     
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return (columnsSetters.get(columnsName.get(columnIndex)) == null) 
                    ? false : true;
        }
     
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if((columnIndex >= 0) && 
               (columnIndex < columnsName.size())) {
                Object o = type.cast(list.get(rowIndex));
                String name = columnsName.get(columnIndex);
                Method m = columnsSetters.get(name);
                try {
                    m.invoke(o, aValue);
                } catch(IllegalAccessException iae) {
                    iae.printStackTrace();
                } catch(InvocationTargetException ite) {
                    ite.printStackTrace();
                }
            }
        }
    }
    Exemple d'utilisation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    AutoTableModel model = new ReadWriteAutoTableModel(MyClass.class);
    model.setData(list);
    JTable table = new JTable(model);
    où list est une List<MyClass>.
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr
      0  0

  20. #40
    Membre émérite
    Avatar de xavlours
    Inscrit en
    Février 2004
    Messages
    1 832
    Détails du profil
    Informations forums :
    Inscription : Février 2004
    Messages : 1 832
    Points : 2 410
    Points
    2 410
    Par défaut
    Citation Envoyé par xavlours
    Bonjour,

    voici une classe qui permet de scroller comme dans Firefox (un clic sur la molette entraine le mode scroll automatique). Si vous programmez pour des flemmards vous allez vous faire des amis .
    Finalement, j'ai décidé de supprimer mon code source après 2 découvertes :
    - la première, c'est sinok qui me l'a montrée dans les messages suivants. Santosh Kumar l'a déjà fait en mieux à tous les points de vue. Je n'ai trouvé qu'une exception : si on veut faire du scroll tout en gardant un glasspane actif (genre, on est en train de faire un drag and drop avec style, et là, paf, on fait un coup de scroll à coup de clic molette) ... un peu tordu, quand même.
    - la deuxième, je l'ai trouvé ici : A well behaved GlassPane, ou l'on apprend que le code de GlassPaneDemo (dont je me suis beaucoup servi) n'est pas du tout le meilleur, et contient des bugs. Et forcément, la façon correcte de faire un GlassPane ressemble énormément à celle de Santosh Kumar.

    Pour ce code, je vous redirige donc vers le blog de Santosh Kumar.
    "Le bon ni le mauvais ne me feraient de peine si si si je savais que j'en aurais l'étrenne." B.V.
    Non au langage SMS ! Je ne répondrai pas aux questions techniques par MP.
    Eclipse : News, FAQ, Cours, Livres, Blogs.Et moi.
      0  0

Discussions similaires

  1. Page Code Source, mettez vos codes ici
    Par Bovino dans le forum Contribuez
    Réponses: 8
    Dernier message: 05/12/2008, 12h11
  2. Participez à la FAQ VBA ou à la page Sources
    Par Nightfall dans le forum Contribuez
    Réponses: 1
    Dernier message: 04/08/2006, 17h34

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