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. #1
    Rédacteur

    Avatar de Mickael Baron
    Homme Profil pro
    Ingénieur de Recherche en Informatique
    Inscrit en
    Juillet 2005
    Messages
    14 974
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vienne (Poitou Charente)

    Informations professionnelles :
    Activité : Ingénieur de Recherche en Informatique
    Secteur : Service public

    Informations forums :
    Inscription : Juillet 2005
    Messages : 14 974
    Points : 73 024
    Points
    73 024
    Par défaut Page Sources Java libres - participez ici
    Bonjour à tous.

    L'équipe a pensé qu'il pourrait être intéressant de mettre à disposition une page recensant les petits bouts de codes récurrents, plutôt utiles pour vos développements.
    Nous nous efforcerons d'adapter ceux mis dans le forum également.

    Merci donc, de poster sur cette application ce que vous souhaitez mettre à la disposition de tous (votre code, ou celui d'autres). Ce code est entièrement libre et gratuit et pourra être réutilisé même dans des applications commerciales.

    Merci de nous aider dans ce sens, et de permettre ainsi d'aider encore plus de monde.

    L'équipe Java.
    Responsable Java de Developpez.com (Twitter et Facebook)
    Besoin d"un article/tutoriel/cours sur Java, consulter la page cours
    N'hésitez pas à consulter la FAQ Java et à poser vos questions sur les forums d'entraide Java
    --------
    Ingénieur de Recherche en informatique au LIAS / ISAE-ENSMA
    Page de Developpez.com : mbaron.developpez.com
    Twitter : www.twitter.com/mickaelbaron
    Blog : mickael-baron.fr
    LinkedIn : www.linkedin.com/in/mickaelbaron
    DBLP : dblp.uni-trier.de/pers/hd/b/Baron:Micka=euml=l
      2  0

  2. #2
    Membre actif

    Inscrit en
    Septembre 2004
    Messages
    108
    Détails du profil
    Informations forums :
    Inscription : Septembre 2004
    Messages : 108
    Points : 229
    Points
    229
    Par défaut
    A travers mon exploration des packages de java, j'ai réalisé que la classe random etait vraiment assez limitée ,

    voici la mienne , elle permet de gener un Date,un Time, un int,un double, un float... et tous compris entre une valeur de depart et une valeur de fin:

    SVP:tous commentaires concernant les ameloirations possibles ou bugs sont les bienvenus

    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
    /*
     * Created on 17 mai 2005
     * you can use it as ever you want
     */
    package random;
    import java.sql.Date;
    import java.sql.Time;
    import java.sql.Timestamp;
    import java.util.Random;
    import javax.swing.JTextField;
     
    /**
     * @author komando
     * @version 1.0
     *  Class RandomObject uses java.util.Random to generate various random 
     *  such as Date, Time, Long, Int 
     */
     
    public class RandomObject extends Random{
     
    	private static final char chars[]={'a','b','c','d','e','f','g','h','i','j',
    			'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    	private static final int LIMIT = 1000;
    	private long echelle;
    	private int init;
     
    	private static final double D_LIMIT = 1.0;
    	private double dechelle;
    	private double dinit=0.0;
     
    	public RandomObject(){
    		super();
    	}
     
    	/** 
             * @param debut
             * @param fin
             * @return this int between debut and fin
             */
     
    	public int nextInt(int debut, int fin) {
    		int val = this.nextInt(fin);
    		return debut + val * (fin - debut) / fin;
    	}
     
    	/**
             * converts String to int
             * @param debutstr
             * @param finstr
             * @return this int between debut and fin
             */
     
    	public int nextInt(String debutstr, String finstr) {
    		int debut, fin;
    		try{
    			debut = Integer.parseInt(debutstr);
    			fin = Integer.parseInt(finstr);
    		}
    		catch(NumberFormatException e){
    			e.getMessage();
    			return -1;
    		}
    		return nextInt(debut,fin);
    	}
     
    	/**
             * reads txtFields and return this int between them
             * @param debtxtField
             * @param fintxtField
             * @return this int between txtFields
             */
     
    	public int nextInt(JTextField debtxtField,JTextField fintxtField) {
    		return nextInt(debtxtField.getText(),fintxtField.getText());
    	}
     
    	/**
             * reads txtFields and return this int between them
             * @deprecated
             * @param txtFields
             * @return andom int between txtFields
             */
     
    	public int nextInt(JTextField txtFields[]) {
    		return nextInt(txtFields[0].getText(),txtFields[1].getText());
    	}
     
    	/**
             * @param debut
             * @param fin
             * @return this long between long debut and fin
             */ 
     
    	public long nextLong(long debut,long fin){
    		int randint;
    		int adjust;
    		long randlong;
    		//setting a scale an generating this int
    		echelle = fin / LIMIT;
    		init = (int) (debut / echelle);
    		randint = this.nextInt(LIMIT);
    		//adjusting this int and resetting the scale 
    		adjust = init + randint * (LIMIT - init) / LIMIT;
    		randlong = adjust * echelle;
    		return randlong;
    	}
     
    	/**
             * 
             * @param debut
             * @param fin
             * @return this long between String debut and fin
             */
     
    	public long nextLong(String debutstr,String finstr){
    		long debut,fin;
    		try{
    		debut=(long) Integer.parseInt(debutstr);
    		fin=(long) Integer.parseInt(finstr);
    		}
    		catch(NumberFormatException e){
    			e.getMessage();
    			return -1;
    		}
    		return nextLong(debut,fin);
    	}
     
    	/**
             * 
             * @param debut
             * @param fin
             * @return this date between long datedebut and datefin
             */
     
    	public Date nextDate(long debut, long fin){
    		return new Date(nextLong(debut,fin));
    	}
     
    	/**
             * @param datedebut
             * @param datefin
             * @return this date between Date datedebut and datefin
             */
     
    	public Date nextDate(Date datedebut, Date datefin) {
    		long debut, fin;
    		//return dates in ms
    		debut = datedebut.getTime();
    		fin = datefin.getTime();
    		return nextDate(debut,fin);
    	}
     
    	/**
             * @param debut
             * @param fin
             * @return this date between string debut and fin
             */
     
    	public Date nextDate(String debutstr, String finstr) {
    		Date datedebut, datefin;
    		datedebut = Date.valueOf(debutstr);
    		datefin = Date.valueOf(finstr);
    		return nextDate(datedebut,datefin);
    	}
     
    	/**
             * 
             * @param debtxtField
             * @param fintxtField
             * @return this date between Fields debut and fin
             */
     
    	public Date nextDate(JTextField debtxtField,JTextField fintxtField) {
    		return nextDate(debtxtField.getText(),fintxtField.getText());
    	}
     
    	/**
             * @deprecated
             * @param txtFields
             * @return this date between Fields txtFields[0] and txtFields[1]
             */
     
    	public Date nextDate(JTextField txtFields[]){
    		return nextDate(txtFields[0].getText(),txtFields[1].getText());
    	}
     
    	public Time nextTime(long debut,long fin){
    		return new Time(nextLong(debut,fin));
    	}
     
    	/**
             * @param timedebut
             * @param timefin
             * @return this Time between long debut and fin
             */
     
    	public Time nextTime(Time timedebut,Time timefin){
    		long debut, fin;
    		//return dates in ms
    		debut = timedebut.getTime();
    		fin = timefin.getTime();
    		return nextTime(debut,fin);
    	}
     
    	/**
             * @param debut
             * @param fin
             * @return this Time between string debut and fin
             */
     
    	public Time nextTime(String debutstr, String finstr) {
    		Time timedebut, timefin;
    		timedebut = Time.valueOf(debutstr);
    		timefin = Time.valueOf(finstr);
    		return nextTime(timedebut,timefin);
    	}
     
    	/**
             * 
             * @param debtxtField
             * @param fintxtField
             * @return this Time between Fields debut and fin
             */
     
    	public Time nextTime(JTextField debtxtField,JTextField fintxtField) {
    		return nextTime(debtxtField.getText(),fintxtField.getText());
    	}
     
    	/**
             * @deprecated
             * @param txtFields
             * @return this Time between Fields txtFields[0] and txtFields[1]
             */
     
    	public Time nextTime(JTextField txtFields[]){
    		return nextTime(txtFields[0].getText(),txtFields[1].getText());
    	}
     
    	/**
             * 
             * @param debut
             * @param fin
             * @return
             */
     
    	public Timestamp nextTimestamp(long debut,long fin){
    		return new Timestamp(nextLong(debut,fin));
    	}
     
    	/**
             * @param timedebut
             * @param timefin
             * @return
             */
     
    	public Timestamp nextTimestamp(Timestamp timedebut,Timestamp timefin){
    		long debut, fin;
    		//return dates in ms
    		debut = timedebut.getTime();
    		fin = timefin.getTime();
    		return nextTimestamp(debut,fin);
    	}
     
    	/**
             * @param debut
             * @param fin
             * @return this Timestamp between string debut and fin
             */
     
    	public Timestamp nextTimestamp(String debutstr, String finstr) {
    		Timestamp timedebut, timefin;
    		timedebut = Timestamp.valueOf(debutstr);
    		timefin = Timestamp.valueOf(finstr);
    		return nextTimestamp(timedebut,timefin);
    	}
     
    	/**
             * 
             * @param debtxtField
             * @param fintxtField
             * @return this Timestamp between Fields debut and fin
             */
     
    	public Timestamp nextTimestamp(JTextField debtxtField,JTextField fintxtField) {
    		return nextTimestamp(debtxtField.getText(),fintxtField.getText());
    	}
     
    	/**
             * @deprecated
             * @param txtFields
             * @return this Timestamp between Fields txtFields[0] and txtFields[1]
             */
     
    	public Timestamp nextTimestamp(JTextField txtFields[]){
    		return nextTimestamp(txtFields[0].getText(),txtFields[1].getText());
    	}
     
    	/**
             * 
             * @return
             */
    	public char nextChar(){
    		return chars[nextInt(chars.length)];
     
    	}
     
    	/**
             * @deprecated
             * @return
             */
     
    	public String nextString(){
    		String str="";
    		for &#40;int i = 0; i < nextInt&#40;&#41;; i++&#41; &#123;
    			str+=nextChar&#40;&#41;;
    		&#125;
    		return str;
    	&#125;
     
    	public String nextString&#40;int lenght&#41;&#123;
    		String str="";
    		for &#40;int i = 0; i < lenght; i++&#41; &#123;
    			str+=nextChar&#40;&#41;;
    		&#125;
    		return str;
    	&#125;
     
    	/**
             * 
             * @param debut
             * @param fin
             * @return
             */
     
    	public float nextFloat&#40;float debut,float fin&#41;&#123;
    		float randint;
    		float adjust;
    		float randlong;
    		//setting a scale an generating this float
    		dechelle = fin / D_LIMIT;
    		dinit =  debut / dechelle;
    		randint = this.nextFloat&#40;&#41;;
    		//adjusting this int and resetting the scale 
    		adjust = &#40;float&#41; &#40;dinit + randint * &#40;D_LIMIT - dinit&#41; / D_LIMIT&#41;;
    		randlong = &#40;float&#41; &#40;adjust * dechelle&#41;;
    		return randlong;
    	&#125;
     
    	/**
             * 
             * @param strdebut
             * @param strfin
             * @return
             */
    	public float nextFloat&#40;String strdebut, String strfin&#41;&#123;
    		float debut,fin;
    		try&#123;
    			debut =  Float.parseFloat&#40;strdebut&#41;;
    			fin = Float.parseFloat&#40;strfin&#41;;			
    		&#125;
    		catch&#40;NumberFormatException e&#41;&#123;
    			e.getMessage&#40;&#41;;
    			return -1;
    		&#125;
    		return nextFloat&#40;debut,fin&#41;;
    	&#125;
     
    	/**
             * 
             * @param debTextfield
             * @param finTextfield
             * @return
             */
    	public float nextFloat&#40;JTextField debTextfield,JTextField finTextfield&#41;&#123;
    		return nextFloat&#40;debTextfield.getText&#40;&#41;,finTextfield.getText&#40;&#41;&#41;;
    	&#125;
     
    	/**
             * @deprecated
             * @param txtFields
             * @return
             */
    	public float nextFloat&#40;JTextField txtFields&#91;&#93;&#41;&#123;
    		return nextFloat&#40;txtFields&#91;0&#93;,txtFields&#91;1&#93;&#41;;
    	&#125;
     
    	/**
             * 
             * @param debut
             * @param fin
             * @return
             */
     
    	public double nextDouble&#40;double debut,double fin&#41;&#123;
    		double randint;
    		double adjust;
    		double randlong;
    		//setting a scale an generating this double
    		dechelle = fin / D_LIMIT;
    		dinit =  debut / dechelle;
    		randint = this.nextDouble&#40;&#41;;
    		//adjusting this int and resetting the scale 
    		adjust =  &#40;dinit + randint * &#40;D_LIMIT - dinit&#41; / D_LIMIT&#41;;
    		randlong =  &#40;adjust * dechelle&#41;;
    		return randlong;
    	&#125;
     
    	/**
             * 
             * @param strdebut
             * @param strfin
             * @return
             */
    	public double nextDouble&#40;String strdebut, String strfin&#41;&#123;
    		double debut,fin;
    		try&#123;
    			debut =  Double.parseDouble&#40;strdebut&#41;;
    			fin = Double.parseDouble&#40;strfin&#41;;			
    		&#125;
    		catch&#40;NumberFormatException e&#41;&#123;
    			e.getMessage&#40;&#41;;
    			return -1;
    		&#125;
    		return nextDouble&#40;debut,fin&#41;;
    	&#125;
     
    	/**
             * 
             * @param debTextfield
             * @param finTextfield
             * @return
             */
    	public double nextDouble&#40;JTextField debTextfield,JTextField finTextfield&#41;&#123;
    		return nextDouble&#40;debTextfield.getText&#40;&#41;,finTextfield.getText&#40;&#41;&#41;;
    	&#125;
     
    	/**
             * @deprecated
             * @param txtFields
             * @return
             */
    	public double nextDouble&#40;JTextField txtFields&#91;&#93;&#41;&#123;
    		return nextDouble&#40;txtFields&#91;0&#93;,txtFields&#91;1&#93;&#41;;
    	&#125;
    	/**
             * Test Method
             * @param args
             */
     
    	public static void main&#40;String args&#91;&#93;&#41;&#123;
    		RandomObject r=new RandomObject&#40;&#41;;
    		for &#40;int i = 0; i < 1000; i++&#41; &#123;
    //			System.out.println&#40;"random int    "+r.nextInt&#40;100,1000&#41;&#41;;
    //			System.out.println&#40;"random int    "+r.nextInt&#40;"100","1000"&#41;&#41;;
    //			System.out.println&#40;"random long   "+r.nextLong&#40;1000000L,10000000L&#41;&#41;;
    //			System.out.println&#40;"random date   "+r.nextDate&#40;"2005-01-01","2005-12-31"&#41;&#41;;
    //			System.out.println&#40;"random time   "+r.nextTime&#40;"08&#58;00&#58;00","23&#58;00&#58;00"&#41;&#41;;
    //			System.out.println&#40;r.nextString&#40;5&#41;&#41;;
    			System.out.println&#40;r.nextDouble&#40;2.20,58.215&#41;&#41;;
    		&#125;
    	&#125;
    &#125;
      1  0

  3. #3
    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
    salut à tous,

    ce code porte sur la reflection, a priori il marche mais comme cela ne fais que trois semaines que j'ai commencé le java, j'aimerais avoir votre avis sur ce code et si il est correct je suis pret à le partager.

    [EDIT] Mis à jour le 26/01/2007 [/EDIT]

    ReflectTools.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
    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
     
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Hashtable;
    import java.util.Map;
     
    /**
     *
     * @author Yann D'Isanto
     */
    public final class ReflectTools {
     
        private ReflectTools() {}
     
        static final private Map<String, Class> wrappers = new Hashtable<String, Class>();
     
        static {
            wrappers.put("void", java.lang.Void.class);
            wrappers.put("boolean", java.lang.Boolean.class);
            wrappers.put("char", java.lang.Character.class);
            wrappers.put("byte", java.lang.Byte.class);
            wrappers.put("short", java.lang.Short.class);
            wrappers.put("int", java.lang.Integer.class);
            wrappers.put("long", java.lang.Long.class);
            wrappers.put("float", java.lang.Float.class);
            wrappers.put("double", java.lang.Double.class);
        }
     
        /**
         * Cree une nouvelle instance d'un objet dont un constructeur est passe en
         * parametre
         *
         *
         * @param constructor Constructeur
         * @param parameters Parametres a passer au constructeur
         * @return Nouvelle instance de l'objet dont le constructeur a ete passe en
         * parametre
         */
        public static final Object newInstance(Constructor constructor,
                Object ...parameters)
                throws IllegalAccessException,
                InstantiationException,
                InvocationTargetException,
                //ReflectionException,
                ConstructorNotFoundException {
            int parametersCount = parameters.length;
            if(parametersCount != constructor.getParameterTypes().length) {
                //throw new ReflectionException("Constructeur inexistant");
                throw new ConstructorNotFoundException(constructor);
            }
            // Comparaison des types des parametres
            for(int i = 0;i < parametersCount;i++) {
                String constructorParameterType;
                constructorParameterType = null;
                try {
                    constructorParameterType = getWrapperName(constructor.
                            getParameterTypes()[i].getName());
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
                String parameterType = parameters[i].getClass().getName();
                if(!constructorParameterType.equals(parameterType)) {
                    //throw new ReflectionException("Constructeur inexistant");
                    throw new ConstructorNotFoundException(constructor);
                }
            }
            return constructor.newInstance(parameters);
        }
     
     
        /**
         * Cree une nouvelle instance d'une classe passee en parametre
         *
         *
         * @param c Classe dont on veut une instance
         * @param parameters Parametres a passer au constructeur
         * @return Nouvelle instance de la classe passee en parametre
         */
        public static final Object newInstance(Class c, Object ...parameters)
        throws InstantiationException,
                IllegalAccessException,
                InvocationTargetException,
                //ReflectionException,
                ConstructorNotFoundException {
            int parametersCount = parameters.length;
            Constructor []tConstructors = c.getConstructors();
            Object instance = null;
     
            // Parcours des constructeurs de la classe passee en parametre
            for(Constructor currentConstructor : tConstructors) {
                int constructorParametersCount = currentConstructor.getParameterTypes(
                        ).length;
                if(constructorParametersCount != parametersCount) {
                    continue;
                }
                boolean allTypesOK = true;
                // Comparaison des types des parametres
                for(int i = 0;i < parametersCount;i++) {
                    String constructorParameterType = null;
                    try {
                        constructorParameterType = getWrapperName(currentConstructor.
                                getParameterTypes()[i].getName());
                    } catch (ClassNotFoundException ex) {
                        ex.printStackTrace();
                    }
                    String parameterType = parameters[i].getClass().getName();
                    if(!constructorParameterType.equals(parameterType)) {
                        allTypesOK = false;
                        break;
                    }
                }
                if(allTypesOK) {
                    instance = currentConstructor.newInstance(parameters);
                }
            }
            if(instance == null) {
                //throw new ReflectionException("Constructeur inexistant");
                StringBuilder sb = new StringBuilder(c.getName());
                sb.append('(');
                boolean first = true;
                for(Object o : parameters) {
                    if(first) {
                        first = false;
                    } else {
                        sb.append(", ");
                    }
                    sb.append(o.getClass().getName());
                }
                sb.append(')');
                throw new ConstructorNotFoundException(sb.toString());
            }
            return instance;
        }
     
     
        /**
         * Cree une nouvelle instance d'une classe dont le nom est
         * passe en parametre
         *
         *
         * @param className Nom complet de la classe dont on veut une instance
         * @param parameters Parametres a passer au constructeur
         * @return Nouvelle instance de la classe dont le nom est
         * passe en parametre
         */
        public static final Object newInstance(String className, Object ...parameters)
        throws InstantiationException,
                IllegalAccessException,
                InvocationTargetException,
                ClassNotFoundException,
                //ReflectionException,
                ConstructorNotFoundException {
            return newInstance(Class.forName(className), parameters);
        }
     
        /**
         * Retourne le wrapper correspondant au primitif passe en parametre
         *
         * @param primitive primitif (exemple : int)
         * @return wrapper correspondant au primitif passe en parametre
         * (exemple : java.lang.Integer pour int)
         */
        public static final Class getWrapper(Class<?> primitive) {
            Class wrapper = wrappers.get(primitive.getName());
            return (wrapper == null) ? primitive : wrapper;
        }
        /**
         * Donne le wrapper correspondant au primitif dont le nom est
         * passe en parametre
         *
         * @param primitive nom du primitif (exemple : "int")
         * @return wrapper correspondant au primitif dont
         * le nom est passe en parametre (exemple : java.lang.Integer pour "int")
         */
        public static final Class getWrapper(String primitive)
        throws ClassNotFoundException {
            return getWrapper(Class.forName(primitive));
        }
     
        /**
         * Donne le nom du wrapper correspondant au primitif passe en parametre
         *
         * @param primitive primitif(exemple : int)
         * @return Nom du wrapper correspondant au primitif passe en parametre
         * (exemple : "java.lang.Integer" pout int)
         */
        public static final String getWrapperName(Class<?> primitive) {
            return getWrapper(primitive).getName();
        }
     
        /**
         * Donne le nom du wrapper correspondant au primitif dont
         * le nom est passe en parametre
         *
         * @param primitive nom du primitif (exemple : "int")
         * @return Nom du wrapper correspondant au primitif dont
         * le nom est passe en parametre (exemple : "java.lang.Integer" pour "int")
         */
        public static final String getWrapperName(String primitive) throws ClassNotFoundException {
            return getWrapper(primitive).getName();
        }
     
        /**
         * Renvoie les noms des attributs d'une classe dont le nom
         * est passé en paramètre
         * @param className nom de la classe
         */
        static public final String[] getFieldsNames(String className)
        throws ClassNotFoundException {
            return getFieldsNames(Class.forName(className));
        }
     
        /**
         * Renvoie les noms des attributs de la classe passée en paramètre
         *
         * @param c classe
         */
        static public final String[] getFieldsNames(Class c) {
            Field[] fields = c.getDeclaredFields();
            int size = fields.length;
            String[] names = new String[size];
            for(int i = 0;i < size;i++) {
                names[i] = fields[i].getName();
            }
            return names;
        }
     
        /**
         * Renvoie les noms des classes des attributs d'une classe dont le nom
         * est passé en paramètre
         * @param className nom de la classe
         */
        static public final String[] getFieldsClassName(String className)
        throws ClassNotFoundException {
            return getFieldsClassName(Class.forName(className));
        }
     
        /**
         * Renvoie les noms des classes des attributs de la classe passée en
         * paramètre
         *
         * @param c classe
         */
        static public final String[] getFieldsClassName(Class c) {
            Field[] fields = c.getDeclaredFields();
            int size = fields.length;
            String[] names = new String[size];
            Class[] classs = new Class[size];
            for(int i = 0;i < size;i++) {
                classs[i] = fields[i].getType();
                names[i] = fields[i].getType().getName();
            }
            return names;
        }
     
        /**
         * Renvoie les classes des attributs d'une classe dont le nom est passé
         * en paramètre
         * @param className nom de la classe
         */
        static public final Class[] getFieldsClass(String className)
        throws ClassNotFoundException {
            return getFieldsClass(Class.forName(className));
        }
        /**
         * Renvoie les classes des attributs de la classe passée en
         * paramètre
         *
         * @param c classe
         */
        static public final Class[] getFieldsClass(Class c) {
            Field[] fields = c.getDeclaredFields();
            int size = fields.length;
            Class[] classs = new Class[size];
            for(int i = 0;i < size;i++) {
                classs[i] = fields[i].getType();
            }
            return classs;
        }
     
        /**
         * Permet de lire la valeur d'un attribut privé
         * @param object objet à lire
         * @param fieldName nom de l'attribut à lire
         * @return valeur de l'attribut
         */
        static public final Object getPrivateField(Object object, String fieldName)
        throws NoSuchFieldException, IllegalAccessException {
            Class objectClass = object.getClass();
            Object value = new Object();
            Field objectField = objectClass.getDeclaredField(fieldName);
            objectField.setAccessible(true);
            value = objectField.get(object);
            return value;
        }
        /**
         * Permet de spécifier une valeur à un attribut privé
         * @param object objet à modifier
         * @param fieldName nom de l'attribut à modifier
         * @param value valeur
         */
        static public final Object setPrivateField(Object object, String fieldName,
                Object value)
                throws NoSuchFieldException, IllegalAccessException {
            Class objectClass = object.getClass();
            Field objectField = objectClass.getDeclaredField(fieldName);
            objectField.setAccessible(true);
            objectField.set(object, value);
            return object;
        }
     
    }
    ReflectionException.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
     
    /**
     *
     * @author Yann D'Isanto
     */
    public class ReflectionException extends Exception {
        static final long serialVersionUID = 1274540209L;
     
        public ReflectionException() {
            this("Undefined error");
        }
     
        public ReflectionException(String message) {
            super(message);
        }
    }
    ConstructorNotFoundException.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
    import java.lang.reflect.Constructor;
     
    /**
     *
     * @author Yann D'Isanto
     */
    public class ConstructorNotFoundException extends Exception {
     
        public ConstructorNotFoundException(String message) {
            super(message);
        }
     
        public ConstructorNotFoundException(Constructor constructor) {
            super("Constructor not found : " + constructor.toGenericString());
        }
     
    }
    merci d'avance pour vos conseils
    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
      1  0

  4. #4
    Membre à l'essai
    Inscrit en
    Avril 2004
    Messages
    18
    Détails du profil
    Informations forums :
    Inscription : Avril 2004
    Messages : 18
    Points : 22
    Points
    22
    Par défaut
    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 &#123;
      /**
       * Nom à afficher.
       */
      private String          name;
     
      /**
       * Constructeur.
       * Initialise les valeurs de la classe.
       * 
       * @param name
       */
      public VerticalLabel&#40;String name&#41; &#123;
        super&#40;&#41;;
        this.name = name;
      &#125;
     
      /*
       *  &#40;non-Javadoc&#41;
       * @see javax.swing.JLabel#setText&#40;java.lang.String&#41;
       */
      public void setText&#40;String text&#41; &#123;
        name = text;
        repaint&#40;&#41;;
      &#125;
     
      /*
       *  &#40;non-Javadoc&#41;
       * @see javax.swing.JComponent#paintComponent&#40;java.awt.Graphics&#41;
       */
      protected void paintComponent&#40;Graphics graphics&#41; &#123;
        Graphics2D graphics2D = &#40;Graphics2D&#41; graphics;
     
        super.paintComponent&#40;graphics&#41;;
     
        graphics2D.setColor&#40;ParameterUI.FONT_BORDER_COLOR&#41;;
        graphics2D.translate&#40;0, getHeight&#40;&#41;&#41;;
        graphics2D.rotate&#40;-Math.PI/2&#41;;
        graphics2D.setFont&#40;ParameterUI.CHART_NAME_FONT&#41;;
        graphics2D.drawString&#40;name, 0 , &#40;getHeight&#40;&#41;-getStringHeight&#40;&#41;&#41;/2&#41;;
      &#125;
     
      /*
       *  &#40;non-Javadoc&#41;
       * @see java.awt.Component#getPreferredSize&#40;&#41;
       */
      public Dimension getPreferredSize&#40;&#41; &#123;
        Dimension dimension = new Dimension&#40;getStringHeight&#40;&#41;, getStringWidth&#40;&#41;&#41;;
        return dimension; 
      &#125;
     
      /*
       *  &#40;non-Javadoc&#41;
       * @see java.awt.Component#getMinimumSize&#40;&#41;
       */
      public Dimension getMinimumSize&#40;&#41; &#123;
        return getPreferredSize&#40;&#41;;
      &#125;
     
      private int getStringWidth&#40;&#41; &#123;
        FontMetrics metrics = getFontMetrics&#40;ParameterUI.CHART_NAME_FONT&#41;;
        int width = metrics.stringWidth&#40;name&#41;;
     
        return width;
      &#125;
     
      private int getStringHeight&#40;&#41; &#123;
        FontMetrics metrics = getFontMetrics&#40;ParameterUI.CHART_NAME_FONT&#41;;
        int height = metrics.getHeight&#40;&#41;;
     
        return height;
      &#125;
    &#125;
      1  0

  5. #5
    Membre confirmé Avatar de calogerogigante
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    602
    Détails du profil
    Informations personnelles :
    Âge : 53
    Localisation : Belgique

    Informations forums :
    Inscription : Avril 2003
    Messages : 602
    Points : 497
    Points
    497
    Par défaut Programme sur JTREE
    Je ne suis pas un crack du java, mais dans ma recherche pour comprendre, et mon envie de tout savoir en profondeur, je suis parfois amené à faire des mini-projets.

    C'est le cas pour le composant swing JTree : je le trouve assez compliqué, et j'avais besoin de faire un petit programme "exemple" pour m'entrainer à l'utiliser, et surtout, en appréhender un minimum le fonctionnement.

    Alors, voici enfin ce programme complet qui met en oeuvre l'arborescence.

    Des objets de type Personne sont stockés dans les branches et les feuilles :

    Tous les mécanismes de base y sont présent :

    - TreeSelectionListener
    - TreeModel
    - DefaultTreeCellRenderer.



    Vous pouvez télécharger les sources zippées à cette page web (c'est mon espace web gratuit chez Multimania qui me permet de stocker ce fichier zip) :

    http://membres.lycos.fr/calogerogiga...test/jtree.htm

    Si mon programme vous a été utile pour comprendre jtree, j'en serais très heureux, et encore plus si vous me le faites savoir !!! ;-)

    P.S.: si vous avez des commentaires et critiques sur ce programme, vous pouvez les mettre dans ce thread, pour en faire profiter tout le monde :

    http://www.developpez.net/forums/viewtopic.php?t=411353
      0  0

  6. #6
    Candidat au Club
    Inscrit en
    Décembre 2005
    Messages
    1
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 1
    Points : 2
    Points
    2
    Par défaut
    Hello,

    une petite classe java pour la gestion d'un fichier de config de type .ini. Vous pouvez générez le javadoc de cette classe pour plus de lisibilité.

    Merci pour vos retours.

    ConfigMgt.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
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
     
    /*
     * Created on Jun 15, 2005
     *
     * $Id&#58; ConfigMgt.java,v 1.1.2.1 2005/12/04 16&#58;36&#58;03 NiCo Exp $
     */
     
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.Hashtable;
     
    /**
     * ConfigMgt est une classe de gestion de configuration dans un fichier. Elle permet de lire
     * et de sauvegarder des informations contenues dans un fichier.<br>
     * Cette classe lit des fichiers texte accessibles en lecture/écriture. Chaque ligne correspond à une nouvelle
     * valeur et une seule, celle-ci pouvant être commentée par le caractère de son choix.<br>
     * Afin de ne pas endommager le fichier de configuration initial, la classe travail sur un fichier temporaire.
     * Lors d'une sauvegarde les données sont placées dans ce fichier temporaire. Pour valider définitivement les
     * modifications, il faut demander explicitement la sauvegarde du fichier temporaire dans le fichier de configuration
     * initial.<br>
     * <br>
     * Exemple &#58;<br>
     * Votre application nécessite de conserver un certain nombre de paramètres d'une session à l'autre, comme
     * la langue, la taille de l'écran et sa position.<br>
     * votre fichier de config pourra ressembler à &#58;<br>
     * <br>
     * config.ini &#58;<br>
     * <br>
     * <i># Config de monApply<br>
     * lang = fr # Langue de l'appli<br>
     * <br>
     * # &#91; Position à l'écran &#93;<br>
     * xPos = 10<br>
     * yPos = 15<br>
     * <br>
     * # &#91; Taille de la fenetre &#93;<br>
     * width = 800<br>
     * height = 600<br></i>
     * <br>
     * Pour charger le fichier il suffit d'exécuter &#58;<br>
     * <br>
     * ConfigMgt config = new ConfigMgt&#40;new File&#40;"config.ini"&#41;,'#'&#41;;<br>
     * <br>
     * maintenant vous accédez aux données de la façon suivante &#58;<br>
     * String language = config.getValeurDe&#40;"lang"&#41;;<br>
     * <br>
     * de la même façon, on peut mettre à jour les données &#58;<br>
     * config.setValeurDe&#40;"lang","en"&#41;;<br>
     * <br>
     * Ces données sont sauvegardées sur fichier par &#58;<br>
     * config.sauveConfigDansFichierTmp&#40;&#41;;<br>
     * <br>
     * Puis pour valider définitivement les données &#40;e.g. lors de la fermeture de l'application&#41; &#58;<br>
     * config.valideSauveDansFichier&#40;&#41;;<br>
     * <br>
     * Bugs et limitations &#58;<br>
     * - a compléter
     * 
     * @author Nicolas Barachet
     * 
     * @since Java 1.3.1
     */
    public class ConfigMgt &#123;
     
    	// ========================================
    	// ========================================
    	//  Membres privés de ConfigMgt.
    	// ========================================
    	// ========================================
     
    	private String           nomFichier;        // Nom du fichier
    	private String           repertoireFichier; // Répertoire du fichier
    	private File             fichier;           // Le fichier
    	private File             fichierTmp;        // Le fichier de travail
    	private RandomAccessFile contenuFichier;    // Son contenu
    	private char             commentaireChar;   // Caractère de commentaire
    	private Hashtable        configuration;     // Variables et leur valeur
     
     
     
     
    	// ========================================
    	// ========================================
    	//  Constructeurs de ConfigMgt.
    	// ========================================
    	// ========================================
     
    	/**
             * Construction d'un nouveau manager de configuration fichier. Si le fichier 
             * passé en parametre est null, cela déclanche une exception. On peut aussi 
             * parametrer la valeur du caractère de commentaire dans le fichier.
             * 
             * @param fic fichier contenant les informations de configurations.
             * @param commentaire Caractère permettant de commenter des lignes.
             * @throws NullPointerException Si le fichier passé en paramètre est null.
             * @throws IOException Si le fichier n'en est pas un, ou s'il n'est lisible,
             * ou s'il n'est pas modifiable.
             */
    	public ConfigMgt&#40;File fic, char commentaire&#41; throws NullPointerException, IOException &#123;		
    		// Initalisation du caractère de commentaire
    		commentaireChar = commentaire;
     
    		// Test de la nullité du fichier.
    		if &#40;fic != null&#41; &#123;
    			// Le fichier n'est pas null.
     
    			// Dernière occurence du caractère '/' ou '\' dans le chemin absolue du fichier.
    			int derIndexSepFichier = fic.getAbsolutePath&#40;&#41;.lastIndexOf&#40;File.separatorChar&#41; + 1;
     
    			// Initialisation du nom et du répertoire du fichier.
    			nomFichier = fic.getAbsolutePath&#40;&#41;.substring&#40;derIndexSepFichier&#41;;
    			repertoireFichier = fic.getAbsolutePath&#40;&#41;.substring&#40;0,derIndexSepFichier&#41;;
     
    			// On test la validité du fichier
    			if &#40;isFichierOk&#40;&#41;&#41; &#123;
    				// Le fichier est OK, on charge les éléments de la config en mémoire.
    				if &#40;!chargementConfig&#40;&#41;&#41; &#123;
    					throw new IOException&#40;"Impossible de charger le fichier en mémoire !!!"&#41;;
    				&#125;
    			&#125; else &#123;
    				// Le fichier ne répond aux critères.
    				throw new IOException&#40;&#41;;
    			&#125;
    		&#125; else &#123;
    			// Le fichier est null, cela produit une exception.
    			throw new NullPointerException&#40;"Le fichier est null !"&#41;;
    		&#125;
    	&#125;
     
    	/**
             * Construction d'un nouveau manager de configuration fichier. Si l'une 
             * des deux chaines de caractères passées en argument est null, cela 
             * provoque une exception.
             * 
             * @param nomFic Chaine de caractères contenant le nom du fichier.
             * @param repFic Chaine de caractères contenant le nom du répertoire
             * où se trouve du fichier.
             * @param commentaire Caractère permettant de commenter des lignes.
             * @throws NullPointerException Si le nom du fichier et/ou le nom 
             * du repertoire passés en paramètre sont null.
             * @throws IOException Si le fichier n'en est pas un, ou s'il n'est lisible,
             * ou s'il n'est pas modifiable.
             */
    	public ConfigMgt&#40;String nomFic, String repFic, char commentaire&#41;
    					throws NullPointerException, IOException &#123;		
    		// Initalisation du caractère de commentaire
    		commentaireChar = commentaire;
     
    		// On teste la nullité du nom du fichier et du répertoire.
    		if &#40;nomFic != null && repFic != null&#41; &#123;
    			// Ni le fichier, ni le répertoire sont null
     
    			if &#40; nomFichier.trim&#40;&#41;.equals&#40;""&#41;&#41; &#123;
    				throw new IOException&#40;&#41;;
    			&#125;
     
    			// Initialisation du nom du fichier
    			nomFichier = nomFic;
     
    			if &#40; &#40;nomFichier + repFic&#41;.trim&#40;&#41;.equals&#40;""&#41;
    			    || &#40;nomFichier + repFic&#41;.trim&#40;&#41;.equals&#40;"\\"&#41;
    			    || &#40;nomFichier + repFic&#41;.trim&#40;&#41;.equals&#40;"/"&#41;&#41; &#123;
    				throw new IOException&#40;&#41;;
    			&#125;
     
    			// On s'assure que le dernier caractère du chemin est bien le
    			// caractère de séparation des répertoires.
    			if &#40;repFic.charAt&#40;repFic.length&#40;&#41; - 1&#41; == File.separatorChar&#41; &#123;
    				// Initialisation du nom du répertoire
    				repertoireFichier = repFic;
    			&#125; else &#123;
    				// Initialisation du nom du répertoire auquel on ajoute
    				// un caractère de séparation
    				repertoireFichier = repFic + File.separatorChar;
    			&#125;
     
    			// On test la validité du fichier
    			if &#40;isFichierOk&#40;&#41;&#41; &#123;
    				// Le fichier est OK, on charge les éléments de la config en mémoire.
    				if &#40;!chargementConfig&#40;&#41;&#41; &#123;
    					throw new IOException&#40;"Impossible de charger le fichier en mémoire !!!"&#41;;
    				&#125;
    			&#125; else &#123;
    				// Le fichier ne répond aux critères.
    				throw new IOException&#40;&#41;;
    			&#125;
    		&#125; else &#123;
    			// Le nom fichier est null ou le nom de repertoire est null,
    			// cela produit une exception.
    			throw new NullPointerException&#40;"Le nom du fichier ou le nom du repertoire est null !!!"&#41;;
    		&#125;
    	&#125;
     
     
    	// ========================================
    	// ========================================
    	//  Méthodes privées de ConfigMgt.
    	// ========================================
    	// ========================================
     
    	/**
             * Méthode de vérification du fichier de configuration. Celui-ci
             * doit existéer, être lisible et accessible en écriture. S'il ne
             * rempli pas ces conditions, cela génère une exception IOException.
             * 
             * @return Vrai si le fichier est conforme aux attentes sinon Faux.
             * @throws IOException Si le fichier n'en est pas un, ou s'il n'est lisible,
             * ou s'il n'est pas modifiable.
             */
    	private boolean isFichierOk&#40;&#41; &#123;
    		boolean rc = false;
     
    		try &#123;
    			// Création du fichier
    			fichier = new File&#40;repertoireFichier + nomFichier&#41;;
     
    			// est-ce bien un fichier?
    			if &#40;!fichier.isFile&#40;&#41;&#41; &#123;
    				rc = false;
    				//System.err.println&#40;"*** Ce n'est pas un fichier valide !!! ***"&#41;;
    			&#125; else if &#40;!fichier.canRead&#40;&#41;&#41; &#123;
    				rc = false;
    				//System.err.println&#40;"*** Le Fichier n'est pas accessible en lecture !!! ***"&#41;;
    			&#125; else if &#40;!fichier.canWrite&#40;&#41;&#41; &#123;
    				rc = false;
    				//System.err.println&#40;"*** Le Fichier n'est pas accessible en écriture !!! ***"&#41;;
    			&#125; else &#123;
    				// création du fichier temporaire sur lequel on va travailler
    				fichierTmp  = File.createTempFile&#40;"$" + nomFichier + "$","tmp",null&#41;;
    				fichierTmp.deleteOnExit&#40;&#41;;
    				copier&#40;fichier,fichierTmp&#41;;
    				rc = true;
    			&#125;
    		&#125; catch &#40;IOException IOex&#41; &#123;
    			rc = false;
    		&#125;
     
    		return rc;
    	&#125;
     
    	/**
             * Méthode de chargement du fichier de config en mémoire.
             * @return Vrai s'il a réussi à le charger, sinon Faux.
             */
    	private boolean chargementConfig&#40;&#41; &#123;
    		boolean rc = false;
    		int posEgal = -1;
    		configuration = new Hashtable&#40;&#41;;
     
    		try &#123;
    			// Création de l'accesseur du fichier
    			contenuFichier = new RandomAccessFile&#40;fichierTmp, "rw"&#41; ;
     
    			// On se replace en haut du fichier
    			contenuFichier.seek&#40;0&#41;;
     
    			// On récupère la première ligne
    			String LigneCourrante = contenuFichier.readLine&#40;&#41;;
     
    			// on sort de la boucle si la ligne courante est null&#40;fin du fichier&#41;
    			while&#40;LigneCourrante != null&#41; &#123;
    				// On s'assure que la ligne n'est pas vide
    				if &#40;LigneCourrante.trim&#40;&#41;.length&#40;&#41; != 0&#41; &#123;
    					// On ne prend que les lignes non commentées
    					if &#40;LigneCourrante.trim&#40;&#41;.charAt&#40;0&#41; != commentaireChar&#41; &#123;
    					    // on supprime les commentaires de fin de lignes
    					    int i = LigneCourrante.indexOf&#40;commentaireChar&#41;;
    					    if &#40; i > -1 &#41; &#123;
    					        LigneCourrante = LigneCourrante.substring&#40;0,i&#41;.trim&#40;&#41;;
    					    &#125;
     
    						// on recherche le caractère '='
    						posEgal = LigneCourrante.indexOf&#40;'='&#41;;
    						if &#40;posEgal > -1&#41; &#123;
    							// Il y a un caractère '='
    						    String variable = new String&#40;LigneCourrante.substring&#40;0,posEgal&#41;.trim&#40;&#41;&#41;;
     
    							if &#40;!variable.equals&#40;""&#41;&#41; &#123;
    							    String valeur = LigneCourrante.substring&#40;posEgal + 1&#41;.trim&#40;&#41;;
     
    								configuration.put&#40;variable,valeur&#41;;
    						    &#125; else &#123;
    							    //System.err.println&#40;"*** Le fichier est mal formater !! ***"&#41;;
    							    throw new IOException&#40;&#41;;
    						    &#125;
    						&#125; else &#123;
    						    //System.err.println&#40;"*** Le fichier est mal formater !! ***"&#41;;
    						    throw new IOException&#40;&#41;;
    						&#125;
    					&#125;
    				&#125;
    				// On passe à la ligne suivante
    				LigneCourrante = contenuFichier.readLine&#40;&#41;;
    			&#125;
     
    			contenuFichier.close&#40;&#41;;
     
    			rc = true;
    		&#125; catch &#40;IOException IOe&#41; &#123;
    			rc = false;
    		&#125; finally &#123;
    		    try &#123;
                    contenuFichier.close&#40;&#41;;
                &#125; catch &#40;IOException e&#41; &#123;
                &#125;
    		&#125;
     
     
    		return rc;
    	&#125;
     
    	/**
             * Méthode de copie d'un fichier dans un autre.
             * @param source Fichier que l'on veut copier.
             * @param destination Fichier dans lequel on copie.
             * @return Vrai Si la copie s'est bien passé sinon faux. 
             */
    	private boolean copier&#40;File source, File destination&#41; &#123;
    		boolean rc = false;
     
    		// Declaration des flux
    		FileInputStream sourceFile=null;
    		FileOutputStream destinationFile=null;
     
    		try &#123;
    		    // Création du fichier &#58;
    			destination.createNewFile&#40;&#41;;
    			// Ouverture des flux
    			sourceFile = new java.io.FileInputStream&#40;source&#41;;
    			destinationFile = new java.io.FileOutputStream&#40;destination&#41;;
    			// Lecture par segment de 1ko 
    			byte buffer&#91;&#93;=new byte&#91;1024&#93;;
    			int nbLecture;
     
    			while&#40; &#40;nbLecture = sourceFile.read&#40;buffer&#41;&#41; != -1 &#41; &#123;
    			    destinationFile.write&#40;buffer, 0, nbLecture&#41;;
    			&#125; 
    				// Copie réussie
    				rc = true;
    			&#125; catch&#40; FileNotFoundException f &#41; &#123;
    			&#125; catch&#40; IOException e &#41; &#123;
    			&#125; finally &#123;
    				// Quoi qu'il arrive, on ferme les flux
    				try &#123;
    				        sourceFile.close&#40;&#41;;
    				&#125; catch&#40;Exception e&#41; &#123;
    				&#125;
    				try &#123;
    				        destinationFile.close&#40;&#41;;
    				&#125; catch&#40;Exception e&#41; &#123;
    				&#125;
    		&#125; 
     
    		return rc;
    	&#125;
     
    	// ========================================
    	// ========================================
    	//  Méthodes publiques de ConfigMgt.
    	// ========================================
    	// ========================================
     
    	/**
             * Fonction retournant la valeur d'un paramètre de la configuration. 
             * <br>e.g. si dans un fichier on a une ligne du type age=34
             * la fonction GetValueOf&#40;"age"&#41; retournera "34".
             * 
             * @param VarName nom de la variable dans le fichier.
             * @return valeur de la variable rentrer en paramètre ou une chaine vide si
             * la variable n'existe pas.
             */
    	public String getValeurDe&#40;String varName&#41; &#123;
    		// Initialisation des variables
    		String rc = "";
    		Object tmp;
     
    		// Vérification du paramètre VarName
    		if &#40;!varName.trim&#40;&#41;.equals&#40;""&#41;&#41; &#123;
    			// Le parametre n'est pas un chaine vide
    			// Lecture de la Hashtable
    			tmp = configuration.get&#40;varName&#41;;
    			// Si la valeur est non null
    			if &#40;tmp != null&#41; &#123;
    				rc = &#40;String&#41; tmp.toString&#40;&#41;;
    			&#125;
    		&#125;
     
    		// On retourne le résultat
    		return rc;
    	&#125;
     
    	/**
             * Méthode de mise à jour d'une variable dans la configuration. Si la valeur passée en argument est null
             * alors on sauve "" et non null &#40;On travaille sur un fichier txt&#41;. Si varName
             * n'existe pas alors rien n'est fait de même si varName est null.
             * 
             * @param varName Chaine de caractères contenant le nom de la variable.
             * @param valeur Chaine de caractères contenant la valeur de la variable.
             * @return Vrai si la configuration a été modifiée sinon Faux.
             */
    	public boolean setValeurDe&#40;String varName,String valeur&#41; &#123;
    	    boolean rc = false;
     
    	    if &#40; varName != null && valeur != null &#41; &#123;
    		    // Les deux paramètres sont non null
    	        if &#40;configuration.containsKey&#40;varName&#41;&#41; &#123;
    	            // La variable existe et on la met à jour
    	            configuration.put&#40;varName,valeur&#41;;
    	            rc = true;
    	        &#125;
    	    &#125; else &#123;
    	        // Au moins l'un des deux est null
    	        if &#40; varName != null &#41; &#123;
    	            // La variable est non null
    		        if &#40;configuration.containsKey&#40;varName&#41;&#41; &#123;
    		            // La variable existe et on la met à jour
    		            configuration.put&#40;varName,""&#41;;
    		            rc = true;
    		        &#125;
    	        &#125;
    	    &#125;
     
    	    return rc;
    	&#125;
     
    	/**
             * Méthode de sauvegarde de la configuration dans le fichier temporaire. Cette méthode
             * permet de sauvegarder un état intermédiaire de la configuration sans écraser le
             * fichier original.
             * 
             * @return Vrai si la sauvegarde a réussi sinon Faux.
             */
    	public boolean sauveConfigDansFichierTmp&#40;&#41; &#123;
    		boolean rc = false;
    		int posEgal = -1;
     
    		String retourLigne = System.getProperty&#40;"line.separator"&#41;;
    		StringBuffer chaineTampon = new StringBuffer&#40;&#41;;
     
    		try &#123;
    			// Création de l'accesseur du fichier
    			contenuFichier = new RandomAccessFile&#40;fichierTmp, "rw"&#41; ;
     
                // On se place au début du fichier
                contenuFichier.seek&#40;0&#41;;
     
                String ligneCourante = contenuFichier.readLine&#40;&#41;;
     
                // On parcourt toutes les lignes du fichiers
                while &#40;ligneCourante != null&#41; &#123;
                    // On regarde si la ligne est non vide
                    if &#40;ligneCourante.length&#40;&#41; > 0&#41; &#123;
    	                // On regarde le premier caractère de la ligne
    	                if &#40;ligneCourante.charAt&#40;0&#41; == commentaireChar&#41; &#123;
    	                    // C'est une ligne de commentaire on la met dans le tampon.
    	                    chaineTampon.append&#40;ligneCourante + retourLigne&#41;;
    	                &#125; else &#123;
    	                    // On sauvegarde les commentaires situés sur cette ligne
    	                    String comment = "";
    	                    int posCom = ligneCourante.indexOf&#40;commentaireChar&#41;;
                            if &#40;posCom > -1&#41; &#123;
                                comment = ligneCourante.substring&#40;posCom&#41;;
                                ligneCourante = ligneCourante.substring&#40;0,posCom&#41;;
                            &#125;
    	                    // Ce n'est pas une ligne de commentaire
    	                    if &#40;ligneCourante.trim&#40;&#41;.length&#40;&#41; > 0&#41;&#123;
    	                        // Ce n'est pas une ligne avec que des espaces
     
    	                        // On teste la présence et la postion du caractère '='
    	                        posEgal = ligneCourante.indexOf&#40;'='&#41;;
     
    	                        if &#40;posEgal > -1&#41; &#123;
    	                            // il y a un caractère '=' dans la ligne
    							    String variable = new String&#40;ligneCourante.substring&#40;0,posEgal&#41;.trim&#40;&#41;&#41;;
     
    								if &#40;!variable.equals&#40;""&#41;&#41; &#123;
    								    // Le nom de la variable est non nul
    								    String valeur = &#40;String&#41; configuration.get&#40;variable&#41;;
     
    								    chaineTampon.append&#40;variable + " = " + valeur + " " + comment + retourLigne&#41;;
    							    &#125; else &#123;
    								    //System.err.println&#40;"*** Le fichier est mal formater !! ***"&#41;;
    								    throw new IOException&#40;&#41;;
    							    &#125;
    	                        &#125; else &#123;
    	                            // la ligne est non vide et ne possède aucun caractère '='
    	                            //System.err.println&#40;"*** Le fichier est mal formaté. ***"&#41;;
    	                            throw new IOException&#40;&#41;;
    	                        &#125;
    	                    &#125; else &#123;
    	                        // La ligne ne possède que des espaces, on met un retour
    	                        // à la ligne dans le tampon
    	                        chaineTampon.append&#40;comment + retourLigne&#41;;
    	                    &#125;
    	                &#125;
                    &#125; else &#123;
                        // La ligne est vide on met un retour à la ligne dans le tampon
                        chaineTampon.append&#40;retourLigne&#41;;
                    &#125;
     
                    ligneCourante = contenuFichier.readLine&#40;&#41;;
                &#125;
     
                // Si on arrive ici c'est l'on a réussi à créer une nouvelle version
                // du fichier dans le tampon.
                contenuFichier.seek&#40;0&#41;;
     
                contenuFichier.setLength&#40;0&#41;;
     
                contenuFichier.writeBytes&#40;chaineTampon.toString&#40;&#41;&#41;;
     
                contenuFichier.close&#40;&#41;;
     
                rc = true;
            &#125; catch &#40;IOException e&#41; &#123;
                rc = false;
            &#125; finally &#123;
                try &#123;
                    contenuFichier.close&#40;&#41;;
                &#125; catch &#40;IOException e1&#41; &#123;
                &#125;
            &#125;
     
    		return rc;
    	&#125;
     
    	/**
             * Cette méthode permet de valider les modifications apportées au fichier. Celle-ci seront
             * disponibles à la prochaine lecture du fichier de configuration. Dans le cas où
             * l'enregistrement des données seraient impossible, la fonction retourne faux.
             * 
             * @return Vrai si la sauvegarde est effective sinon Faux.
             */
    	public boolean valideSauveDansFichier&#40;&#41; &#123;
    	    boolean rc = false;
     
    	    rc = copier&#40;fichierTmp,fichier&#41;;
     
    	    return rc;
    	&#125;
    &#125;
      1  0

  7. #7
    Membre habitué Avatar de Oui-Oui MB
    Homme Profil pro
    Architecte technique
    Inscrit en
    Avril 2005
    Messages
    111
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Belgique

    Informations professionnelles :
    Activité : Architecte technique

    Informations forums :
    Inscription : Avril 2005
    Messages : 111
    Points : 127
    Points
    127
    Par défaut
    Utiliser OpenOffice via une application Java

    Par moi-même

    Voila donc un petit copier / coller d'un de mes précédents posts visant à expliquer comment on utilise OpenOffice et Java en même temps pour faire des chouettes trucs...


    Le SDK d'OpenOffice est très vaste et permet beaucoup de chose et nottament en Java.

    D'ailleurs, il existe un bean (appellé OOoBean) qui permet d'intégrer OpenOffice à une applic AWT Java super facilement. De mémoire, on instancies le bean (facile : OOoBean ob = new OOoBean() et c'est tout) puis on fait un add(ob) pour avoir une fenetre OpenOffice dans son applic...

    Sinon il faut bien lire le Developers Guide et on comprend vite que tout marche avec des services, comme ils appellent ça. En gros, on part d'un service de base (XComponent je crois) et on peut appeller le XDesktop qui permet d'ouvrir, editer, sauver, ... les documents.

    Je met un exemple de mon cru : le petit programme ouvre un document au format Word, lit un fichier de données (fichier Properties) et fait, pour chaque valeur un replace. Ensuite, il enregistre le tout au format Word. C'est un exemple de base qui permet de commencer à bien comprendre le truc. Ah oui : précision : OpenOffice écoute sur le port 8100. On spécifie cela dans le fichier OOoBasePath\share\registry\data\org\openoffice\Setup.xcu. Il faut ajouter les lignes suivantes :

    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    <prop oor:name="ooSetupConnectionURL" oor:type="xs:string">
     <value>socket,host=localhost,port=8100;urp;</value>
    </prop>

    Juste après cette ligne-ci :
    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    <node oor:name="Office">

    Ensuite, il faut lancer OpenOffice...



    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
    import java.io.File;
    import java.util.Properties;
     
    import com.sun.star.beans.XPropertySet;
    import com.sun.star.bridge.XUnoUrlResolver;
    import com.sun.star.comp.helper.Bootstrap;
    import com.sun.star.frame.XDesktop;
    import com.sun.star.lang.XMultiComponentFactory;
    import com.sun.star.uno.UnoRuntime;
    import com.sun.star.uno.XComponentContext;
     
    public class OOoUtils
    {
        private XComponentContext xRemoteContext = null;
        private XMultiComponentFactory xRemoteServiceManager = null;
        private Object desktop = null;
        private XDesktop xDesktop = null;
     
        public XMultiComponentFactory useConnection()
        throws java.lang.Exception 
        {
            try
            {
                xRemoteServiceManager = this.getRemoteServiceManager("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager");
            }
            catch (com.sun.star.connection.NoConnectException e)
            {
                System.err.println("No process listening on the resource");
                e.printStackTrace();
                throw e;
            }
            catch (com.sun.star.lang.DisposedException e)
            { //works from Patch 1
                xRemoteContext = null;
                throw e;
            }
     
            return xRemoteServiceManager;
        }
     
        public XDesktop getXDesktop()
        throws Exception
        {
            Object desktop = xRemoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xRemoteContext);
            xDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, desktop);
     
            return xDesktop;
        }
     
        protected XMultiComponentFactory getRemoteServiceManager(String unoUrl)
        throws java.lang.Exception 
        {
            if (xRemoteContext == null)
            {
                // First step: create local component context, get local servicemanager and
                // ask it to create a UnoUrlResolver object with an XUnoUrlResolver interface
     
                XComponentContext xLocalContext = Bootstrap.createInitialComponentContext(null);
                XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();
                Object urlResolver  = xLocalServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xLocalContext );
     
                // query XUnoUrlResolver interface from urlResolver object
                XUnoUrlResolver xUnoUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, urlResolver);
     
                // Second step: use xUrlResolver interface to import the remote StarOffice.ServiceManager,
                // retrieve its property DefaultContext and get the remote servicemanager
                Object initialObject = xUnoUrlResolver.resolve(unoUrl);
                XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, initialObject);
                Object context = xPropertySet.getPropertyValue("DefaultContext");            
                xRemoteContext = (XComponentContext)UnoRuntime.queryInterface(XComponentContext.class, context);
            }
     
            return xRemoteContext.getServiceManager();
        }
    }
    Et le main qui utilise tout ça :

    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
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.util.Date;
    import java.util.Enumeration;
    import java.util.Properties;
     
    import com.sun.star.beans.PropertyValue;
    import com.sun.star.beans.XPropertySet;
    import com.sun.star.bridge.XInstanceProvider;
    import com.sun.star.bridge.XUnoUrlResolver;
    import com.sun.star.comp.helper.Bootstrap;
    import com.sun.star.frame.XComponentLoader;
    import com.sun.star.frame.XDesktop;
    import com.sun.star.frame.XStorable;
    import com.sun.star.lang.XComponent;
    import com.sun.star.lang.XMultiComponentFactory;
    import com.sun.star.text.XTextDocument;
    import com.sun.star.uno.UnoRuntime;
    import com.sun.star.uno.XComponentContext;
    import com.sun.star.util.XCloseable;
    import com.sun.star.util.XReplaceDescriptor;
    import com.sun.star.util.XReplaceable;
     
    public class TestOOo
    {
        public static void main(String[] args)
        {
            System.out.println("******** DEBUT DU TRAITEMENT ********");
            long start = System.currentTimeMillis();
     
            try
            {
                // get the remote office component context
                long st = System.currentTimeMillis();
     
                OOoUtils OOo = new OOoUtils();
     
                XMultiComponentFactory xMCF = OOo.useConnection();
                XDesktop xDesktop = OOo.getXDesktop();
     
                XComponentLoader xComponentLoader = 
                    (XComponentLoader)UnoRuntime.queryInterface(XComponentLoader.class, xDesktop);
     
                System.out.println("Loading : " 
                        + (System.currentTimeMillis() - st) + " ms");
     
     
                // Ouvrir un doc existant
                PropertyValue[] prop = new PropertyValue[1];
                prop[0] = new PropertyValue();
                prop[0].Name = "Hidden";
                prop[0].Value = Boolean.TRUE;
     
                st = System.currentTimeMillis();
                XComponent xComp = xComponentLoader.loadComponentFromURL("file:///c:/testOOo.doc", "_blank", 0, prop);
                System.out.println("XComponent : " 
                        + (System.currentTimeMillis() - st) + " ms");
     
     
     
                // Charger l'objet XTextDocument
                st = System.currentTimeMillis();
                XTextDocument xTextDoc = (XTextDocument)UnoRuntime.queryInterface(XTextDocument.class, xComp);
                System.out.println("XTextDocument : " 
                        + (System.currentTimeMillis() - st) + " ms");
     
     
     
                st = System.currentTimeMillis();
     
                File data = new File("c:/testOOo.data");
                FileInputStream fis = new FileInputStream(data);
                Properties pdata = new Properties();
                pdata.load(fis);
                fis.close();
     
                XReplaceable xReplace = (XReplaceable)UnoRuntime.queryInterface(XReplaceable.class, xTextDoc);
                XReplaceDescriptor xRD = xReplace.createReplaceDescriptor();
     
                Enumeration enum8 = pdata.keys();
                while (enum8.hasMoreElements())
                {
                    String key = (String)enum8.nextElement();
                    String value = pdata.getProperty(key);
     
                    xRD.setSearchString(key);
                    xRD.setReplaceString(value);
     
                    xReplace.replaceAll(xRD);
                }
     
                System.out.println("Replace : " 
                        + (System.currentTimeMillis() - st) + " ms");
     
     
     
     
                // Enregistrer dans un nouveau fichier
                PropertyValue[] filterProperties = new PropertyValue[1];
                filterProperties[0] = new PropertyValue();
                filterProperties[0].Name = "FilterName";
                filterProperties[0].Value = "MS Word 97";
     
                st = System.currentTimeMillis();
                XStorable xStore = (XStorable)UnoRuntime.queryInterface(XStorable.class, xComp);
                xStore.storeToURL("file:///c:/testout.doc", filterProperties);
                System.out.println("XStorable : " 
                        + (System.currentTimeMillis() - st) + " ms");
     
     
     
     
                // Fermer le document
                st = System.currentTimeMillis();
                XCloseable xClose = (XCloseable)UnoRuntime.queryInterface(XCloseable.class, xComp);
                xClose.close(true);
                System.out.println("XCloseable : " 
                        + (System.currentTimeMillis() - st) + " ms");
     
     
     
                // Fermer l'instance OOo
    //            st = System.currentTimeMillis();
    //            xDesktop.terminate();
    //            System.out.println("xDesktop.terminate() : " 
    //                    + (System.currentTimeMillis() - st) + " ms");
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace();
            }
     
            System.out.println("Temps tot. : " + (System.currentTimeMillis() - start) + " ms");
            System.out.println("******** FIN DU TRAITEMENT ********");
            System.exit(0);
        }
    }
    Que la Schtuche soit avec vous !!!
      0  0

  8. #8
    Expert confirmé
    Avatar de GLDavid
    Homme Profil pro
    Service Delivery Manager
    Inscrit en
    Janvier 2003
    Messages
    2 851
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Service Delivery Manager
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Janvier 2003
    Messages : 2 851
    Points : 4 743
    Points
    4 743
    Par défaut
    Bonjour

    Voici ma modeste contribution suite à ce fil http://www.developpez.net/forums/vie....php?p=2729814.

    Titre : Image dans un JdesktopPane
    Auteur: GLDavid
    Champ d'application : l'idée de ce code est de vous permettre d'agrémenter vos JDesktopPane avec une image qui sera à la même taille que votre composant JDesktopPane.
    Ce code tient sur 2 fichiers: Main.java qui contient la fonction main et la construction de notre fenêtre et JDesktopPane. Puis, CentredBackgroundBorder.java qui se chargera de redimensionner votre image en fonction de la taille de votre JDesktopPane.

    Main.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
    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
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Toolkit;
     
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.UIManager;
     
    import java.awt.event.*;
    import javax.swing.JDesktopPane;
     
    public class Main{
        public static JFrame jFrame = null;
        private JPanel jContentPane = null;
        private JPanel jPanel = null;
        public static JDesktopPane jDesktopPane = null;
     
        /**
         * This method initializes jFrame    
         *     
         * @return javax.swing.JFrame    
         */
        private JFrame getJFrame() {
            if (jFrame == null) {
                jFrame = new JFrame();
                jFrame.setContentPane(getJContentPane());
                java.awt.Dimension screend = Toolkit.getDefaultToolkit().getScreenSize(); 
                jFrame.setSize((int)screend.getWidth(), (int)screend.getHeight());
                jFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
                jFrame.addWindowListener(new WindowListener(){
                    public void windowOpened(WindowEvent e){}
                    public void windowClosing(WindowEvent e){
                        Object[] options = {"Yes", "No", "Cancel"};
                        int n = javax.swing.JOptionPane.showOptionDialog(jFrame,
                                "Are you sure to quit ?",
                                "Quit",
                                javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                                javax.swing.JOptionPane.QUESTION_MESSAGE,
                                null,
                                options,
                                options[0]);
                        if(n!=0){
                            jFrame.setDefaultCloseOperation(jFrame.DO_NOTHING_ON_CLOSE);
                        } 
                        else
                            System.exit(0);
                    }
                    public void windowClosed(WindowEvent e){}
                    public void windowIconified(WindowEvent e){}
                    public void windowDeiconified(WindowEvent e){}
                    public void windowActivated(WindowEvent e){}
                    public void windowDeactivated(WindowEvent e){}
                });
            }
            return jFrame;
        }
     
        /**
         * This method initializes jContentPane    
         *     
         * @return javax.swing.JPanel    
         */
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                jContentPane = new JPanel();
                jContentPane.setLayout(new BorderLayout());
                jContentPane.add(getJPanel(), java.awt.BorderLayout.CENTER);
            }
            return jContentPane;
        }
     
        /**
         * This method initializes jPanel    
         *     
         * @return javax.swing.JPanel    
         */
        private JPanel getJPanel() {
            if (jPanel == null) {
                jPanel = new JPanel(new BorderLayout());
                jPanel.add(getJDesktopPane(), BorderLayout.CENTER);
            }
            return jPanel;
        }
     
        public Main() {
            //Create an object who contains all the text of the differents components in all languages
            JFrame mainFrame = getJFrame();
            mainFrame.setVisible(true);
        }
        private void Exit(ActionEvent evt){
            Object[] options = {"Yes", "No", "Cancel"};
            int n = javax.swing.JOptionPane.showOptionDialog(Main.jFrame,
                    "Are you sure to quit JPCR ?",
                    "Quit 2",
                    javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                    javax.swing.JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    options[0]);
            if(n==0)
                System.exit(0);
        }
     
        /**
         * This method initializes jDesktopPane    
         *     
         * @return javax.swing.JDesktopPane    
         */
        private JDesktopPane getJDesktopPane() {
            if (jDesktopPane == null) {
                 jDesktopPane = new JDesktopPane();
                 try{
                    java.net.URL url = getClass().getResource("debian.png");
                    java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(url);
                    jDesktopPane.setBorder(new CentredBackgroundBorder(image));
                 }
                 catch(java.net.MalformedURLException murle){ murle.printStackTrace(); }
                 catch(java.io.IOException ioe){ ioe.printStackTrace(); }
              }
              return jDesktopPane; 
        }
     
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.metal.MetalLookAndFeel");
            } catch (Exception e) { }
            new Main();
        }
     
    }
    CentredBackgroundBorder.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
     
    import javax.swing.border.Border;
     
    import java.awt.Graphics2D;
    import java.awt.Graphics;
    import java.awt.Component;
    import java.awt.RenderingHints;
    import java.awt.Insets;
    import java.awt.Image;
    import java.awt.geom.AffineTransform;
     
    public class CentredBackgroundBorder implements Border {
     
        private final Image image;
     
        public CentredBackgroundBorder(Image image) {
            this.image = image;
        }
     
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = 0;
            int y0 = 0;
            Graphics2D g2 = (Graphics2D)g;
            AffineTransform t = AffineTransform.getScaleInstance(width / (double) image.getWidth(Main.jDesktopPane), height / (double) image.getHeight(Main.jDesktopPane)); 
            g2.transform(t);
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
            g2.drawImage(image, x0, y0, null);
            try{
                ((Graphics2D)g).transform(t.createInverse());
            }catch(java.awt.geom.NoninvertibleTransformException nte){
                nte.printStackTrace();
            } 
            g = (Graphics)g2;
        }
     
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        }
     
        public boolean isBorderOpaque() {
            return true;
        }
     
    }
    En espérant que cela aide.

    @++
    GLDavid
    Consultez la FAQ Perl ainsi que mes cours de Perl.
    N'oubliez pas les balises code ni le tag

    Je ne répond à aucune question technique par MP.
      1  0

  9. #9
    Membre confirmé
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Octobre 2005
    Messages
    244
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    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
    Hophophop! Modeste contribution avec une petite DialogBox basée sur Swing gerant les messages tout simples, avec une icone perso, inputbox avec textfield et plein d'autre truc

    Bon y'a des choses a revoir (notamment les params d'entrée du constructeur!!), de base c'etait pas pour partager

    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
     
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
     
    /**
     * Boite de dialogue permettant les messageBox et dialogBox
     */
    public class DialogBox extends JDialog implements ActionListener {
     
        // Constantes:
        public static final int BTN_OK = 1;
        public static final int BTN_CANCEL = 2;
        public static final int BTN_IGNORE = 4;
        public static final int BTN_YES = 8;
        public static final int BTN_NO = 16;
        public static final int BTN_RETRY = 32;
     
        // Constante de sortie
        public static final int IS_CANCEL = 0;
        public static final int IS_OK = 1;
        public static final int IS_IGNORE = 2;
        public static final int IS_YES = 3;
        public static final int IS_NO = 4;
        public static final int IS_RETRY = 5;
     
        // Liste des options
        private boolean InputBox = false;
        private boolean password = false;
        private String ibDefault = "";
         private String ibOut = "";
        private TextField inputField = null;
        private String title = "MessageBox";
        private String description = "";
        private Icon icon = new ImageIcon();
     
        private int buttons = 1;
        private int messageOut = 0;
     
        private JPanel jContentPane = null;
        private JPanel jpnlContent = null;
        private JLabel jlblIcon = null;
        private JPanel jpnlButtons = null;
        private JPanel jpnlText = null;
     
        private    ActionListener btnAL = 
            (new ActionListener()
                {
                    public void actionPerformed(ActionEvent act) 
                    {
                        ibOut = inputField.getText();
                    }
                }    
            );
     
        /** Constructeur de la boite de dialogue
         * @param Title Le titre de la fenetre
         * @param Description Le texte à afficher
         * @param Buttons Le ou les boutons a mettre en place
         * @param icon L'icone a mettre en place. Optionnel (null pour aucune icones)
         * @param InputBox Type inputbox ou non (vrai ou faux)
         * @param InputBoxDefault Texte par defaut de l'input box. Peu etre nul si InputBox = false
         * @param InputBoxPassword Si l'entrée est de type mot de passe. Inutile si InputBox = false
         */
        public DialogBox(String Title, String Description, int Buttons, Icon icon,
                boolean InputBox, String InputBoxDefault, boolean InputBoxPassword) {
            super();
            password = InputBoxPassword;
            title = Title;
            description = Description;
            buttons = Buttons;
            this.icon = icon;
            this.InputBox = InputBox;
            ibDefault = InputBoxDefault;
            initialize();
        }
     
        private void initialize() {
     
            this.setContentPane(getJContentPane());
            this.setTitle(title);
     
            Dimension d = getToolkit().getScreenSize();
            this.setLocation(d.width / 3, d.height / 3);
            this.pack();
            this.setModal(true);
            this.setVisible(true);
            this.paintAll(this.getGraphics());
        }
     
        /**
         * This method initializes jContentPane
         * @return javax.swing.JPanel
         */
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                GridLayout gridLayout = new GridLayout();
                gridLayout.setRows(2);
                gridLayout.setColumns(1);
                jContentPane = new JPanel();
                jContentPane.setLayout(gridLayout);
                jContentPane.add(getJpnlContent(), null);
                jContentPane.add(getJpnlButtons(), null);
            }
            return jContentPane;
        }
     
        /**
         * This method initializes jpnlButtons
         * @return javax.swing.JPanel
         */
        private JPanel getJpnlContent() {
            if (jpnlContent == null) {
     
                jpnlContent = new JPanel();
     
                if (icon != null) {
                    jlblIcon = new JLabel();
                    jlblIcon.setIcon(icon);
                    jlblIcon.setPreferredSize(new Dimension(icon.getIconWidth(),
                            icon.getIconHeight()));
                    jpnlContent.add(jlblIcon, null);
                    jpnlContent.add(getJPanel(), null);
                }
     
            }
            return jpnlContent;
        }
     
        /** 
         * Ajout de bouton en fonction de la variable {@link #buttons}
         */
        private void addButtons() {
            if ((buttons & BTN_OK) == BTN_OK) {
                JButton btn = new JButton("Ok");
                if (InputBox)
                    btn.addActionListener(btnAL);
                btn.addActionListener(this);
                jpnlButtons.add(btn);
            }
            if ((buttons & BTN_YES) == BTN_YES) {
                JButton btn = new JButton("Oui");
                if (InputBox)
                    btn.addActionListener(btnAL);
                btn.addActionListener(this);
                jpnlButtons.add(btn);
            }
            if ((buttons & BTN_NO) == BTN_NO) {
                JButton btn = new JButton("Non");
                if (InputBox)
                    btn.addActionListener(btnAL);
                btn.addActionListener(this);
                jpnlButtons.add(btn);
            }
            if ((buttons & BTN_RETRY) == BTN_RETRY) {
                JButton btn = new JButton("Rééssayer");
                if (InputBox)
                    btn.addActionListener(btnAL);
                btn.addActionListener(this);
                jpnlButtons.add(btn);
            }
            if ((buttons & BTN_IGNORE) == BTN_IGNORE) {
                JButton btn = new JButton("Ignorer");
                if (InputBox)
                    btn.addActionListener(btnAL);
                btn.addActionListener(this);
                jpnlButtons.add(btn);
            }
            if ((buttons & BTN_CANCEL) == BTN_CANCEL) {
                JButton btn = new JButton("Annuler");
                if (InputBox)
                    btn.addActionListener(btnAL);
                btn.addActionListener(this);
                jpnlButtons.add(btn);
            }
        }
     
        /**
         * This method initializes jpnlButtons
         * @return javax.swing.JPanel
         */
        private JPanel getJpnlButtons() {
            if (jpnlButtons == null) {
                jpnlButtons = new JPanel();
                addButtons();
            }
            return jpnlButtons;
        }
     
        /**
         * This method initializes jPanel
         * @return javax.swing.JPanel
         */
        private JPanel getJPanel() {
            if (jpnlText == null) {
                GridLayout gridLayout2 = new GridLayout();
                gridLayout2.setColumns(1);
                jpnlText = new JPanel();
                String[] labels_description = description.split("\r\n");
     
                for (int i = 0; i < labels_description.length; i++)
                    jpnlText.add(new JLabel(labels_description[i]));
                if (InputBox) {
                    inputField = new TextField(ibDefault);
                    jpnlText.add(inputField, null);
                    if (password)
                        inputField.setEchoChar('*');
     
                    inputField.addPropertyChangeListener("text",
                            new PropertyChangeListener() {
                                public void propertyChange(PropertyChangeEvent e) {
                                    ibOut = inputField.getText();
                                }
                            });
     
                }
     
                jpnlText.setLayout(gridLayout2);
                gridLayout2.setRows(jpnlText.getComponentCount());
            }
            return jpnlText;
        }
     
        /** Action lors du click d'un bouton */
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof JButton) {
                JButton btn = ((JButton) e.getSource());
     
                if (btn.getText().equals("Ok"))
                    messageOut = IS_OK;
                else if (btn.getText().equals("Annuler"))
                    messageOut = IS_CANCEL;
                else if (btn.getText().equals("Ignorer"))
                    messageOut = IS_IGNORE;
                else if (btn.getText().equals("Non"))
                    messageOut = IS_NO;
                else if (btn.getText().equals("Rééssayer"))
                    messageOut = IS_RETRY;
                else if (btn.getText().equals("Oui"))
                    messageOut = IS_YES;
     
                this.setVisible(false);
            }
        }
     
        public int getButtons() {
            return buttons;
        }
     
        public void setButtons(int buttons) {
            this.buttons = buttons;
        }
     
        public String getDescription() {
            return description;
        }
     
        public void setDescription(String description) {
            this.description = description;
        }
     
        public String getIbDefault() {
            return ibDefault;
        }
     
        public void setIbDefault(String ibDefault) {
            this.ibDefault = ibDefault;
        }
     
        public Icon getIcon() {
            return icon;
        }
     
        public void setIcon(ImageIcon icon) {
            this.icon = icon;
        }
     
        public boolean isInputBox() {
            return InputBox;
        }
     
        public void setInputBox(boolean inputBox) {
            InputBox = inputBox;
        }
     
        public int getMessageOut() {
            return messageOut;
        }
     
        public String getTitle() {
            return title;
        }
     
        public void setTitle(String title) {
            super.setTitle(title);
            this.title = title;
        }
     
        public String getIbOut() {
            return ibOut;
        }
     
    }
    Et voilà un exemple d'appelle:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    DialogBox message = new DialogBox("Attention",FileDialog.getSelectedFile().getAbsolutePath() + " existe déjà. \r\n " +
                            "Etes vous sur de vouloir le remplacer?",DialogBox.BTN_YES | DialogBox.BTN_NO,new ImageIcon(getClass().getResource(Constantes.IMAGEPATH + "help.gif")),false,null,false);
     
                    if (message.getMessageOut() != DialogBox.IS_YES) 
                        return Constantes.ERROR_CANCEL_BY_USER; //Si l'utilisateur annule, alors on quitte la procedure
     
                    message.dispose();
      1  0

  10. #10
    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 : 35
    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 Uploader un fichier depuis une URL
    Voilà ma modeste et première contribution aux sources de developpez.com

    Cette méthode permet de télécharger un fichier depuis une URL et de la mettre ou vous voulez ensuite sur votre pc :

    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
    /**
      * Cette méthode permet d'uploader un fichier depuis une URL
      * @param urlPath chemin du fichier source (site web)
      * @param destination chemin de destination
      */
     private void uploadUrlFile(String urlPath, String destination) { 
      try { 
       //On crée l'URL
              URL url = new URL(urlPath);
     
       //On crée une connection vers cet URL
       URLConnection connection = url.openConnection( );
     
       //On récupère la taille du fichier
       int length = connection.getContentLength();
     
       //Si le fichier est inexestan, on lance une exception
       if(length == -1){
        throw new IOException("Fichier vide");
             }
     
       //On récupère le stream du fichier
       InputStream is = new BufferedInputStream(connection.getInputStream());
     
       //On prépare le tableau de bits pour les données du fichier
       byte[] data = new byte[length];
     
       //On déclare les variables pour se retrouver dans la lecture du fichier
       int currentBit = 0;
       int deplacement = 0;
     
       //Tant que l'on n'est pas à la fin du fichier, on récupère des données
       while(deplacement < length){
        currentBit = is.read(data, deplacement, data.length-deplacement); 
        if(currentBit == -1)break; 
        deplacement += currentBit;
       }
     
       //On ferme le stream
       is.close();
     
       //Si on est pas arrivé à la fin du fichier, on lance une exception
       if(deplacement != length){
        throw new IOException("Le fichier n'a pas été lu en entier (seulement "
     + deplacement + " sur " + length + ")");
       }  
     
       //On crée un stream sortant vers la destination
       FileOutputStream destinationFile = new FileOutputStream(destination); 
     
       //On écrit les données du fichier dans ce stream
       destinationFile.write(data);
     
       //On vide le tampon et on ferme le stream
       destinationFile.flush();
       destinationFile.close();
     
           } catch (MalformedURLException e) { 
             System.err.println("Problème avec l'URL : " + urlPath); 
           } catch (IOException e) { 
             e.printStackTrace();
           }   
     }
      1  0

  11. #11
    Membre confirmé Avatar de calogerogigante
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    602
    Détails du profil
    Informations personnelles :
    Âge : 53
    Localisation : Belgique

    Informations forums :
    Inscription : Avril 2003
    Messages : 602
    Points : 497
    Points
    497
    Par défaut
    Un petit programme idéal pour les débutants !

    Ma collègue des ressources humaines en avait marre de calculer les différences d'heures à la main lorsqu'elle calculait les prestations des employés (pourtant, elle a des logiciels comme exel à sa disposition, allez comprendre !!), mais bon ! Alors, pris de pitié, je lui ai fait ce petit programme qui permet de calculer la différence entre deux heures données :

    xx H yy min et ww H zz min

    avec une gestion du chevauchement d'un jour à l'autre, si nécessaire.

    Cela utilise le gridbaglayout pour le positionnement des composants.

    Si les débutants veulent savoir : aucun logiciel de création visuelle d'interfaces n'a été utilisé : tout à la main, en 2h25min sous Eclipse 3.1 .

    En espérant que cela donnera un peu de matière aux débutants (même si mon programme n'est pas 100% codé dans les règles de l'Art).
      0  0

  12. #12
    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
    Une petite classe qui calcule le PGCD et le PPCM de 2 nombres entiers positifs J'en ai eu besoin pour une fonction de gestion d'intersection de programmations périodique dans un projet que je développe (MyFreeTV, enfin pour la version 3 qui n'est pas sortie), et j'étais persuadé qu'elle était dans java.lang.Math... Mais non...
    Alors voilà, si vous en avez besoin, ça vous évitera de galérer 20mn pour se rappeler comment on calcule ça par Bézout

    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
    /**
     * Cette classe n'est composée que de méthodes statiques, utiles pour certains
     * calculs.
     * 
     * @author rom1v
     */
    public final class MathUtils {
     
        /**
         * Interdiction d'instancier.
         */
        private MathUtils() {}
     
        /**
         * Calcule le Plus Grand Dénominateur Commun entre <code>a</code> et
         * <code>b</code>.
         * <p>
         * <code>a</code> et <code>b</code> doivent être positifs ou nuls.
         * 
         * @param a
         *            Entier <code>a</code>.
         * @param b
         *            Entier <code>b</code>.
         * @return <code>PGCD(a,b)</code>.
         */
        public static int pgcd(int a, int b) {
            assert a >= 0 : "a doit être positif ou nul.";
            assert b >= 0 : "b doit être positif ou nul.";
     
            /* a doit être plus grand ou égal à b */
            if(a < b) {
                int tmp = a;
                a = b;
                b = tmp;
            }
            int r = 1;
            do {
                if(b > 0) {
                    r = a % b;
                    a = b;
                    b = r;
                }
            } while(r > 0);
            return a;
        }
     
        /**
         * Calcule le Plus Petit Commun Multiple entre <code>a</code> et
         * <code>b</code>.
         * <p>
         * <code>a</code> et <code>b</code> doivent être positifs ou nuls.
         * 
         * @param a
         *            Entier <code>a</code>.
         * @param b
         *            Entier <code>b</code>.
         * @return <code>PPCM(a,b)</code>.
         */
        public static int ppcm(int a, int b) {
            assert a >= 0 : "a doit être positif ou nul.";
            assert b >= 0 : "b doit être positif ou nul.";
            return a * b / pgcd(a, b);
        }
     
    }
      1  0

  13. #13
    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
    Bon, et pendant que j'y suis, une classe qui permet de gérer un intervalle, éventuellement infini à gauche et/ou à droite, de comparables (je m'en sers principalement pour des Calendar).
    Par exemple, un interval du style [3 janvier 2003 18:30, 17 mai 2004 14:15[, ou ]null, 14 juin 2006[ (qui représente en fait l'intervalle ouvert ]-infini, 14 juin 2006[).
    Ca marche aussi pour des réels: [12; 95[ ou ]-infini;15[.

    Par contre, une amélioration possible serait de gérer si les bornes sont ouvertes ou fermées, pour le moment c juste fermé à gauche, ouvert à droite (car c t dans ce cas que ça me servait).

    Cette classe est paramétrée par un type T qui étend Comparable.
    Une méthode contains(T) permet de savoir si cet intervalle contient une valeur donnée.
    Une méthode intersect(T) permet de savoir si 2 intervalles se recoupent.
    Une méthode getIntersection(T) permet de récupérer l'intervalle intersection de 2 intervalles.

    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
    package org.myfreetv.core.util;
     
     
    /**
     * Cette classe représente un intervalle. Cet intervalle est
     * inaltérable.
     * 
     * @author rom1v
     */
    public class Interval<T extends Comparable<T>> {
     
        private T start;
        private T end;
     
        /**
         * Crée un intervalle, qui représente <code>[start; end[</code>.
         * <p>
         * Une valeur <code>null</code> signifie l'</code>infini</code>. Par
         * exemple, si <code>end</code> vaut <code>null</code>, l'intervalle
         * n'a pas de fin, <em>ie</em> quelque soit <code>d >= start</code>,
         * <code>d</code> appartient à l'intervalle.
         * <p>
         * Le cas où <code>end < start</code> est possible. Cela représente alors
         * un intervalle vide.
         * <p>
         * <code>start = null</code> et <code>end = null</code> représente
         * l'ensemble complet (<code>]-infini;+infini[</code>).
         * 
         * @param start
         *            Début de l'intervalle, inclus (si non <code>null</code>).
         * @param end
         *            Fin de l'intervalle, exclus.
         */
        public Interval(T start, T end) {
            this.start = start;
            this.end = end;
     
            if(start != null && end != null && end.compareTo(start) < 0) {
                /*
                 * Si la fin est inférieure au début, on lui affecte la valeur du
                 * début.
                 */
                this.end = start;
            }
        }
     
        /**
         * Retourne le début (éventuellement <code>null</code> si
         * <code>-infini</code>).
         * 
         * @return Début.
         */
        public T getStart() {
            return start;
        }
     
        /**
         * Retourne la fin de l'intervalle (éventuellement <code>null</code> si
         * <code>+infini</code>).
         * 
         * @return Fin.
         */
        public T getEnd() {
            return end;
        }
     
        /**
         * Indique si l'intervalle est un intervalle infini.
         * 
         * @return <code>true</code> si l'intervalle est infini.
         */
        public boolean isInfiniteRange() {
            /* L'interval est infini s'il n'a pas de début ou de fin défini. */
            return start == null || end == null;
        }
     
        /**
         * Indique si l'intervalle est vide.
         * 
         * @return <code>true</code> si l'intervalle est vide.
         */
        public boolean isEmptyRange() {
            /*
             * L'intervalle est vide si le départ est postérieur ou simultané à la
             * fin (l'intervalle étant ouvert à droite).
             */
            return !isInfiniteRange() && start.compareTo(end) >= 0;
        }
     
        /**
         * Indique si l'intervalle contient une valeur donnée.
         * 
         * @param value
         *            Valeur à tester.
         * @return <code>true</code> si l'intervalle contient la date.
         */
        public boolean contains(T value) {
            assert value != null : "La valeur à tester ne doit pas être null.";
            boolean result = true;
            if(start != null)
                result = start.compareTo(value) <= 0;
            if(result && end != null)
                result = end.compareTo(value) > 0;
            return result;
        }
     
        /**
         * Indique si <code>this</code> et <code>other</code> ont une
         * intersection non vide.
         * 
         * @param other
         *            Intervalle à comparer.
         * @return <code>true</code> si <code>this</code> et <code>other</code>
         *         ont une intersection non vide.
         */
        public boolean intersect(Interval<T> other) {
            assert other != null : "L'intervalle à comparer ne doit pas être null.";
            boolean intersect;
            if(isEmptyRange())
                intersect = false;
            else if(isInfiniteRange())
                intersect = !other.isEmptyRange();
            else if(other.isInfiniteRange())
                /* this n'est pas un intervalle vide */
                intersect = true;
            else
                /* on est sûr que start/stop de this & other sont non null */
                intersect = start.compareTo(other.end) < 0 && end.compareTo(other.start) > 0;
     
            return intersect;
        }
     
        /**
         * Retourne l'intervalle intersection entre <code>this</code> et
         * <code>other</code>.
         * 
         * @param other
         *            Intervalle à comparer.
         * @return Intervalle intersection entre <code>this</code> et
         *         <code>other</code>.
         */
        public Interval<T> getIntersection(Interval<T> other) {
            assert other != null : "L'intervalle à comparer ne doit pas être null.";
     
            /* initialisation de startT au max entre start et other.start. */
            T startT = start;
            if(other.start != null && start != null && other.start.compareTo(start) > 0)
                startT = other.start;
     
            /* initialisation de endT au min entre end et other.end. */
            T endT = end;
            if(other.end != null && end != null && other.end.compareTo(end) < 0)
                endT = other.end;
     
            return new Interval<T>(startT, endT);
        }
     
        /**
         * Teste l'égalité logique de l'intervalle <code>this</code> avec un autre objet.
         * <p>
         * Le résultat est <code>true</code> ssi <code>other</code>
         * représente un intervalle avec les mêmes bornes que <code>this</code>.
         * 
         * @return <code>true</code> si égalité logique.
         */
        public boolean equals(Object other) {
            boolean eq;
            if(other != null && other instanceof Interval) {
                Interval o = (Interval) other;
                if(start == null)
                    eq = o.start == null;
                else
                    eq = o.start != null && start.equals(o.start);
                if(end == null)
                    eq &= o.end == null;
                else
                    eq &= o.end != null && end.equals(o.end);
            } else
                eq = false;
            return eq;
        }
     
        /**
         * Retourne l'intervalle sous la forme <code>[début, fin[</code>.
         * 
         * @return Intervalle sous forme de chaîne de caractères.
         */
        public String toString() {
            String startString, endString;
     
            if(start == null)
                startString = "-infini";
            else
                startString = start.toString();
     
            if(end == null)
                endString = "+infini";
            else
                endString = end.toString();
     
            return (start == null ? "]" : "[") + startString + ", " + endString + "[";
        }
     
    }
      0  0

  14. #14
    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 ma première contribution à cette page de sources libres.
    Voici une classe qui permet de lire un fichier en format wav, en fournissant le nom du fichier. La classe n'est pas compliquée, mais toutes les semaines y a qqn qui poste un message sur le forum en voulant lire du son sur un programme java no applet (sinon c'est facile lol).
    En espérant que ça va servir, 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
     
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.DataLine.Info;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.AudioSystem;
    import java.io.File;
     
    public class Sound
    {        
        /**
         * Read an audio file in wav format.
         * @param fileName the path of the file you want to read.
         */
        public static void readWavFile(final String fileName)
        {
            class SoundRunnable implements Runnable
            {
                public void run()
                {
                    try
                        {
                            AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileName));
                            AudioFormat format = ais.getFormat();
                            Info info = new Info(SourceDataLine.class, format);
                            SourceDataLine source = (SourceDataLine)AudioSystem.getLine(info);
                            source.open(format);
                            source.start();
                            int read = 0;
                            byte[] audioData = new byte[16384];
                            while(read > -1)
                                {
                                    read = ais.read(audioData, 0 , audioData.length);
                                    if(read >= 0)
                                        source.write(audioData, 0, read);
                                }
                            source.drain();
                            source.close();
                        }
                    catch(Exception e)
                        {
                            e.printStackTrace();
                        }
                }
     
            }
     
            Runnable r = new SoundRunnable();
            Thread t = new Thread(r);
            t.start();
     
     
        }
     
    }
    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

  15. #15
    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 pour compresser et décompresser une archive zip.

    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
    /*
     * ZipTools.java
     *
     * Created on 12 octobre 2005, 08:56
     */
     
     
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.zip.Adler32;
    import java.util.zip.CRC32;
    import java.util.zip.CheckedInputStream;
    import java.util.zip.CheckedOutputStream;
    import java.util.zip.Checksum;
    import java.util.zip.Deflater;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
    import java.util.zip.ZipOutputStream;
     
    /**
     *
     * @author Yann D'ISANTO
     *
     * Cette classe fournit diverses méthodes pour manipuler les archives zip..
     *
     */
    final public class ZipTools {
     
        private ZipTools() {};
     
        static public final int BUFFER_SIZE = 2048;
        static public final Checksum CHECK_NONE = null;
        static public final Checksum CHECK_ADLER32 = new Adler32();
        static public final Checksum CHECK_CRC32 = new CRC32();
     
     
        /**
         * Décompresse l'archive zip spécifiée dans le répertoire contenant la dite 
         * archive. Les fichiers existants sont écrasés.
         * @param file L'archive zip à  décompresser.
         */
        static public final void unzip(File file)
        throws IOException {
            String path = file.getAbsolutePath();
            unzip(file, path.substring(0, path.lastIndexOf(File.separatorChar)));
        }
        /**
         * Décompresse l'archive zip spécifiée dans le répertoire contenant la dite 
         * archive en utilisant le checksum spécifié. Les fichiers existants sont écrasés.
         * @param file L'archive zip à  décompresser.
         * @param checksum Le checksum à  utiliser lors de la décompression.
         */
        static public final void unzip(File file, Checksum checksum)
        throws IOException {
            String path = file.getAbsolutePath();
            unzip(file, path.substring(0, path.lastIndexOf(File.separatorChar)), 
                    checksum);
        }
        /**
         * Décompresse l'archive zip spécifiée dans le répertoire spécifié.
         * Les fichiers existants sont écrasés.
         * @param file L'archive zip à  décompresser.
         * @param destinationPath Le répertoire dans lequel l'archive zip doit être décompressée.
         */
        static public final void unzip(File file, String destinationPath)
        throws IOException {
            unzip(file, destinationPath, true, CHECK_NONE);
        }
        /**
         * Décompresse l'archive zip spécifiée dans le répertoire spécifiéen 
         * utilisant le checksum spécifié. Les fichiers existants sont écrasés.
         * @param file L'archive zip à  décompresser.
         * @param destinationPath Le répertoire dans lequel l'archive zip doit être décompressée.
         * @param checksum Le checksum à  utiliser lors de la décompression.
         */
        static public final void unzip(File file, String destinationPath, 
                Checksum checksum)
        throws IOException {
            unzip(file, destinationPath, true, checksum);
        }
        /**
         * Décompresse l'archive zip spécifiée dans le répertoire spécifié en 
         * utilisant le checksum spécifié. Permet de spécifier s'il faut ou non 
         * écraser les fichiers existants.
         * @param file L'archive zip à  décompresser.
         * @param destinationPath Le répertoire dans lequel l'archive zip doit être décompressée.
         * @param force Spécifie s'il faut écraser les fichiers existants.
         * @param checksum Le checksum à utiliser lors de la décompression.
         */
        static public final void unzip(File file, String destinationPath,
                boolean force, Checksum checksum) throws IOException {
            ZipFile zipfile = new ZipFile(file);
            byte [] buf = new byte[BUFFER_SIZE];
            FileInputStream fis = new FileInputStream(zipfile.getName());
            CheckedInputStream cis = (checksum == null) ? null :
                new CheckedInputStream(fis, checksum);
            BufferedInputStream bis = new BufferedInputStream((cis != null) ?
                cis : fis);
            ZipInputStream zis = new ZipInputStream(bis);
            ZipEntry entry = null;
            try {
                while((entry = zis.getNextEntry()) != null) {
                    File f = new File(destinationPath + File.separatorChar + 
                            entry.getName());
                    if(entry.isDirectory()) {
                        if(!f.exists()) {
                            f.mkdirs();
                        }
                        continue;
                    }
                    if(f.exists()) {
                        if(force) {
                            f.delete();
                        } else {
                            continue;
                        }
                    }
                    f.createNewFile();
                    FileOutputStream fos = new FileOutputStream(f);
                    BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
                    int nbRead;
                    try {
                        while ((nbRead = zis.read(buf)) > 0) {
                            bos.write(buf, 0, nbRead);
                        }
                    } finally {
                        bos.flush();
                        bos.close();
                        fos.close();
                    }
                }
            } finally {
                zis.close();
                bis.close();
                if(cis != null) {
                    cis.close();
                }
                fis.close();
            }
        }
     
     
        /**
         * Compresse les fichiers spécifiés dans l'archive zip spécifiée.
         * @param zipFile L'archive zip dans laquelle seront compressés les 
         * fichiers. Ce fichier doit déjà  avoir été créé.
         * @param files fichiers à  compresser.
         */
        static public final void zip(File zipFile, File ...files)
        throws IOException {
            zip(zipFile, Deflater.BEST_COMPRESSION, files);
        }
        /**
         * Compresse les fichiers spécifiés dans l'archive zip spécifiée en 
         * utilisant le taux de compression spécifié.
         * @param zipFile L'archive zip dans laquelle seront compressés les 
         * fichiers. Ce fichier doit déjà  avoir été créé.
         * @param level niveau de compression.
         * @param files fichiers à  compresser.
         */
        static public final void zip(File zipFile, int level, File ...files)
        throws IOException {
            zip(zipFile, level, CHECK_NONE, files);
        }
        /**
         * Compresse les fichiers spécifiés dans l'archive zip spécifiée en 
         * utilisant le checksum spécifié.
         * @param zipFile L'archive zip dans laquelle seront compressés les 
         * fichiers. Ce fichier doit déjà  avoir été créé.
         * @param checksum Le checksum à utiliser lors de la compression.
         * @param files fichiers à compresser.
         */
        static public final void zip(File zipFile, Checksum checksum, File ...files)
        throws IOException {
            zip(zipFile, Deflater.BEST_COMPRESSION, checksum, files);
        }
        /**
         * Compresse les fichiers spécifiés dans l'archive zip spécifiée en 
         * utilisant le taux de compression et le checksum spécifié.
         * @param zipFile L'archive zip dans laquelle seront compressés les 
         * fichiers. Ce fichier doit déjà  avoir été créé.
         * @param level niveau de compression.
         * @param checksum Le checksum à utiliser lors de la compression.
         * @param files fichiers à compresser.
         */
        static public final void zip(File zipFile, int level,
                Checksum checksum, File ...files)
                throws FileNotFoundException, IOException {
            FileOutputStream fos = new FileOutputStream(zipFile);
            CheckedOutputStream cos = (checksum == null) ? null :
                new CheckedOutputStream(fos, checksum);
            BufferedOutputStream bos = new BufferedOutputStream((cos != null) ?
                cos : fos);
            ZipOutputStream zos = new ZipOutputStream(bos);
            zos.setMethod(zos.DEFLATED);
            zos.setLevel(level);
            try {
                for(File f : files) {
                    String path = f.getCanonicalPath();
                    path = path.substring(0, path.lastIndexOf(File.separator));
                    HashMap<ZipEntry, File> entries = createEntries(path, f);
                    byte[] buf = new byte[BUFFER_SIZE];
                    for(Map.Entry<ZipEntry, File> e : entries.entrySet()) {
                        if(e.getValue().length() == 0) {
                            ZipEntry zipEntry = e.getKey();
                            zipEntry.setSize(0);
                            zipEntry.setCrc(0);
                            zipEntry.setMethod(zipEntry.STORED);
                            zos.closeEntry();
                            zos.putNextEntry(e.getKey());
                            continue;
                        }
                        zos.putNextEntry(e.getKey());
                        FileInputStream fis = new FileInputStream(e.getValue());
                        BufferedInputStream bis = new BufferedInputStream(fis, BUFFER_SIZE);
                        int nbRead;
                        try {
                            while((nbRead = bis.read(buf)) > 0) {
                                zos.write(buf, 0, nbRead);
                            }
                        } finally {
                            zos.closeEntry();
                            bis.close();
                            fis.close();
                        }
                    }
                }
                zos.finish();
            } finally {
                zos.close();
                bos.close();
                if(cos != null) {
                    cos.close();
                }
                fos.close();
            }
        }
     
     
        static private final HashMap<ZipEntry, File> createEntries(String path,
                File ...files)
                throws IOException {
            path += path.endsWith(File.separator) ? "" : File.separator;
            HashMap<ZipEntry, File> map = new HashMap<ZipEntry, File>();
            for(File f : files) {
                if(f.isDirectory()) {
                    HashMap<ZipEntry, File> temp = createEntries(path,
                            f.listFiles());
                    String entrypath = f.getAbsolutePath().replace(path, "").
                            replace(File.separatorChar, '/');
                    entrypath += entrypath.endsWith("/") ? "" : "/";
                    map.put(new ZipEntry(entrypath), f);
                    for(Map.Entry<ZipEntry, File> e : temp.entrySet()) {
                        map.put(e.getKey(), e.getValue());
                    }
                } else {
                    map.put(new ZipEntry(f.getAbsolutePath().replace(path, "").
                            replace(File.separatorChar, '/')), f);
                }
            }
            return map;
        }
    }
    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

  16. #16
    Expert éminent sénior
    Avatar de adiGuba
    Homme Profil pro
    Développeur Java/Web
    Inscrit en
    Avril 2002
    Messages
    13 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java/Web
    Secteur : Transports

    Informations forums :
    Inscription : Avril 2002
    Messages : 13 938
    Points : 23 190
    Points
    23 190
    Billets dans le blog
    1
    Par défaut
    Voici une implémentation de FilenameFilter qui utilise des méta-caractères similaires à ceux des shells, c'est à dire que :
    • * représente n'importe quel chaine de caractères.
    • ? représente n'importe quel caractère.
    Cette classe utilise les expressions régulière en interne, mais les caractères spéciaux des regexp ne sont pas pris en compte, et les caractères * et ? sont pris en comtpe de la même manière que les shell ( * --> .* et ? --> .)

    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
    /**
     * FilenameFilter qui utilise des meta-caractères similaires a ceux des shells basiques :
     * <ul>
     *         <li> '*' représente n'importe quel chaine de caractère ('.*' en regexp).</ul>
     *         <li> '?' représente n'importe quel caractère ('.' en regexp).</ul>
     * </ul>
     * Les autres caractères ne sont pas interprétés...
     */
    class MetaFilenameFilter implements FilenameFilter {
     
    	/** La pattern regexp correspondant aux meta-caractères */
    	private final Pattern pattern;
     
    	/**
             * Constructeur.
             * 
             * @param fileMask La chaine représentant le masque de nom de fichier.
             */
    	public MetaFilenameFilter(String fileMask) {
    		// Ajout de \Q \E autour des sous-chaines de fileMask
    		// qui ne sont pas des meta-caractères :
    		String regexpPattern = fileMask.replaceAll("[^\\*\\?]+", "\\\\Q$0\\\\E");
    		// On remplace toutes les occurrences de '*' afin de les interpréter :
    		regexpPattern = regexpPattern.replaceAll("\\*", ".*");
    		// On remplace toutes les occurrences de '?' afin de les interpréter :
    		regexpPattern = regexpPattern.replaceAll("\\?", ".");
     
    		// On crée le pattern :
    		this.pattern = Pattern.compile(regexpPattern);
    	}
     
    	public boolean accept(File dir, String name) {
    		return this.pattern.matcher(name).matches();
    	}
    }
    Exemples d'utilisations :
    • Lister tous les fichiers *.txt du répertoire courant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
            File directory = new File(".");
            for (File f : directory.listFiles(new MetaFilenameFilter("*.txt"))) {
                System.out.println(f);
            }
    • Lister tous les fichiers du répertoire courant dont l'extension ne contient que deux caractères :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
            File directory = new File(".");
            for (File f : directory.listFiles(new MetaFilenameFilter("*.??"))) {
                System.out.println(f);
            }
    Nota : Ce code nécessite la méthode Pattern.quote() de Java 5.0. Si vous ne l'utiliser pas encore, voir la FAQ : Comment empêcher les expressions régulières d'interpréter une sous-chaînes ?


    [EDIT] [MAJ 21/08/2007]

    Le constructeur de la classe a été mis à jour avec la proposition de le y@m's sur ce post : http://developpez.net/forums/showpos...9&postcount=10

    Pour rappel l'ancien constructeur était le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        public MetaFilenameFilter(String fileMask) {
            // Ajoute de \Q \E autour de la chaine :
            String regexpPattern = Pattern.quote(fileMask);
            // On remplace toutes les occurences de '*' afin de les interpréter :
            regexpPattern = regexpPattern.replaceAll("\\*", "\\\\E.*\\\\Q");
            // On remplace toutes les occurences de '?' afin de les interpréter :
            regexpPattern = regexpPattern.replaceAll("\\?", "\\\\E.\\\\Q");
            // On supprime tous les \Q\E inutiles : 
            regexpPattern = regexpPattern.replaceAll("\\\\Q\\\\E", "");
     
            // On crée le pattern :
            this.pattern = Pattern.compile(regexpPattern);
        }
    Il est tout à fait correct mais un bug introduit dans Java 6.0 provoque une PatternSyntaxException lorsqu'on exécute cette ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    regexpPattern.replaceAll("\\\\Q\\\\E", "");
    Ce bug semble être corrigé dans les builds de Java 7 (Plus d'info : bug_id=6497148), mais la solution de le y@m's est préférable puisque parfaitement portable


    a++
      0  0

  17. #17
    Rédacteur
    Avatar de Arnaud F.
    Homme Profil pro
    Développeur COBOL
    Inscrit en
    Août 2005
    Messages
    5 183
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France

    Informations professionnelles :
    Activité : Développeur COBOL
    Secteur : Finance

    Informations forums :
    Inscription : Août 2005
    Messages : 5 183
    Points : 8 873
    Points
    8 873
    Par défaut
    Ma première contribution à ce fil ...

    Voici une classe qui permet de découper une Image en un tableau d'icones :

    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
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.util.Random;
     
    /* utilise:
     *  Toolkit.getImage()
     *  Image. getScaledInstance()
     *  ImageProducer
     *  CropImageFilter
     *  FilteredImageSource(ImageProducer, CropImageFilter)
     *  Toolkit.createImage(FilteredImageSource)
     */
     
    class DecoupeurImage
    {    
        public static ImageIcon lireImage(String chemin, int width, int height)
        {
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image src1 = tk.getImage(chemin);
        Image src2 = src1.getScaledInstance(width, height, Image.SCALE_DEFAULT);
            return new ImageIcon(src2);
        }//lire
     
        public static ImageIcon decouper(ImageIcon src, int x, int y, int largeur, int hauteur)
        {
        ImageProducer ip = src.getImage().getSource();
        CropImageFilter cif = new CropImageFilter(x, y, largeur , hauteur);
        FilteredImageSource fis = new FilteredImageSource(ip, cif);
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image img = tk.createImage(fis);
            return new ImageIcon(img);
        }//decouper
     
        public static ImageIcon getIcon(ImageIcon src,
                         int i, int j, int nl, int nc)
        {
        int largeur = src.getIconWidth() / nc;
        int hauteur = src.getIconHeight() / nl;
            return decouper(src, j * largeur, i * hauteur, 
                                            largeur , hauteur);
        }//getIcon
     
        public static ImageIcon[][] diviser(ImageIcon src, int nl, int nc)
        {
        ImageIcon[][] res = new ImageIcon[nl][nc];
     
            for (int i = 0 ; i < nl; ++i)
            {
                for (int j = 0; j < nc; ++j)
                {
                    res[i][j] = getIcon(src, i, j, nl, nc);
                }
            }
            return res;
        }//diviser
     
     
        public static void main(String[] args)
        {
        // création des images
        final int nl = 4;
        final int nc = 5;
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension dim = tk.getScreenSize();
        ImageIcon src = lireImage(args[0], dim.width / 2, dim.height / 2);
        ImageIcon[][] icones = diviser(src, nl, nc);
     
        // création des boutons
        JFrame jf = new JFrame();
            jf.setLayout(new GridLayout(nl, nc));
        JButton[][] jbs = new JButton[nl][nc];
        Insets insets = new Insets(0, 0, 0, 0);
            for (int i = 0 ; i < nl; ++i)
            {
                for (int j = 0; j < nc; ++j)
                {
                    jbs[i][j] = new JButton(icones[i][j]);
                    jbs[i][j].setMargin(insets);
                    jf.add(jbs[i][j]);
                }
            }
     
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jf.setVisible(true);
        } //  main
    } // EssaiSwing
    C'est par l'adresse que vaut le bûcheron, bien plus que par la force. Homère

    Installation de Code::Blocks sous Debian à partir de Nightly Builds
      0  0

  18. #18
    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
    Comme promis sur je sais plus quel forum ou on demandait comment protéger des donnés, comment encryper etc, voici une série de classes :
    la première, le premier encrypteur inventé, comme introduction à ce qui va suivre : c'est le cébèbre chiffrement de césar, qui consicte à déplacer tous les caratères.
    Si vous tenez à protéger, n'utilisez pas cet encrypteur, ça se casse en deux secondes...

    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
     
    package Security;
    import java.io.*;
     
    /**
     * @author Absil Romain
     **/
    public class CaesarEncryptor
    {
        public CaesarEncryptor(int aKey)
        {
    	key = aKey;
        }
     
        /**
         * Encrypts a file named inputFileName and saves the encrypted file in 
         * outputFileName. To decrypt a file, juste call the method with -key.
         * @param inputFileName the file you want to encrypt.
         * @param outputFileName the location you want to save the ecrypted file.
         **/
        public void encryptFile(String inputFileName, String outputFileName) throws IOException
        {       
    	InputStream in = null;
    	OutputStream out = null;
    	try
    	    {
    		in = new FileInputStream(inputFileName);
    		out = new FileOutputStream(outputFileName);
    		encryptStream(in,out);
     
    	    }
    	finally
    	    {
    		if(in != null)
    		    in.close();
    		if(out != null)
                        out.close();
    	    }
        }
     
        public void encryptStream(InputStream in, OutputStream out) throws IOException
        {
    	boolean done = false;
    	while(!done)
    	    {
    		int next = in.read();
    		if(next == -1)
    		    done = true;
    		else
    		    {
    			byte b = (byte)next;
    			byte c = encrypt(b);
    			out.write(c);
    		    }
    	    }
        }
     
        public byte encrypt(byte b)
        {
    	return (byte)(b + key);
        }    
     
        private int key;
    }
    Voilà pour un premier. Les autres vont suivre.
    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

  19. #19
    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 une petite classe qui permet d'btenir une empreinte d'un fichier (supposée unique), avec au choix l'algorithme de hachage SHA-1 ou MD5, ce qui signifie qui si votre fichier a été modifié et que vous en refaites l'empreinte, les deux empreintes seront différentes, ça ne protège pas vos données mais ça vus permet de savoir si on les a modifiées...

    La 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
     
    /*
     * MessageInprint.java
     *
     * Created on 17 juin 2006, 12:36
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
     
    package Security;
     
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
     
    /**
     *
     * @author Absil Romain
     */
    public class MessageInprint
    {
     
        /**
         * Create a object that will makes imprints of messages, with a specified 
         * algorithm.
         * @param algorithm the algorithm you want to use (see constants).
         **/
        public MessageInprint(String algorithm)
        {
            try
            {
                this.algorithm = MessageDigest.getInstance(algorithm);
            } 
            catch (NoSuchAlgorithmException ex)
            {
                ex.printStackTrace();
            }
        }
     
        /** 
         * Gets the inprint of the wanted file inputFileName and write in in the 
         * file outputFileName.
         * @param inputFileName the file you want the inprint.
         * @param outputFileName the file you want to write the inprint in.
         **/
        public void getInprint(String inputFileName, String outputFileName)
            throws IOException
        {
            PrintWriter out = null;
            try
            {
                out = new PrintWriter(outputFileName);
                out.println(computeDigest(loadBytes(inputFileName)));
            }
            finally
            {
                if(out != null)
                    out.close();
            }
        }
     
        private byte[] loadBytes(String inputFileName) throws IOException
        {
            FileInputStream in = null;
            try
            {
               in = new FileInputStream(inputFileName) ;
               ByteArrayOutputStream buffer = new ByteArrayOutputStream();
               int ch;
               while( (ch = in.read()) != -1)
                   buffer.write(ch);
               return buffer.toByteArray();
            }
            finally
            {
                if(in != null)
                    in.close();
            }
        }
     
        private String computeDigest(byte[] b)
        {
            algorithm.reset();
            algorithm.update(b);
            byte[] hash = algorithm.digest();
            String d = "";
            for (int i = 0; i < hash.length; i++)
            {
                int v = hash[i] & 0xFF;
                if(v < 16)
                    d += "0";
                d += Integer.toString(v, 16).toUpperCase() + " ";            
            }
     
            return d;
        }        
     
        private MessageDigest algorithm;
        /**
         * Correspond à l'algorithme de hachage SHA-1.
         **/
        public static final String SHA1 = "SHA-1";
        /**
         * Correspond à l'algorithme de hachage MD5.
         **/
        public static final String MD5 = "MD5";
     
    }

    [EDIT]

    Une version plus récente de cette classe est présente dans une des pages suivantes de ce topic, ici.

    [/EDIT]
    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

  20. #20
    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
    Tout d'abord avant de continuer à poster, une courte explication sur le concept de cryptographie de clé publique. (Références : Core Java 2 , de Cay Horstmann).

    La cryptographie de clé publique est fondée sur la notion de clé publique et clé privée. L'idée est de communiquer sa clé publique à tout le monde. Vous êtes toutefois le seul à détenirla clé privée et il est primordiald e la conserver secrète et de ne la divulguer sous aucun prétexte. Les clés sont mises en correspondance par relation mathématique, mais il est reconnu comme pratiquement impossible de calsuler l'une à partir de l'autre. C'est-à-dire que même si tout le monde connait votre clé publique, personne ne peut calculer votre clé privée, quelque soit les ressources informatiques mises en oeuvre.

    Cela peut sembler difficile à croire, mais personne n'a jamais trouvé d'algorithme capable de le réaliser à partir des agorithmes de cryptage actuellement utilisés. Si les clés sont suffisement longues, la technique de force brutale - essayer simpelemtnt toutes les combinaisons de clé possibles - necéssiterait plus d'ordinateurs qu'on en peut en construire à partir de tous les atomes du système solaire, en calculant pendant des milliers d'années. Il est bien sûr possible que quelqu'un découvre des algorithmes capables de calculer des clés par un autre moyen plus élaboré. Par exemple, l'algorithme de cryptage RSA (inventé par Rivest, Shamir et Adleman) repose sur la difficulté de calculer de grands nombres. Ces 20 dernières années, les meilleurs mathmaticiens ont essayé de trouver des algorithmes, sans succès jusqu'à présent. Pour cette raison, la plupart des cryptographes pensent que les clés avec un modulo de 2000 bits ou plus sont actuellement totalement protégées contre toute intrusion.

    Il existe deux sortes de paires de clé publiques/privées : pour le cryptage et pour l'authentification. Si qqn vous envoie un message quia été crypté avec votre clé de cryptage publique, vous pouvez le décripter à l'aide de votre clé de décryptage privée, mais personne d'autre ne le peut. Inversément, si vous signez un message à l'aide de votre clé privée, tout le monde peut vérifier peut vérifier la signature à l'aide de votre clé publique. Le contrôle n'est positif que pour les messages que vous avez signé et il échoue si quelqu'un d'autre a utilisé sa clé pour signer le message.

    De nombreux algorithmes de cryptage, comme RSA et DSA (l'algorithme de signature numérique) utilisent cette diée. La structure exacte des clés et ecq ue signifie leur correspondance dépendent de l'algorithme considéré.



    Voilà pour l'introduction, maintenant je propose ici une petite classe qui permet de signer un document (et d'en vérifier l'authenticité, à l'aide de l'algorithme DSA).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
     
    /*
     * MessageSignature.java
     *
     * Created on 17 juin 2006, 13:59
     *
     */
     
    package org.cosmopol.security;
     
    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.security.Signature;
    import java.security.SignatureException;
     
    /**
     * This class provides methods for signing and varify (i.e. authentify) messages
     * and files with the DSA algorithm.
     * @author Absil Romain
     */
    public class DSAMessageSigner
    {        
        private PublicKey publicKey;
        private PrivateKey privateKey;
        private boolean isSignInitialized;
        private boolean isVerifyInitialized;
     
        /**
         * Constructs a new DSA message signer with the specified file containing 
         * one of the keys, in sign or verify mode (depends on the type of stored
         * key, if the key is public, then the signer is in verify mode, otherwise
         * it is in sign mode.
         * @param keyFileName the name of the file containing a DSA 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 DSAMessageSigner(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 = (PublicKey)key;
                isSignInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (PrivateKey)key;
                isVerifyInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new DSA message signer with the specified file containing 
         * one of the keys, in sign or verify mode (depends on the type of stored
         * key, if the key is public, then the signer is in verify mode, otherwise
         * it is in sign mode.
         * @param keyFile the file containing a DSA 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 DSAMessageSigner(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 = (PublicKey)key;
                isSignInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (PrivateKey)key;
                isVerifyInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new DSA message signer in verify mode with the specified
         * public key.
         * @param key the public key (used to authentify files and messages).
         **/
        public DSAMessageSigner(PublicKey key)
        {
            this.publicKey = key;
            this.isSignInitialized = true;
        }
     
        /**
         * Constructs a new DSA message signer in sign mode with the specified
         * private key.
         * @param key the private key (used to sign files and messages).
         **/
        public DSAMessageSigner(PrivateKey key)
        {
            this.privateKey = key;
            this.isVerifyInitialized = true;
        }
     
        /**
         * Constructs a new DSA message signer in sign and verify 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 DSAMessageSigner(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 = (PublicKey)puKey;
                this.isSignInitialized = true;
                this.privateKey = (PrivateKey)prKey;
                this.isVerifyInitialized = true;
            }
            else
                throw new InvalidKeyException("Some of the files don't contains" +
                        " a valid key");
        }
     
        /**
         * Constructs a new DSA message signer in sign and verify 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 DSAMessageSigner(File publicKeyFile, File privateKeyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFile));
            this.publicKey = (PublicKey) keyIn.readObject();
            this.isSignInitialized = true;
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFile));
            this.privateKey = (PrivateKey) keyIn.readObject();
            this.isVerifyInitialized = true;
            keyIn.close();
        }
     
        /**
         * Constructs a new DSA message signer in sign and verify mode with the
         * specified files containing the public and private key.
         * @param publicKey the public key (used to verify files and messages).
         * @param privateKey the private key (used to sign files and messages).
         **/
        public DSAMessageSigner(PublicKey publicKey, PrivateKey privateKey)
        {
            this.publicKey = publicKey;
            this.isSignInitialized = true;
            this.privateKey = privateKey;
            this.isVerifyInitialized = true;
        }
     
         /**
         * Constructs a new DSA message signer in sign and verify mode with the
         * specified pair of keys.
         * @param keyPair the pair of keys used to verify and sign files and
         * messages.
         **/
        public DSAMessageSigner(KeyPair keyPair)
        {
            this(keyPair.getPublic(), keyPair.getPrivate());
        }
     
        /**
         * Returns the public key of the underlying DSA message signer.
         * @return the public key of the underlying DSA message signer.
         **/
        public PublicKey getPublicKey()
        {
            return publicKey;
        }
     
        /**
         * Sets the public key of the underlying DSA message signer.
         * @param key the public key to set.
         **/
        public void setPublicKey(PublicKey key)
        {
            this.publicKey = key;
        }
     
        /**
         * Returns the private key of the underlying DSA message signer.
         * @return the private key of the underlying DSA message signer.
         **/
        public PrivateKey getPrivateKey()
        {
            return privateKey;
        }
     
        /**
         * Returns a new instance of DSAMessageSigner with the specified size for
         * generated keys.
         * @param size the size of the generated keys.
         * @return a new instance of DSAMessageSigner.
         **/
        public static DSAMessageSigner getInstance(int size)
        {
            return new DSAMessageSigner(generateKeys(size));
        }
     
        /**
         * Returns a new instance of DSAMessageSigner with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of DSAMessageSigner.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich you want to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich you want to write
         * the private key.
         * @throws java.io.IOException if an error occurs during writing one of the
         * keys.
         */
        public static DSAMessageSigner getInstance(int size, 
            String publicKeyFileName, String privateKeyFileName) 
                throws IOException
        {
            return new DSAMessageSigner(generateAndSaveKeys(size, 
                    publicKeyFileName, privateKeyFileName));
        }
     
        /**
         * Returns a new instance of DSAMessageSigner with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of DSAMessageSigner.
         * @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 DSAMessageSigner getInstance(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            return new DSAMessageSigner(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("DSA");
            } 
            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
        {
            KeyPair keyPair = generateKeys(size);
     
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFileName));
            out.writeObject(keyPair.getPublic());
            out.close();
     
            out = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFileName));
            out.writeObject(keyPair.getPrivate());
            out.close();
     
            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 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.
         * @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;
        }
     
        /**
         * Returns signed the specified String.
         * @param message the message to sign.
         * @return signed the specified String.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         **/
        public String signMessage(String message) 
            throws InvalidKeyException, SignatureException
        {
            String signature = new String(sign(message.getBytes()));
            return signature.length() + signature + message;
        }
     
        /**
         * Returns the signature of the given bytes array.
         * @return the signature of the given bytes array.
         * @param message the message to sign.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         */
        public byte[] sign(byte[] message) 
            throws InvalidKeyException, SignatureException
        {
            if(!this.isSignInitialized)
                throw new IllegalStateException("The underlying message signer is"+
                        " not initialized in sign mode. You must specify a " +
                        "private key.");
            Signature signalg = null;
            try
            {
                signalg = Signature.getInstance("DSA");
            } 
            catch (NoSuchAlgorithmException ex)//never thrown
            {
                ex.printStackTrace();
            }
            signalg.initSign(privateKey);
     
            signalg.update(message);
            byte[] signature = signalg.sign();
     
            return signature;
        }
     
        /**
         * Signs the file denoted by the given location and writes the signed file
         * to the given location.
         * @param inputFileName the name of the file to sign.
         * @param outputFileName the name of the file in wich you want to write the
         * signed file.
         * @throws java.io.FileNotFoundException if the file denoted by the 
         * specified location doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the input
         * file or writing the signed file.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         **/
        public void signFile(String inputFileName, String outputFileName) 
            throws FileNotFoundException, IOException, InvalidKeyException, 
                SignatureException
        {
            File inFile = new File(inputFileName);
            File outFile = new File(outputFileName);
            signFile(inFile, outFile);
        }
     
        /**
         * Signs the given file and writes the result to the given file.
         * @param inputFile the file to sign.
         * @param outputFile the file in wich you want to write the signed file.
         * @throws java.io.FileNotFoundException if the file denoted by the 
         * specified location doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the input
         * file or writing the signed file.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         */
        public void signFile(File inputFile, File outputFile) 
            throws FileNotFoundException, IOException, InvalidKeyException, 
                SignatureException
        {
            InputStream in = new FileInputStream(inputFile);
            int length = (int)inputFile.length();
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();
     
            byte[] signature = sign(message);
     
            DataOutputStream out = new DataOutputStream(
                    new FileOutputStream(outputFile));
            int signlength = signature.length;
            out.writeInt(signlength);
            out.write(signature, 0, signlength);
            out.write(message, 0, length);
            out.close();    
        }        
     
        /**
         * Authentifies the given message, i.e. returns true if the public key
         * is matched to the given signed message, returns false otherwise.
         * @param message the message to verify.
         * @return true if the public key is matched to the given signed message, 
         * returns false otherwise.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         **/
        public boolean verifyMessage(String message) 
            throws InvalidKeyException, SignatureException
        {
            int length = getLength(message);
            String signature = message.substring(1, length + 1);
            String msg = message.substring(length + 1);
     
            return verify(msg.getBytes(), signature.getBytes());
        }
     
        private int getLength(String message)
        {
            String s = "0";
            for (int i = 0; i < message.length() && Character.isDigit(message.charAt(i)); i++)
                s+=message.charAt(i);
            return Integer.parseInt(s);
        }
     
        /**
         * Authentifies the given message under bytes array format, i.e. returns
         * true if the public key is matched to the given signed message, 
         * returns false otherwise.
         * @param message the message to verify.
         * @param signature the signature of the message under bytes array format.
         * @return true if the public key is matched to the given signed message, 
         * returns false otherwise.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         **/
        public boolean verify(byte[] message, byte[] signature) 
            throws InvalidKeyException, SignatureException
        {
            if(!this.isSignInitialized)
                throw new IllegalStateException("The underlying message signer is"+
                        " not initialized in verify mode. You must specify a " +
                        "public key.");
            Signature verifyalg = null;
            try
            {
                verifyalg = Signature.getInstance("DSA");
            } 
            catch (NoSuchAlgorithmException ex)//never thrown
            {
                ex.printStackTrace();
            }
     
            verifyalg.initVerify(publicKey);
            verifyalg.update(message);
     
            return verifyalg.verify(signature);
        }
     
        /**
         * Authentifies the file denoted by the specified location, i.e. returns 
         * true if the public key is matched to the given signed file, returns
         * false otherwise.
         * @param inputFileName the name of the file to verify.
         * @return true if the public key is matched to the given signed file, 
         * returns false otherwise.
         * @throws java.io.FileNotFoundException if the file denoted by the
         * specified location doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the
         * input file.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         **/
        public boolean verifyFile(String inputFileName) 
            throws FileNotFoundException, IOException, InvalidKeyException, 
                SignatureException 
        {
            return verifyFile(new File(inputFileName));
        }
     
        /**
         * Authentifies the given file , i.e. returns true if the public key is 
         * matched to the given signed file, returns false otherwise.
         * @param inputFile the file to verify.
         * @return true if the public key is matched to the given signed file, 
         * returns false otherwise.
         * @throws java.io.FileNotFoundException if the input file doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the
         * input file.
         * @throws java.security.InvalidKeyException if the key is not valid for 
         * this type of operation.
         * @throws java.security.SignatureException if this signature object is not
         * initialized properly or if this signature algorithm is unable to process
         * the input data provided.
         **/
        public boolean verifyFile(File inputFile)
            throws FileNotFoundException, IOException, InvalidKeyException, 
                SignatureException 
        {
            Signature verifyalg = null;
            try
            {
                verifyalg = Signature.getInstance("DSA");
            } 
            catch (NoSuchAlgorithmException ex)//never thrown
            {
                ex.printStackTrace();
            }
            verifyalg.initVerify(publicKey);
     
            DataInputStream in = new DataInputStream(
                    new FileInputStream(inputFile));
            int signlength = in.readInt();
            byte[] signature = new byte[signlength];
            in.read(signature, 0 , signlength);
     
            int length = (int)inputFile.length() - signlength - 4;
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();
     
            verifyalg.update(message);
            return verifyalg.verify(signature);
        }     
     
    }
    Bon y a moyen de faire plus concis, cette classe a été crée en vue de réutilisabilité et est donc assez longue, comme toutes les autres classes de cryptage que je propose dans ce topic.
    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

Discussions similaires

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

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