Précédent   Forum du club des développeurs et IT Pro > Java > Général Java
Général Java Java SE, Java ME, APIs, Persistance, JDBC, Spring, XML. Avant de poster -> FAQ Java, Sources Java
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Discussion fermée Actualité déjà publiée
 
Outils de la discussion
Publicité
'
Vieux 05/08/2007, 19h59   #61
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Fonctions précalculées : sinus, cosinus

Bonjour,

Voici une classe qui donne les sin et cos, en précalculés, donc plus rapide.
Le propos est surtout de présenter l'algorithme de précalcul des fonctions.
Plus la fonction est lourde, plus le précalcul est rentable.

Code :
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
/* Une classe offrant des services sin(a) et cos(a) précalculés.
 * Comme dans la fonction d'origine, a est en radians.
 *
 * Cette classe est un exemple de passage d'une fonction calculée à une 
 * fonction précalculée. Dans le cas de sin(a) et cos(a), ces fonctions sont 
 * prériodiques et on ne va précalculer qu'une période.
 *
 * Un modulo nous permettra d'accéder à la totalité de l'espace d'entrée, à 
 * toutes les valeurs possible de l'angle a.
 *
 * On précalcule les valeurs pour 0 <= a < 2 * Math.PI
 *
 * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
public class PPSin {
 
  // La table de nos résultats
  private double[] results;
 
  // Initialisation de la table
  // step indique quelle finesse on désire pour différencier deux résultats de la table
  public PPSin(double step) {
    // L'inverse de la finesse du pas multipliée par la taille de l'intervalle d'entrée 
    // nous donne la taille du tableau
    int n = (int)Math.round((2 * Math.PI) / step);
    // Création/allocation du tableau
    results = new double[n];
    // Recalcul de la finesse, inverse de la taille (int) du tableau 
    double step2 = (2 * Math.PI) / (double)n;
    // Angle de travail
    double a = 0;
    for (int i = 0 ; i < n ; i++) {
      // Enregistrement des valeurs
      results[i] = Math.sin(a);
      // Progression dans les entrées
      a += step2;
    }
  }
 
  // Une chance! Pour la fonction cosinus, la table sinus fonctionne à une translation près
  public double cos(double a) {
    return sin(a + Math.PI / 2d);
  }
 
  // Renvoie le sinus de l'angle a, en radians
  public double sin(double a) {
    int rl = results.length;
    int i = (int)Math.round(a * rl / (2 * Math.PI));
    if (i < 0) {
      int n = -i / rl + 1;
      i += n * rl;
    }
    return results[i % rl];
  }
 
  // Tests, exemples d'utilisation
  public static void main(String[] args) {
    final double STEP = 0.000001;
    final int SIZE = (int)Math.round(2 * Math.PI / STEP);
    System.out.print("Initialisation de la table fonction : ");
    PPSin fct = new PPSin(STEP);
    System.out.println("OK.");
    double a = -Math.PI;
    System.out.println("Tests : a == " + a);
    double difMax = 0;
    double difMin = 1;
    double difAvg = 0;
    for (int i = 0 ; i < SIZE ; i++) {
 
      double dif = Math.abs(fct.cos(a) - Math.cos(a));
      if (dif > 0.00001)
        System.out.println("COS : " + a + " : " + dif);
      if (dif < difMin)
        difMin = dif;
      if (dif > difMax)
        difMax = dif;
      difAvg += dif;
 
      dif = Math.abs(fct.sin(a) - Math.sin(a));
      if (dif > 0.00001)
        System.out.println("SIN : " + a + " : " + dif);
      if (dif < difMin)
        difMin = dif;
      if (dif > difMax)
        difMax = dif;
      difAvg += dif;
 
      a += STEP;
    }
    difAvg /= 2 * SIZE;
    System.out.println("Tests OK. a == " + a);
    System.out.println("Erreur minimale : " + difMin);
    System.out.println("Erreur maximale : " + difMax);
    System.out.println("Erreur moyenne  : " + difAvg);
    while (true);
  }
 
}
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 06/08/2007, 02h40   #62
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Générateur de BufferedImage

Salut,

Voici un générateur de BufferedImage adaptées à l'environnement graphique de travail :

Code :
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
 
import java.awt.GraphicsEnvironment;
import java.awt.GraphicsConfiguration;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
 
/* Un générateur de BufferedImage adaptées aux paramètres graphiques 
 * de l'environnement de travail.
 *
 * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
public class BufferCreator {
 
  // Configuration graphique de l'environnement de travail
  public static final GraphicsConfiguration DGC = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
 
  // Crée un buffer opaque
  public static BufferedImage createBuffer(int width, int height) {
    return createBuffer(width, height, Transparency.OPAQUE);
  }
 
  // Crée un buffer opaque avec la transparence désirée
  // Transparency.OPAQUE : images opaques (JPG)
  // Transparency.BITMASK : images avec transparence de masque (GIF)
  // Transparency.TRANSLUCENT : images avec alpha (PNG)
  public static BufferedImage createBuffer(int width, int height, int transparency) {
    return DGC.createCompatibleImage(width, height, transparency);
  }
 
}
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 08/08/2007, 19h27   #63
fmasurelle
Invité de passage
 
Inscription : août 2007
Messages : 2
Détails du profil
Informations forums :
Inscription : août 2007
Messages : 2
Points : 2
Points : 2
Par défaut Algorithme polynome Newton

Code :
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
import java.util.ArrayList;
 
/**
 * @author fmasurelle
 *
 */
public class CalculTRI {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        ArrayList<Double> listCoef = new ArrayList<Double>();
        listCoef.add(new Double(400));
        listCoef.add(new Double(400));
        listCoef.add(new Double(400));
        listCoef.add(new Double(500));        
 
        double equity = 1000;
 
        System.out.println("TRI="+getTRI(listCoef,equity));
    }
    /**
     * Fonction de calcul du Taux de Rendement Interne
     * @param listCoef la liste des coefficients du polynome
     * chaque coefficient est le delta de la trésorerie entre t et t-1
     * @param equity coût initial
     * @return le Taux de Rendement Interne 
     */
    public static double getTRI(ArrayList<Double> listCoef, double equity){
        double resultX = 1;
        double epsilon = 1;
        while (Math.abs(epsilon)>0.01){// précision du résultat: 0.0001
            double numerateur = -equity;
            double denominateur =0;
            // balayage de la liste des coeff pour calcul des sommes
            double factX =1;
            for(int i=0;i<listCoef.size();i++){
                denominateur +=( listCoef.get(i).doubleValue()*factX*(i+1) );
                factX *= resultX;
                numerateur +=( listCoef.get(i).doubleValue()*factX );
            }
            // calcul du nouveau X et epsilon
            epsilon = resultX;
            resultX -=( numerateur/denominateur );
            epsilon -= resultX;
        }
        return (1/resultX)-1;
    }
}
fmasurelle est déconnecté   Envoyer un message privé 00
Vieux 22/08/2007, 21h43   #64
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Un viewer HTML simple

Bonjour,

Voici un code qui permet de faire un viewer HTML très facilement.
Javascript et Flash n'apparaissent pas.

Code :
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
 
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
import java.io.*;
 
/* Un viewer de sites internet très basique, mais fonctionnel
 *
 * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
 
public class SimpleViewer extends JFrame {
 
  // Contenu HTML
  private JEditorPane editorPane = null;
 
  // Construit un Viewer avec l'url et avec titre l'url
  public SimpleViewer(String url) {
    this(url, url);
  }
 
  // Construit un Viewer avec l'url et avec le titre titre
  public SimpleViewer(String url, String title) {
    super(title);
 
    // Par defaut, on quitte le programme quand on ferme la JFrame
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        exit();
      }
    });
 
    // Construit la page d'url url
    try {
      editorPane = new JEditorPane(url);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    editorPane.setEditable(false);
 
    // Sensibilité aux clics sur les liens
    editorPane.addHyperlinkListener(new HyperlinkListener() {
      public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
          // Nouvelle page
          JEditorPane pane = (JEditorPane) e.getSource();
          if (e instanceof HTMLFrameHyperlinkEvent) {
            HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;
            HTMLDocument doc = (HTMLDocument)pane.getDocument();
            doc.processHTMLFrameHyperlinkEvent(evt);
          } 
          else {
            try {
              pane.setPage(e.getURL());
            } catch (Throwable t) {
              t.printStackTrace();
            }
          }
        }
      }
    });
 
    // Affichage de la fenêtre
    getContentPane().add("Center", new JScrollPane(editorPane));
    setSize(1024, 768);
    setVisible(true);
  }
 
  private static void exit() {
    System.exit(0);
  }
 
  public static void main(String[] args) {
    new SimpleViewer("http://www.anadoncamille.com/");
  }
 
}
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 23/08/2007, 09h22   #65
vahid
Membre confirmé
 
Avatar de vahid
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 237
Points : 237
Fonction split en 1.3 (Java ME)
Impossible de travailler sans

Code :
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
 
	public static String[] split(String string, String pattern){
		Vector parts = new Vector();
		if(string == null)
			throw new NullPointerException("String is null");
 
		int matchIndex = 0;
		int curPos = 0;
		while ( (matchIndex = string.indexOf(pattern, curPos)) != - 1 ){
			parts.addElement(string.substring(curPos,matchIndex));
			curPos = matchIndex+pattern.length();
		}
		if ( curPos <=  string.length() ) 
			parts.addElement(string.substring(curPos));
 
		String[] res = new String[parts.size()];
		int cpt = 0;
		Enumeration e = parts.elements();
		while (e.hasMoreElements()) {
			String element = (String) e.nextElement();
			res[cpt] = element;
			cpt++;
		}
 
		return res;
	}
__________________
Non, Vahid n'est pas mon prénom
c' est gratuit , aussi
vahid est déconnecté   Envoyer un message privé 00
Vieux 05/09/2007, 18h04   #66
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Player midi

Auteur : anadoncamille

Voici un player MIDI très simple, pour aborder le fonctionnement du MIDI :

Code :
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
 
import java.io.File;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.MetaEventListener;
 
/* Un player MIDI simple
 *
 * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
public class MidiPlayer implements MetaEventListener {
 
  private Sequencer sequencer;
 
  public MidiPlayer() {
    try {
      sequencer = MidiSystem.getSequencer(); // Séquenceur MIDI par défaut
      sequencer.addMetaEventListener(this); // Lecture des événements MIDI
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  // Joue un fichier au format MIDI (*.mid)
  public void playFile(String fileName) {
    playSequence(getSequence(fileName));
  }
 
  // Indique si le player est actif
  public boolean isPlaying() {
    if (sequencer == null)
      return false;
    return sequencer.isOpen();
  }
 
  // Réception des messages, traitement du message de fin de lecture
  public void meta(javax.sound.midi.MetaMessage metaMessage) {
    if (metaMessage.getType() == 47) // 47 : fin de la piste
      sequencer.close();
  }
 
   // Crée une séquence MIDI à partir du fichier fileName
  public static Sequence getSequence(String fileName) {
    File file = new File(fileName);
    Sequence sequence;
    try {
      sequence = MidiSystem.getSequence(file);
    }
    catch (Exception e) {
      e.printStackTrace();
      sequence = null;
    }
    return sequence;
  }
 
  // Joue une séquence
  public void playSequence(Sequence sequence) {
    if ((sequence == null) || (sequencer == null))
      return;
    try {
      sequencer.setSequence(sequence); // Indique au séquenceur quelle séquence il va jouer
      sequencer.open(); // Ouverture du séquenceur
      sequencer.start(); // Lecture de la séquence
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  public static void main(String[] args) {
    System.out.println("Playing : " + args[0]);
    MidiPlayer mp = new MidiPlayer();
    mp.playFile(args[0]);
    while (mp.isPlaying())
      Thread.yield();
    System.out.println("OK");
  }
 
}
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 05/09/2007, 19h54   #67
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Batukada aléatoire

Salut,

voici un générateur de batukada aléatoire (percussions), un métronome de luxe.

C'est un vieux code, fonctionnel mais non commenté.

Je cherche à refaire le même objet en plus clair, plus aéré et plus performant.
Cf le post suivant : http://www.developpez.net/forums/sho...62#post2471062

Auteur : anadoncamille

Code :
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
 
import java.util.*;
import javax.sound.midi.*;
 
/* Un générateure de batukada aléatoire (percussions) 
 *
 * 2004-2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
public class RandomBatukada implements MetaEventListener {
 
  private static final int NO_RYTHM = 0;
  private static final int SILENCE = 1;
  private static final int NO_RYTHM_2 = 2;
 
  private static final int TRACK_LENGTH = 64;
  private static final int MULTIPLICATOR = 9 * 5 * 7;
 
  private static final int IC = 47;
  private int[][][] instrumentsRythmes = 
        { {{/*"Acoustic bass drum"  */}, {}, {}, {0, 3, 6, 9, 14}},
          {{/*"Bass drum 1"         */}, {}, {}, {0, 4, 8, 12}}, 
          {{/*"Side stick"          */}, {}, {}, {2, 6, 13}}, 
          {{/*"Acoustic snare"      */}, {}, {}, {11}}, 
          {{/*"Hand clap"           */}, {}, {}, {4, 6, 9}}, 
          {{/*"Electric snare"      */}, {}, {}, {4, 12}}, 
          {{/*"Low floor tom"       */}, {}, {}, {0, 2, 13}}, 
          {{/*"Closed hi-hat"       */}, {}, {}, {0, 2, 4}}, 
          {{/*"High floor tom"      */}, {}, {}, {6, 10}}, 
          {{/*"Pedal hi-hat"        */}, {}, {}, {1, 5, 8}}, 
          {{/*"Low tom"             */}, {}, {}, {0, 12}}, 
          {{/*"Open hi-hat"         */}, {}, {}, {10}}, 
          {{/*"Low-mid tom"         */}, {}, {}, {0, 3, 13}}, 
          {{/*"Hi-mid tom"          */}, {}, {}, {1, 4, 12}}, 
          {{/*"Crash cymbal 1"      */}, {}, {}, {}}, 
          {{/*"High tom"            */}, {}, {}, {4, 10, 12, 14}}, 
          {{/*"Ride cymbal 1"       */}, {}, {}, {}}, 
          {{/*"Chinese cymbal"      */}, {}, {}, {}}, 
          {{/*"Ride bell"           */}, {}, {}, {0}}, 
          {{/*"Tambourine"          */}, {}, {}, {0, 2, 4, 6, 8, 9, 11, 12, 13, 14}}, 
          {{/*"Splash cymbal"       */}, {}, {}, {}}, 
          {{/*"Cowbell"             */}, {}, {}, {0}}, 
          {{/*"Crash cymbal 2"      */}, {}, {}, {}}, 
          {{/*"Vibraslap"           */}, {}, {}, {1}}, 
          {{/*"Ride cymbal 2"       */}, {}, {}, {}}, 
          {{/*"Hi bongo"            */}, {}, {}, {2, 4, 12, 14}}, 
          {{/*"Low bongo"           */}, {}, {}, {0, 8}}, 
          {{/*"Mute hi conga"       */}, {}, {}, {1}}, 
          {{/*"Open hi conga"       */}, {}, {}, {3}}, 
          {{/*"Low conga"           */}, {}, {}, {5}}, 
          {{/*"High timbale"        */}, {}, {}, {6}}, 
          {{/*"Low timbale"         */}, {}, {}, {10}}, 
          {{/*"High agogo"          */}, {}, {}, {0, 3, 6, 9, 12}}, 
          {{/*"Low agogo"           */}, {}, {}, {0, 2, 4, 6, 8, 10, 12, 14}}, 
          {{/*"Cabasa"              */}, {}, {}, {1, 5, 9, 13}}, 
          {{/*"Maracas"             */}, {}, {}, {7, 15}}, 
          {{/*"Short whistle"       */}, {}, {}, {10, 13}}, 
          {{/*"Long whistle"        */}, {}, {}, {0}}, 
          {{/*"Short guiro"         */}, {}, {}, {10, 13}}, 
          {{/*"Long guiro"          */}, {}, {}, {0}}, 
          {{/*"Claves"              */}, {}, {}, {0, 2, 6, 10, 12}}, 
          {{/*"Hi wood block"       */}, {}, {}, {0, 2, 12}}, 
          {{/*"Low wood block"      */}, {}, {}, {4, 6, 10}}, 
          {{/*"Mute cuica"          */}, {}, {}, {4}}, 
          {{/*"Open cuica"          */}, {}, {}, {13}}, 
          {{/*"Mute triangle"       */}, {}, {}, {0, 3, 6, 9}}, 
          {{/*"Open triangle"       */}, {}, {}, {12}} };
 
  private String instruments[] = 
        { "Acoustic bass drum", 
          "Bass drum 1", 
          "Side stick", 
          "Acoustic snare",
          "Hand clap", 
          "Electric snare", 
          "Low floor tom", 
          "Closed hi-hat",
          "High floor tom", 
          "Pedal hi-hat", 
          "Low tom", 
          "Open hi-hat", 
          "Low-mid tom", 
          "Hi-mid tom", 
          "Crash cymbal 1", 
          "High tom", 
          "Ride cymbal 1", 
          "Chinese cymbal", 
          "Ride bell", 
          "Tambourine", 
          "Splash cymbal", 
          "Cowbell", 
          "Crash cymbal 2", 
          "Vibraslap", 
          "Ride cymbal 2", 
          "Hi bongo", 
          "Low bongo", 
          "Mute hi conga", 
          "Open hi conga", 
          "Low conga", 
          "High timbale", 
          "Low timbale", 
          "High agogo", 
          "Low agogo", 
          "Cabasa", 
          "Maracas", 
          "Short whistle", 
          "Long whistle", 
          "Short guiro", 
          "Long guiro", 
          "Claves", 
          "Hi wood block", 
          "Low wood block", 
          "Mute cuica", 
          "Open cuica", 
          "Mute triangle", 
          "Open triangle" };
 
  private static final int PROGRAM = 192;
  private static final int NOTEON = 144;
  private static final int NOTEOFF = 128;
  private static final int velocity = 100;
 
  private Vector data;
  private Hashtable dataKeys;
  private Sequencer sequencer;
  private Sequence sequence;
  private Track track;
  private int tempo;
  private boolean ready;
  private boolean initOk;
  private boolean midiExit;
  private long midiExitDate;
  private int[] lastPlayed;
  private Random random;
 
  public static void main(String[] args) {
    RandomBatukada rb = new RandomBatukada();
    rb.setTempo(109);
    while (true)
      rb.live();
  }
 
  public RandomBatukada() {
    random = new Random();
    ready = false;
    midiExit = false;
    initOk = false;
    lastPlayed = new int[6];
    for (int i = 0 ; i < 6 ; i++)
      lastPlayed[i] = random.nextInt(instruments.length);
  }
 
  public void setTempo(int bpm) {
    tempo = bpm;
  }
 
  public void play(String instrument, int time) {
    play(instrument, time, time);
  }
 
  public void play(String instrument, int timeStart, int timeEnd) {
    Data dt = (Data)dataKeys.get(instrument);
    if (dt != null)
      dt.play(timeStart, timeEnd);
  }
 
  public void silence(String instrument, int time) {
    silence(instrument, time, time);
  }
 
  public void silence(String instrument, int timeStart, int timeEnd) {
    Data dt = (Data)dataKeys.get(instrument);
    if (dt != null)
      dt.silence(timeStart, timeEnd);
  }
 
  public void playRythm(String instrument) {
    Data dt = (Data)dataKeys.get(instrument);
    if (dt != null)
      dt.playRythm();
  }
 
  public void playRythm(String instrument, int r) {
    Data dt = (Data)dataKeys.get(instrument);
    if (dt != null)
      dt.playRythm(r);
  }
 
  private void createEvent(int type, int chan, int num, long tick) {
    ShortMessage message = new ShortMessage();
    try {
      message.setMessage(type, chan, num, velocity); 
      MidiEvent event = new MidiEvent( message, tick );
      track.add(event);
    } 
    catch (Exception ex) { 
      ex.printStackTrace(); 
    }
  }
 
  private void createSequence() {
    try {
      sequence = new Sequence(Sequence.PPQ, 4 * MULTIPLICATOR);
    }
    catch (Exception ex) {
      ex.printStackTrace(); 
    }
  }
 
  private void initTrack() {
    createSequence();
    track = sequence.createTrack();
  }
 
  private void refreshTrack() {
    initTrack();
    createEvent(PROGRAM, 9, 1, 0);
    for (int i = 0; i < data.size(); i++) {
      Data d = (Data)data.get(i);
      for (int j = 0; j < d.staff.length; j++)
        if (d.staff[j]) {
          createEvent(NOTEON, 9, d.id, j); 
          createEvent(NOTEOFF, 9, d.id, j + 1); 
        }
    }
    createEvent(PROGRAM, 9, 1, (TRACK_LENGTH * MULTIPLICATOR) - 1);
  }
 
  private void setSequencer() {
    try {
      sequencer.setSequence(sequence);
    } 
    catch (Exception ex) {
      ex.printStackTrace(); 
    }
  }
 
  private void startSequencer() {
    refreshTrack();
    setSequencer();
    sequencer.start();
    sequencer.setTempoInBPM(tempo);
  }
 
  private void initSequencer() {
    sequencer = null; 
    try {
      sequencer = MidiSystem.getSequencer();
      sequencer.open();
      sequencer.addMetaEventListener(this);
      startSequencer();
    }
    catch (Exception e) {
      sequencer = null;
      e.printStackTrace(); 
    }
  }
 
  private void createMidi() {
    data = new Vector();
    dataKeys = new Hashtable();
    Data dt;
    for (int i = 0, id = 35; i < instruments.length; i++, id++) {
      dt = new Data(instruments[i], id);
      data.add(dt);
      dataKeys.put(instruments[i], dt);
    }
    for (int i = 0 ; i < 7 ; i++)
      playRythm(instruments[random.nextInt(instruments.length)]);
    for (int i = 0 ; i < 6 ; i++)
      playRythm(instruments[lastPlayed[i]]);
    setTempo(tempo);
    initSequencer();
    ready = sequencer != null;
  }
 
  public void meta(javax.sound.midi.MetaMessage metaMessage) {
    if (metaMessage.getType() == 47) // 47 is end of track
      startSequencer();
  }
 
  protected void finalize() throws Throwable {
    close();
    super.finalize();
  }
 
  public void close() {
    if (sequencer != null)
      sequencer.close();
  }
 
  public void live() {
    if (ready) {
      setTempo(tempo);
      if (random.nextBoolean()) {
        int n = random.nextInt(3) + 1;
        for (int i = 0 ; i < 1 ; i++)
          silence(instruments[random.nextInt(instruments.length)], 0, TRACK_LENGTH * MULTIPLICATOR - 1);
        for (int i = 0 ; i < 2 ; i++) {
          lastPlayed[i] = lastPlayed[i + 2];
          lastPlayed[i + 2] = lastPlayed[i + 4];
          lastPlayed[i + 4] = random.nextInt(instruments.length);
          playRythm(instruments[lastPlayed[i + 4]]);
        }
      }
      else {
        for (int i = 0 ; i < 6 ; i++)
          playRythm(instruments[lastPlayed[i]], NO_RYTHM_2);
        for (int i = 0 ; i < 3 ; i++) {
          lastPlayed[i] = lastPlayed[i + 3];
          lastPlayed[i + 3] = random.nextInt(instruments.length);
          playRythm(instruments[lastPlayed[i + 3]], NO_RYTHM_2);
        }
      }
    }
    else 
      if (!initOk) {
        createMidi();
        initOk = true;
      }
    if (midiExit) {
      if (System.currentTimeMillis() > midiExitDate)
        System.exit(0);
    }
  }
 
  class Data {
 
    String name; 
    int id; 
    boolean[] staff;
    int[][] rythmes;
 
    public Data(String name, int id) {
      this.name = name;
      this.id = id;
      rythmes = instrumentsRythmes[id - 35];
      staff = new boolean[TRACK_LENGTH * MULTIPLICATOR];
      for (int i = 0; i < staff.length; i++)
        staff[i] = false;
    }
 
    public void playRythm() {
      playRythm(random.nextInt(rythmes.length - 2) + 2);
    }
 
    public void playRythm(final int r) {
      switch(r) {
        case NO_RYTHM : {
          staff[random.nextInt(TRACK_LENGTH) * MULTIPLICATOR] = true;
          staff[random.nextInt(TRACK_LENGTH) * MULTIPLICATOR] = false;
          break;
        }
        case NO_RYTHM_2 : {
          boolean okt = false;
          boolean okf = false;
          for (int i = 0 ; i < TRACK_LENGTH / 2 ; i++) {
            okt |= staff[(i * 2 + 1) * MULTIPLICATOR];
            okt |= staff[i * 2 * MULTIPLICATOR];
            okf |= !staff[i * 2 * MULTIPLICATOR];
          }
          if (!okt) {
            staff[random.nextInt(TRACK_LENGTH) * MULTIPLICATOR] = true;
            break;
          }
          if (!okf) {
            staff[random.nextInt(TRACK_LENGTH) * MULTIPLICATOR] = false;
            break;
          }
          int i0 = random.nextInt(TRACK_LENGTH) * MULTIPLICATOR;
          while (!staff[i0])
            i0 = random.nextInt(TRACK_LENGTH) * MULTIPLICATOR;
          int i1 = random.nextInt(TRACK_LENGTH / 2) * 2 * MULTIPLICATOR;
          while (staff[i1])
            i1 = random.nextInt(TRACK_LENGTH / 2) * 2 * MULTIPLICATOR;
          if (i0 < i1) {
            staff[i0] = false;
            staff[i1] = true;
          }
          break;
        }
        case SILENCE : {
          for (int i = 0 ; i < TRACK_LENGTH * MULTIPLICATOR ; i++)
            staff[i] = false;
          break;
        }
        default : {
          for (int i = 0 ; i < TRACK_LENGTH * MULTIPLICATOR ; i++)
            staff[i] = false;
          for (int j = 0 ; j < TRACK_LENGTH / 16 ; j++)
            for (int i = 0 ; i < rythmes[r].length ; i++)
              staff[(rythmes[r][i % 16] + j * 16) * MULTIPLICATOR] = true;
          break;
        }
      }
    }
 
    public void play(int timeStart, int timeEnd) {
      for (int i = timeStart ; i <= timeEnd ; i++)
        staff[i] = true;
    }
 
    public void silence(int timeStart, int timeEnd) {
      for (int i = timeStart ; i <= timeEnd ; i++)
        staff[i] = false;
    }
 
  }
 
}
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 06/09/2007, 16h24   #68
Razgriz
Membre confirmé
 
Avatar de Razgriz
 
Chercheur en informatique
Inscription : avril 2006
Messages : 383
Détails du profil
Informations professionnelles :
Activité : Chercheur en informatique

Informations forums :
Inscription : avril 2006
Messages : 383
Points : 251
Points : 251
Ayant constaté récemment que certains utilisateurs revenaient avec des bugs issus de vielles classe de cryptage que j'avais codées, j'ai décidé de mettre tous mes posts à jour sur ces classes, afin que ces bugs n'aparraissent plus.

Seulement, à cause de refactoring de modélisation, plus présisément sur la classe de cryptage symétrique et sur celle de cryptage RSA présentes ici, je dois fournir la superclasse indispensable à leur utilisation.

La voici :
Code :
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
 
package org.cosmopol.crypto;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
 
/**
 * This class models cipher algorithm encryptors wich are represented by
 * their stream and bytes encryption method.
 * @author Absil Romain
 */
public class CipherEncryptor
{
    /**
     * Crypts or decrypts the specified input stream to the specified output
     * stream with a given cipher. The crypting or decrypting operation is 
     * determined by the cipher's state.
     * @param cipher The cipher used to crypt the specified input stream to the specified output
     * stream.
     * @param in the input srteal stream to be encypted or decrypted.
     * @param out the output stream to be encypted or decrypted.
     * @throws java.io.IOException if an I/O error occurs during crypting the input stream to the output stream.
     */
    public void crypt(InputStream in, OutputStream out, Cipher cipher)
        throws IOException
    {
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(blockSize);
        byte[] inBytes = new byte[blockSize];
        byte[] outBytes = new byte[outputSize];
 
        int inLength = 0;
        boolean done = false;
        while(!done)
        {
            inLength = in.read(inBytes);
            if(inLength == blockSize)
            {
                try
                {
                    int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
                    out.write(outBytes, 0, outLength);
                }
                catch(ShortBufferException e)
                {
                    e.printStackTrace();
                }
            }
            else
                done = true;
        }
 
        try
        {
            if(inLength > 0)
                outBytes = cipher.doFinal(inBytes, 0, inLength);
            else
                outBytes = cipher.doFinal();
            out.write(outBytes);
        }
        catch(IllegalBlockSizeException e)
        {
            e.printStackTrace();
        }
        catch(BadPaddingException e)
        {
            e.printStackTrace();
        }
    }
 
}
__________________
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.
Razgriz est déconnecté   Envoyer un message privé 00
Vieux 06/09/2007, 17h09   #69
Razgriz
Membre confirmé
 
Avatar de Razgriz
 
Chercheur en informatique
Inscription : avril 2006
Messages : 383
Détails du profil
Informations professionnelles :
Activité : Chercheur en informatique

Informations forums :
Inscription : avril 2006
Messages : 383
Points : 251
Points : 251
Bon allez pour la route, une petite classe qui permet de crypter des byte[] et des String en RSA.

Utilisez les clés générées par la classe RSAEncryptor présente ici

[EDIT]
Je ne conseille pas d'utiliser cette classe qui si on demande l'encryption de grandes quantités de bytes (ex : fichiers) va vite devenir très lente à cause des constructions répétitives de BigInteger et des aopels à modPow. Je recommende l'utilisation de l'encrypteur RSA posté ici
[/EDIT]

Code :
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
 
package org.cosmopol.crypto;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
 
/**
 * This class provides methods for
 * @author Absil Romain, Michel Deriaz.
 */
public class RSAStringEncryptor
{
    private RSAPublicKey publicKey;
    private RSAPrivateKey privateKey;
    private boolean isEncryptInitialized;
    private boolean isDecryptInitialized;
 
    /**
     * Constructs a new RSA encryptor with the specified file containing one
     * of the keys, in encrypt or decrypt mode (depends on the type of stored
     * key, if the key is public, then the encryptor is in encrypt mode,
     * otherwise it is in decrypt mode.
     * @param keyFileName the name of the file containing a RSA key.
     * @throws java.io.FileNotFoundException if the file containing the key doesn't
     * exist.
     * @throws java.io.IOException if an error occurs during reading the file
     * containing the key.
     * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
     * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
     */
    public RSAStringEncryptor(String keyFileName)
    throws FileNotFoundException, IOException, ClassNotFoundException,
            InvalidKeyException
    {
        ObjectInputStream keyIn = new ObjectInputStream(
                new FileInputStream(keyFileName));
        Object key = keyIn.readObject();
        keyIn.close();
 
        if(key instanceof RSAPublicKey)
        {
            publicKey = (RSAPublicKey)key;
            isEncryptInitialized = true;
        }
        else if(key instanceof RSAPrivateKey)
        {
            privateKey = (RSAPrivateKey)key;
            isDecryptInitialized = true;
        }
        else
            throw new InvalidKeyException("The file does not contain a " +
                    "valid key");
    }
 
    /**
     * Constructs a new RSA encryptor with the specified file containing one
     * of the keys, in encrypt or decrypt mode (depends on the type of stored
     * key, if the key is public, then the encryptor is in encrypt mode,
     * otherwise it is in decrypt mode.
     * @param keyFile the file containing a RSA key.
     * @throws java.io.FileNotFoundException if the file containing the key doesn't
     * exist.
     * @throws java.io.IOException if an error occurs during reading the file
     * containing the key.
     * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
     * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
     */
    public RSAStringEncryptor(File keyFile)
    throws FileNotFoundException, IOException, ClassNotFoundException, InvalidKeyException
    {
        ObjectInputStream keyIn = new ObjectInputStream(
                new FileInputStream(keyFile));
        Object key = keyIn.readObject();
        keyIn.close();
 
        if(key instanceof RSAPublicKey)
        {
            publicKey = (RSAPublicKey)key;
            isEncryptInitialized = true;
        }
        else if(key instanceof RSAPrivateKey)
        {
            privateKey = (RSAPrivateKey)key;
            isDecryptInitialized = true;
        }
        else
            throw new InvalidKeyException("The file does not contain a " +
                    "valid key");
    }
 
    /**
     * Constructs a new RSA encryptor in encrypt mode with the specified
     * public key.
     * @param key the public key (used to encrypt files and streams).
     **/
    public RSAStringEncryptor(RSAPublicKey key)
    {
        if(key == null)
            throw new NullPointerException();
        this.publicKey = key;
        this.isEncryptInitialized = true;
    }
 
    /**
     * Constructs a new RSA encryptor in decrypt mode with the specified
     * private key.
     * @param key the private key (used to decrypt files and streams).
     **/
    public RSAStringEncryptor(RSAPrivateKey key)
    {
        if(key == null)
            throw new NullPointerException();
        this.privateKey = key;
        this.isDecryptInitialized = true;
    }
 
    /**
     * Constructs a new RSA encryptor in encrypt and decrypt mode with the
     * specified files containing the public and private key.
     * @param publicKeyFileName the name of the file containing the public key.
     * @param privateKeyFileName the name of the file containing the private key.
     * @throws java.io.FileNotFoundException if one of the files containing a key
     * doen't exist.
     * @throws java.io.IOException if an error occurs during reading one of the keys.
     * @throws java.lang.ClassNotFoundException if one of the class of the keys is
     * unknown.
     * @throws java.security.InvalidKeyException if the files containing the keys don't
     * contain valid keys.
     */
    public RSAStringEncryptor(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 RSAPublicKey && prKey instanceof RSAPrivateKey)
        {
            this.publicKey = (RSAPublicKey)puKey;
            this.isEncryptInitialized = true;
            this.privateKey = (RSAPrivateKey)prKey;
            this.isDecryptInitialized = true;
        }
        else
            throw new InvalidKeyException("Some of the files don't contains" +
                    " a valid key");
    }
 
    /**
     * Constructs a new RSA encryptor in encrypt and decrypt mode with the
     * specified files containing the public and private key.
     * @param publicKeyFile the file containing the public key.
     * @param privateKeyFile the file containing the private key.
     * @throws java.io.FileNotFoundException if one of the files containing a key
     * doen't exist.
     * @throws java.io.IOException if an error occurs during reading one of the keys.
     * @throws java.lang.ClassNotFoundException if one of the class of the keys is
     * unknown.
     */
    public RSAStringEncryptor(File publicKeyFile, File privateKeyFile)
    throws FileNotFoundException, IOException, ClassNotFoundException
    {
        ObjectInputStream keyIn = new ObjectInputStream(
                new FileInputStream(publicKeyFile));
        this.publicKey = (RSAPublicKey) keyIn.readObject();
        this.isEncryptInitialized = true;
        keyIn.close();
 
        keyIn = new ObjectInputStream(
                new FileInputStream(privateKeyFile));
        this.privateKey = (RSAPrivateKey) keyIn.readObject();
        this.isDecryptInitialized = true;
        keyIn.close();
    }
 
    /**
     * Construct a new RSA encryptor in encrypt and decrypt mode with the
     * specified public and private key.
     * @param publicKey the public key (used to encrypt files and streams).
     * @param privateKey the private key (used to decrypt files and streams).
     **/
    public RSAStringEncryptor(RSAPublicKey publicKey, RSAPrivateKey privateKey)
    {
        this.publicKey = publicKey;
        this.isEncryptInitialized = publicKey == null;
        this.privateKey = privateKey;
        this.isDecryptInitialized = privateKey == null;
    }
 
    /**
     * Construct a new RSA encryptor in encrypt and decrypt mode with the
     * specified pair of keys.
     * @param keyPair the pair of keys used to encrypt and decrypt files and
     * streams.
     **/
    public RSAStringEncryptor(KeyPair keyPair)
    {
        this((RSAPublicKey)keyPair.getPublic(),
                (RSAPrivateKey)keyPair.getPrivate());
    }
 
    /**
     * Returns the public key of the underlying encryptor.
     * @return the public key of the underlying encryptor.
     **/
    public RSAPublicKey getPublicKey()
    {
        return (RSAPublicKey) publicKey;
    }
 
    /**
     * Sets the public key of the underlying encryptor.
     * @param key the public key to set.
     **/
    public void setPublicKey(RSAPublicKey key)
    {
        this.publicKey = key;
    }
 
    /**
     * Returns the private key of the underlying encryptor.
     * @return the private key of the underlying encryptor.
     **/
    public RSAPrivateKey getPrivateKey()
    {
        return (RSAPrivateKey) privateKey;
    }    
 
    /**
     * Encrypts the given datas in RSA and returns the result under bytes array 
     * format.
     * @param datas the datas to encrypt in RSA.
     * @return the result of RSA encryption under bytes array format.
     */
    public byte[] encryptBytes(byte[] datas)
    {
        return crypt(new BigInteger(addOneByte(datas))).toByteArray();
    }
 
 
    /**
     * Encrypts the given String in RSA and returns the result under bytes array 
     * format.<br>
     * Make sure the text is not to long, so that the decoded String in bytes array
     * can be convert in {@link java.math.BigInteger}.
     * @param text the text to encrypt.
     * @return the result of encryption under byte array format.
     */
    public byte[] encryptString(String text)
    {
        return encryptBytes(text.getBytes());
    }
 
 
    /**
     * Decrypts the given bytes with the RSA algorithm and returns the result under
     * bytes array format.
     * @param datas the datas to decrypt.
     * @return the result of decryption under bytes array format.
     */
    public byte[] decryptBytes(byte[] datas)
    {
        return removeOneByte(decrypt(new BigInteger(datas)).toByteArray());
    }
 
 
    /**
     * Decrypts the given datas with the RSA algorithm and returns the retult under
     * String format.
     * @param datas the datas to decrypt.
     * @return the result of decryption under string format.
     */
    public String decryptString(byte[] datas)
    {
        return new String(decryptBytes(datas));
    }
 
    private BigInteger crypt(BigInteger plaintext)
    {
        return plaintext.modPow(publicKey.getPublicExponent(), 
                publicKey.getModulus());
    }
 
 
    private BigInteger decrypt(BigInteger ciphertext)
    {
        return ciphertext.modPow(privateKey.getPrivateExponent(), 
                privateKey.getModulus());
    }
 
 
    /**
     * Ajoute un byte de valeur 1 au début du message afin d'éviter que ce dernier
     * ne corresponde pas à un nombre négatif lorsqu'il sera transformé en
     * BigInteger.
     */
    private byte[] addOneByte(byte[] input)
    {
        byte[] result = new byte[input.length+1];
        result[0] = 1;
        for (int i = 0; i < input.length; i++)
        {
            result[i+1] = input[i];
        }
        return result;
    }
 
 
    /**
     * Retire le byte ajouté par la méthode addOneByte.
     */
    private byte[] removeOneByte(byte[] input)
    {
        byte[] result = new byte[input.length-1];
        for (int i = 0; i < result.length; i++)
        {
            result[i] = input[i+1];
        }
        return result;
    }
 
}
Rq : cette classe s'inspire d'une version très courte proposée dans les sources Java.
__________________
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.
Razgriz est déconnecté   Envoyer un message privé 00
Vieux 14/09/2007, 10h04   #70
Razgriz
Membre confirmé
 
Avatar de Razgriz
 
Chercheur en informatique
Inscription : avril 2006
Messages : 383
Détails du profil
Informations professionnelles :
Activité : Chercheur en informatique

Informations forums :
Inscription : avril 2006
Messages : 383
Points : 251
Points : 251
Pom pom pom pom pom pom....

Bon allez encore un encrypteur, en PBE (Password Besed Encryption) cette fois. Cette classe hérite encore de CipherEncryptor presente ici (dernier post de la page).

Si j'en vois encore un poser une question en cryptage dans le forum Sécurité, il va m'entendre parler du pays (comme on dit dans le coin lol).

Bon plus sérieux, cette classe crypte symétriquement (plus rapide que l'asymétrique donc) et a l'avantage qu'on ne doit pas stocker la clé de cryptage. En effet si on veut crypter un document, on donne un password. La clé est générée sur base de ce password, on crypte le document, et voilà c'est tout. On enregistre pas la clé.
Pour décrypter, on donne le pass, on génère une clé avec ce pass (qui si les deux pass sont identiques est LA MEME que celle générée précédemment) et on décrypte.

[EDIT]
Classe mise à jour le 16/10/2007 d'un point de vue modélisation et sécurité.
La superclasse se trouve ici
[/EDIT]

Voici le code source :
Code :
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
 
/*
 * PBEEncryptor.java
 *
 * Created on 11 septembre 2007, 14:11
 *
 */
 
package org.cosmopol.crypto;
 
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.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
 
/**
 * This class provides methods to generate keys, encrypt or decrypt bytes, 
 * files and streams with the PBE (Password Based Encryption) algorithm.
 * @author Administrateur
 */
public class PBEEncryptor extends FileEncryptor
{
    private SecretKey key;
    private byte[] encodedAlgParams;
    private byte[] decodedAlgParams;
    private Cipher decryptor;
    private Cipher encryptor;
 
    /**
     * Constructs a new PBE encryptor with the key used to encrypt 
     * and decrypt bytes, files and streams.
     * @param key the key used to encrypt and decrypt bytes, files and
     * streams.
     * @throws java.security.InvalidKeyException if the key is invalid
     * for PBE encryption or decryption.
     * @throws java.io.IOException if an error occurs during encoding
     * the key.
     **/
    public PBEEncryptor(SecretKey key) throws InvalidKeyException, IOException
    {
        this.key = key;
        this.initialize(key);
    }
 
    /**
     * Constructs a new PBE encryptor with the secret key contained in the 
     * given file. This key will be used to encrypt and decrypt bytes, files 
     * and streams.
     * @param file the file containing the key used to encrypt and decrypt
     * bytes, files and streams.
     * @throws java.security.InvalidKeyException if the key is invalid
     * for PBE encryption or decryption.
     * @throws java.io.IOException if an error occurs during encoding
     * the key or reading the key file.
     * @throws java.lang.ClassNotFoundException if the class of the key
     * is unknown.
     **/
    public PBEEncryptor(File file) 
        throws IOException, ClassNotFoundException, 
            InvalidKeyException
    {
        ObjectInputStream reader = new ObjectInputStream(
                new FileInputStream(file));
        this.key = (SecretKey)reader.readObject();
        this.initialize(key);
    }
 
    /**
     * Constructs a new PBE encryptor with the secret key contained in the 
     * given file denoted by its pathname. This key will be used to encrypt and
     * decrypt bytes, files and streams.
     * @param path the path of the file containing the key used to encrypt and
     * decrypt bytes, files and streams.
     * @throws java.security.InvalidKeyException if the key is invalid
     * for PBE encryption or decryption.
     * @throws java.io.IOException if an error occurs during encoding
     * the key or reading the key file.
     * @throws java.lang.ClassNotFoundException if the class of the key
     * is unknown.
     **/
    public PBEEncryptor(String path) 
        throws IOException, ClassNotFoundException, 
            InvalidKeyException
    {
        this(new File(path));
    }
 
    //initializes the PBE encryptor with the given key.
    private void initialize(SecretKey key) 
        throws InvalidKeyException, IOException
    {
        AlgorithmParameters decParams = null;
        try
        {
            encryptor = Cipher.getInstance("PBEWithMD5AndDES");
            decryptor = Cipher.getInstance("PBEWithMD5AndDES");
            decParams = AlgorithmParameters.getInstance("PBEWithMD5AndDES");
        }
        catch(NoSuchPaddingException ex)
        {
            ex.printStackTrace();
        }
        catch(NoSuchAlgorithmException ex)
        {
            ex.printStackTrace();
        }
        encryptor.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters encParams = encryptor.getParameters();
        this.encodedAlgParams = encParams.getEncoded();
 
        decParams.init(encodedAlgParams);
        decodedAlgParams = decParams.getEncoded();
        try
        {
            decryptor.init(Cipher.DECRYPT_MODE, key, decParams);
        }
        catch(InvalidKeyException ex)
        {
            ex.printStackTrace();
        }
        catch(InvalidAlgorithmParameterException ex)//never thrown
        {
            ex.printStackTrace();
        }
    }
 
    /**
     * Generates a key for PBE encryption and decryption with the secified
     * javax.crypto.spec.PBEKeySpec used for generation.
     * @param keySpec the parameters used for key generation.
     * @return the generated key.
     **/
    public static SecretKey generateKey(PBEKeySpec keySpec)
    {
        SecretKeyFactory factory = null;
        try
        {
            factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        }
        catch (NoSuchAlgorithmException ex)//never thrown
        {
            ex.printStackTrace();
        }
 
        SecretKey key = null;
        try
        {
            key = factory.generateSecret(keySpec);//never thrown
        }
        catch (InvalidKeySpecException ex)
        {
            ex.printStackTrace();
        }
        return key;
    }
 
    /**
     * Generates a key for PBE encryption and decryption with te specified
     * password as a char array and default salt, iteration count and size.
     * @param password the password used for key generation.
     * @return the generated key.
     **/
    public static SecretKey generateKey(char[] password)
    {
        return generateKey(new PBEKeySpec(password));
    }
 
    /**
     * Generates a key for PBE encryption and decryption with the password as
     * a char array, salt as a bytes array, iteration count and default key 
     * size.
     * @param password the password used for key generation.
     * @param salt the salt used for key generation.
     * @param iterationCount the number of iteration used for key generation.
     * @return the generated key.
     **/
    public static SecretKey generateKey(char[] password, byte[] salt, 
            int iterationCount)
    {
        return generateKey(new PBEKeySpec(password, salt, iterationCount));
    }
 
    /**
     * Generates a key for PBE encryption of the specified size and decryption
     * with the password as a char array, salt as a bytes array, iteration 
     * count.
     * @param password the password used for key generation.
     * @param salt the salt used for key generation.
     * @param iterationCount the number of iteration used for key generation.
     * @param keySize the size of the key to generate.
     * @return the generated key.
     **/
    public static SecretKey generateKey(char[] password, byte[] salt, 
            int iterationCount, int keySize)
    {
        return generateKey(
                new PBEKeySpec(password, salt, iterationCount, keySize));
    }
 
    /**
     * Generates a key for PBE encryption and decryption with the secified
     * javax.crypto.spec.PBEKeySpec used for generation and save it in
     * the specified file.
     * @param keyspec the parameters used for key generation.
     * @param file the file where you want to save the key.
     * @throws java.io.IOException if an error occurs during writing
     * the key.
     */
    public static void generateAndSaveKey(PBEKeySpec keyspec, File file) 
        throws IOException
    {
        SecretKey key = generateKey(keyspec);
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(file));
        out.writeObject(key);
        out.close();
    }
 
    /**
     * Generates a key for PBE encryption and decryption with the secified
     * javax.crypto.spec.PBEKeySpec used for generation and save it in
     * the file denoted by the given path.
     * @param keyspec the parameters used for key generation.
     * @param path the path the file where you want to save the key.
     * @throws java.io.IOException if an error occurs during writing
     * the key.
     */
    public static void generateAndSaveKey(PBEKeySpec keyspec, String path) 
        throws IOException
    {
        generateAndSaveKey(keyspec, new File(path));
    }
 
    /**
     * Generates a key for PBE encryption and decryption with the password as
     * a char array, salt as a bytes array, iteration count and default key 
     * size and save it in the specified file.
     * @param password the password used for key generation.
     * @param salt the salt used for key generation.
     * @param iterationCount the number of iteration used for key generation.
     * @param file the file where you want to save the key.
     * @throws java.io.IOException if an error occurs during writing
     * the key.
     **/
    public static void generateAndSaveKey(char[] password, byte[] salt, 
            int iterationCount, File file) 
                throws IOException
    {
        generateAndSaveKey(new PBEKeySpec(password, salt, iterationCount), 
                file);
    }
 
    /**
     * Generates a key for PBE encryption and decryption with the password as
     * a char array, salt as a bytes array, iteration count and default key 
     * size and save it in the file denoted by the specified path.
     * @param password the password used for key generation.
     * @param salt the salt used for key generation.
     * @param iterationCount the number of iteration used for key generation.
     * @param path the path the file where you want to save the key.
     * @throws java.io.IOException if an error occurs during writing
     * the key.
     **/
    public static void generateAndSaveKey(char[] password, byte[] salt, 
            int iterationCount, String path)
                throws IOException
    {
        generateAndSaveKey(new PBEKeySpec(password, salt, iterationCount), 
                path);
    }
 
    /**
     * Generates a key for PBE encryption of the specified size and decryption
     * with the password as a char array, salt as a bytes array, iteration 
     * count and save it into the specified file.
     * @param password the password used for key generation.
     * @param salt the salt used for key generation.
     * @param iterationCount the number of iteration used for key generation.
     * @param keySize the size of the key to generate.
     * @param file the file where you want to save the key.
     * @throws java.io.IOException if an error occurs during writing
     * the key.
     **/
    public static void generateAndSaveKey(char[] password, byte[] salt, 
            int iterationCount, int keySize, File file)
                throws IOException
    {
        generateAndSaveKey(new PBEKeySpec(password, salt, iterationCount, 
                keySize), file);   
    }
 
    /**
     * Generates a key for PBE encryption of the specified size and decryption
     * with the password as a char array, salt as a bytes array, iteration 
     * count and save it into the file denoted by the specified path.
     * @param password the password used for key generation.
     * @param salt the salt used for key generation.
     * @param iterationCount the number of iteration used for key generation.
     * @param keySize the size of the key to generate.
     * @param path the path of the file where you want to save the key.
     * @throws java.io.IOException if an error occurs during writing
     * the key.
     **/
    public static void generateAndSaveKey(char[] password, byte[] salt, 
            int iterationCount, int keySize, String path)
                throws IOException
    {
        generateAndSaveKey(new PBEKeySpec(password, salt, iterationCount, 
                keySize), path);
    }
 
    /**
     * Encrypts the specified input stream to the specified output stream.
     * @param in the stream to encrypt.
     * @param out the stream where you want to write the encrypted stream.
     * @throws java.io.IOException if an error occurs during writing encrypted
     * datas.
     */
    public void encryptStream(InputStream in, OutputStream out) 
        throws IOException
    {
        super.crypt(in, out, encryptor);
    }
 
    /**
     * Decrypts the specified input stream to the specified output stream.
     * 
     * @param in the stream to decrypt.
     * @param out the stream where you want to write the decrypted stream.
     * @throws java.io.IOException if an error occurs during writing encrypted
     * datas.
     */
    public void decryptStream(InputStream in, OutputStream out) throws IOException
    {
        super.crypt(in, out, decryptor);
    }
}
__________________
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.
Razgriz est déconnecté   Envoyer un message privé 00
Vieux 16/10/2007, 15h19   #71
Razgriz
Membre confirmé
 
Avatar de Razgriz
 
Chercheur en informatique
Inscription : avril 2006
Messages : 383
Détails du profil
Informations professionnelles :
Activité : Chercheur en informatique

Informations forums :
Inscription : avril 2006
Messages : 383
Points : 251
Points : 251
Yop yop,

voici ci dessous une classe qui à priori ne sert pas à grand chose mais qui en fait met à jour les classes de cryptage de fichiers(RSA, PBE, Symetric) postées dans ce topic et remodule la structure.

Cette superclasse hérite de CipherEncryptor et est la superclasse de tous les encrypeurs de streams.

Voici donc :
Code :
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
 
/*
 * FileEncryptor.java
 *
 * Created on 17 septembre 2007, 13:47
 *
 */
 
package org.cosmopol.crypto;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.OutputStream;
import java.security.InvalidKeyException;
 
/**
 * This class provides methods to
 * @author Administrateur
 */
public abstract class FileEncryptor extends CipherEncryptor
{
    /**
     * Encrypts the specified input file to the specified output file.
     * @param input the file to encrypt.
     * @param output the file where the result of encryption is written.
     * @throws java.io.FileNotFoundException if the input file denoted by its
     * pathname doesn't exist.
     * @throws java.security.InvalidKeyException if the encryption key is not 
     * valid for the underlying encryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the encryption.
     **/
    public void encryptFile(File input, File output) 
        throws FileNotFoundException, InvalidKeyException, IOException
    {
        InputStream in = new FileInputStream(input);
        OutputStream out = new FileOutputStream(output);
        encryptStream(in,out);
    }
 
    /**
     * Encrypts the file denoted by the specified input path to the file
     * denoted by the specified output path.
     * @param inputFileName the name of the file to encrypt.
     * @param outputFileName the name of the file where the result of
     * encryption is written.
     * @throws java.io.FileNotFoundException if the input file denoted by its
     * pathname doesn't exist.
     * @throws java.security.InvalidKeyException if the encryption key is not 
     * valid for the underlying encryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the encryption.
     **/
    public void encryptFile(String inputFileName, String outputFileName) 
        throws FileNotFoundException, InvalidKeyException, IOException
    {
        encryptFile(new File(inputFileName), new File(outputFileName));
    }
 
    /**
     * Encrypts the specified datas under bytes array format and returns the
     * result of encryption under bytes array format.
     * @param inbytes the bytes to encrypt.
     * @return the result of encryption under bytes array format.
     * @throws java.security.InvalidKeyException if the encryption key is not
     * valid fot the underlying encryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the encryption.
     **/
    public byte[] encryptBytes(byte[] inbytes) throws InvalidKeyException, IOException
    {
        ByteArrayInputStream in = new ByteArrayInputStream(inbytes);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encryptStream(in, out);
        return out.toByteArray();
    }
 
    /**
     * Decrypts the specified input file to the specified output file.
     * @param input the file to decrypt.
     * @param output the file where the result of decryption is written.
     * @throws java.io.FileNotFoundException if the input file denoted by its
     * pathname doesn't exist.
     * @throws java.security.InvalidKeyException if the decryption key is not 
     * valid for the underlying decryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the decryption.
     **/
    public void decryptFile(File input, File output) 
        throws FileNotFoundException, InvalidKeyException, IOException
    {
        InputStream in = new FileInputStream(input);
        OutputStream out = new FileOutputStream(output);
        decryptStream(in,out);
    }
 
    /**
     * Decrypts the file denoted by the specified input path to the file
     * denoted by the specified output path.
     * @param inputFileName the name of the file to decrypt.
     * @param outputFileName the name of the file where the result of
     * decryption is written.
     * @throws java.io.FileNotFoundException if the input file denoted by its
     * pathname doesn't exist.
     * @throws java.security.InvalidKeyException if the decryption key is not 
     * valid for the underlying decryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the decryption.
     **/
    public void decryptFile(String inputFileName, String outputFileName) 
        throws FileNotFoundException, InvalidKeyException, IOException
    {
        decryptFile(new File(inputFileName), new File(outputFileName));
    }
 
    /**
     * Decrypts the specified datas under bytes array format and returns the
     * result of decryption under bytes array format.
     * @param ciphered the bytes to encrypt.
     * @return the result of decryption under bytes array format.
     * @throws java.security.InvalidKeyException if the decryption key is not
     * valid fot the underlying decryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the decryption.
     **/
    public byte[] decryptBytes(byte[] ciphered) throws InvalidKeyException, IOException
    {
        ByteArrayInputStream in = new ByteArrayInputStream(ciphered);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        decryptStream(in, out);
        return out.toByteArray();
    }
 
    /**
     * Encrypts the specified input stream to the specified output stream.
     * @param in the input stream to encrypt.
     * @param out the stream where you want the result of encryption to be
     * written.
     * @throws java.security.InvalidKeyException if the encryption key is not 
     * valid for the underlying encryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the encryption.
     **/
    public abstract void encryptStream(InputStream in, OutputStream out) 
        throws InvalidKeyException, IOException;
 
    /**
     * Decrypts the specified input stream to the specified output stream.
     * @param in the input stream to decrypt.
     * @param out the stream where you want the result of decryption to be
     * written.
     * @throws java.security.InvalidKeyException if the decryption key is not 
     * valid for the underlying decryption algorithm.
     * @throws java.io.IOException if an I/O error occurs during the decryption.
     **/
    public abstract void decryptStream(InputStream in, OutputStream out) 
        throws InvalidKeyException, IOException;
}
__________________
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.
Razgriz est déconnecté   Envoyer un message privé 00
Vieux 16/10/2007, 15h44   #72
Razgriz
Membre confirmé
 
Avatar de Razgriz
 
Chercheur en informatique
Inscription : avril 2006
Messages : 383
Détails du profil
Informations professionnelles :
Activité : Chercheur en informatique

Informations forums :
Inscription : avril 2006
Messages : 383
Points : 251
Points : 251
Yop,

voici un encrypteur qui zippe des fichiers en les cryptant (encrypteur au choix) et les dézippe en les décryptant.

Note, cette classe est quasi la même que celle postée ici par le y@m's, elle inclut simpmement une fonction de cryptage. Merci à lui donc, sans lui cette clas ne serait pas.

Note : la classe FileEncryptor se trouve ici et les classes de cryptage concrètes sont éparpillées un peu partout dans le topic.

Note pour les administrateurs : si possible pour éviter toutes les questions dans les topics j'aierais bien faire un tuto cryptographie Java, mais je ne sais pas comment m'y prendred 'un point de vue administratif. Ca sera plus clair que tous ces posts éparpillés dans le topic.

Code :
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
 
/*
 * ZipFileEncryptor.java
 *
 * Created on 19 septembre 2007, 13:15
 *
 */
 
package org.cosmopol.crypto;
 
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.security.InvalidKeyException;
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;
 
/**
 * This class provides methods for zip compression, encrypting the given files
 * with a file encryptor.
 * @author Absil Romain.
 */
public class ZipFileEncryptor
{
    private FileEncryptor encryptor;
 
    /**
     * A null checksum if you don't want to use a checksome for zip
     * compression.
     **/
    public static final Checksum CHECK_NONE = null;
 
    /**
     * The Adler32 checksum used for zip compression.
     **/
    public static final Checksum CHECK_ADLER32 = new Adler32();
 
    /**
     * The CRC32 checksum used for zip compression.
     **/
    public static final Checksum CHECK_CRC32 = new CRC32();
 
    /**
     * Constructs a new zip file encryptor with the specified file encryptor
     * used for encrypt or decrypt file to / from zip archives.
     * @param encryptor the encryptor used for file encryption and / or
     * decryption.
     **/
    public ZipFileEncryptor(FileEncryptor encryptor)
    {
        this.encryptor = encryptor;
    }
 
    /**
     * Unzip the specified zip file to the same location it lies using no
     * checksum and erasing the existing files during unzip processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param file the file to unzip.
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(File file) throws IOException, InvalidKeyException
    {
        String path = file.getAbsolutePath();
        unzip(path, path.substring(0, path.lastIndexOf(File.separatorChar)));
    }
 
    /**
     * Unzip the zip file denoted by the specified path to the same location
     * it lies using no checksum and erasing the existing files duriing unzip
     * processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param path the path of the file to unzip.
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(String path) throws IOException, InvalidKeyException
    {
        unzip(path, path.substring(0, path.lastIndexOf(File.separatorChar)));
    }
 
    /**
     * Unzip the specified zip file to the same location it lies using the
     * specified checksum and erasing the existing files duriing unzip
     * processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param file the file to unzip.
     * @param checksum the checksum used to unzip the file.
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     */
    public void unzip(File file, Checksum checksum) 
        throws IOException, InvalidKeyException    
    {
        String path = file.getAbsolutePath();
        unzip(path, path.substring(0, path.lastIndexOf(File.separatorChar)),
                checksum);
    }
 
    /**
     * Unzip the zip file denoted by the specified path to the same location
     * it lies using the specified checksum and erasing the existing files
     * during unzip processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param path the path of the file to unzip.
     * @param checksum the checksum used to unzip the file.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(String path, Checksum checksum) 
        throws IOException, InvalidKeyException    
    {
        unzip(path, path.substring(0, path.lastIndexOf(File.separatorChar)),
                checksum);
    }
 
    /**
     * Unzip the specified zip file to the specified location using no
     * checksum and erasing the existing files during unzip processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param file the file to unzip.
     * @param destination the file you want the unzipped file to be
     * written.
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(File file, File destination) 
        throws IOException, InvalidKeyException
    {
        unzip(file, destination, true, CHECK_NONE);
    }
 
    /**
     * Unzip the zip file denoted by the sopecified path to the specified
     * location using no checksum and erasing the existing files during unzip
     * processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param path the path of the file to unzip.
     * @param destinationPath the path of the file you want the unzipped file to be
     * written.
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(String path, String destinationPath)
        throws IOException, InvalidKeyException
    {
        unzip(path, destinationPath, true, CHECK_NONE);
    }
 
    /**
     * Unzip the specified zip file to the specified location using the
     * specified checksum and erasing the existing files during unzip 
     * processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param file the file to unzip.
     * @param checksum the checksum used to unzip the file.
     * @param destination the file you want the unzipped file to be written.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(File file, File destination, Checksum checksum)
        throws IOException, InvalidKeyException
    {
        unzip(file, destination, true, checksum);
    }
 
    /**
     * Unzip the zip file denotedby the specified path to the specified
     * location using the specified checksum and erasing the existing files
     * during unzip processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param path the path of the file to unzip.
     * @param checksum the checksum used to unzip the file.
     * @param destinationPath the path of the file you want the unzipped file to be written.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(String path, String destinationPath, Checksum checksum)
        throws IOException, InvalidKeyException
    {
        unzip(path, destinationPath, true, checksum);
    }
 
    /**
     * Unzip the specified zip file to the specified location using the
     * specified checksum and erasing or not the existing files duriing unzip
     * processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param file the file to unzip.
     * @param destination the file you want the unzipped file to be
     * written.
     * @param erase true if you want the files lying under the specified to be
     * erased if an unzipped file has the same name, false otherwise.
     * @param checksum the checksum used to unzip the file.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(File file, File destination, boolean erase, 
            Checksum checksum) 
                throws IOException, InvalidKeyException
    {
        String destinationPath = destination.getAbsolutePath();
        ZipFile zipfile = new ZipFile(file);
        FileInputStream fis = new FileInputStream(zipfile.getName());
        CheckedInputStream checker = (checksum == null) ? null :
            new CheckedInputStream(fis, checksum);
        BufferedInputStream bis = new BufferedInputStream((checker != null) ?
            checker : fis);
        ZipInputStream unzipper = new ZipInputStream(bis);
        ZipEntry entry = null;
        try
        {
            while((entry = unzipper.getNextEntry()) != null)
            {
                File f = new File(destinationPath + File.separatorChar +
                        entry.getName());
                if(entry.isDirectory())
                {
                    if(!f.exists())
                        f.mkdirs();
                    continue;
                }
                if(f.exists())
                {
                    if(erase)
                        f.delete();
                    else
                        continue;
                }
                f.createNewFile();
                FileOutputStream writer = new FileOutputStream(f);
                try
                {
                    encryptor.decryptStream(unzipper, writer);
                }
                finally
                {
                    writer.close();
                }
            }
        }
        finally
        {
            unzipper.close();
            bis.close();
            if(checker != null)
                checker.close();
            fis.close();
        }
    }
 
    /**
     * Unzip the zip file denoted by the specified path to the specified
     * location using the specified checksum and erasing or not the existing
     * files duriing unzip processing.<br>
     * Note that the file is unzipped recursively, i.e. if the archive contains
     * at least a directory, it will be unzipped recursively.
     * @param path the path of the file to unzip.
     * @param destinationPath the path of the file you want the unzipped file
     * to be written.
     * @param erase true if you want the files lying under the specified to be
     * erased if an unzipped file has the same name, false otherwise.
     * @param checksum the checksum used to unzip the file.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     * @throws java.io.IOException if an I/O error occurs during unzipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file decryption is invalid for this algorithm.
     */
    public void unzip(String path, String destinationPath, boolean erase,
            Checksum checksum) 
                throws IOException, InvalidKeyException
    {
        unzip(new File(path), new File(destinationPath), erase, checksum);
    }
 
    /**
     * Zips the specified files to the specified zip file using a default
     * compression level and no checksum.
     * @param zipFile the file where you want the specified files to be zipped.
     * @param files the files to zip.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     */
    public void zip(File zipFile, File ... files)
        throws IOException, InvalidKeyException
    {
        zip(zipFile, Deflater.DEFAULT_COMPRESSION, files);
    }
 
    /**
     * Zips the files denoted by the specified paths to the zip file denoted
     * by the specified pathusing a default compression level and no checksum.
     * @param zipPath the path of the file where you want the specified files
     * to be zipped.
     * @param paths the paths of the files to zip.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     */
    public void zip(String zipPath, String ... paths) 
        throws IOException, InvalidKeyException
    {
        zip(new File(zipPath), buildFiles(paths));
    }
 
    /**
     * Zips the specified files to the specified zip file using a specified
     * compression level and no checksum.
     * @param zipFile the file where you want the specified files to be zipped.
     * @param files the files to zip.
     * @param level the level of zip compression.
     * @see java.util.zip.Deflater for informations on zip compression level.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     */
    public void zip(File zipFile, int level, File ... files)
        throws IOException, InvalidKeyException
    {
        zip(zipFile, level, CHECK_NONE, files);
    }
 
    /**
     * Zips the files denoted by the specified paths to the zip file denoted
     * by the specified pathusing a default compression level and no checksum.
     * @param zipPath the path of the file where you want the specified files
     * to be zipped.
     * @param level the level of zip compression.
     * @param paths the paths of the files to zip.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     */
    public void zip(String zipPath, int level, String ... paths)
        throws IOException, InvalidKeyException
    {
        zip(new File(zipPath), level, CHECK_NONE, buildFiles(paths));
    }
 
    /**
     * Zips the specified files to the specified zip file using a default
     * compression level and the specified checksum.
     * @param zipFile the file where you want the specified files to be zipped.
     * @param files the files to zip.
     * @param checksum the checksum to use for zip compression.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     */
    public void zip(File zipFile, Checksum checksum, File ... files)
        throws IOException, InvalidKeyException
    {
        zip(zipFile, Deflater.DEFAULT_COMPRESSION, checksum, files);
    }
 
    /**
     * Zips the files denoted by the specified paths to the zip file denoted
     * by the specified path using a default compression level and the
     * specified checksum.
     * @param zipPath the path of the file where you want the specified files
     * to be zipped.
     * @param paths the paths of the files to zip.
     * @param checksum the checksum to use for zip compression.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     */
    public void zip(String zipPath, Checksum checksum, String ... paths)
        throws IOException, InvalidKeyException
    {
        zip(new File(zipPath), Deflater.DEFAULT_COMPRESSION, checksum, 
                buildFiles(paths));
    }
 
    /**
     * Zips the specified files to the specified zip file using a specified
     * compression level and the specified checksum.
     * @param zipFile the file where you want the specified files to be zipped.
     * @param files the files to zip.
     * @param level the level of zip compression.
     * @param checksum the checksum to use for zip compression.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     * @throws java.io.FileNotFoundException if one of the input files doesn't
     * exist.
     * @see java.util.zip.Deflater for informations on zip compression level.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     */
    public void zip(File zipFile, int level, Checksum checksum, File ... files)
        throws FileNotFoundException, IOException, InvalidKeyException
    {
        FileOutputStream out = new FileOutputStream(zipFile);
        CheckedOutputStream checker = (checksum == null) ? null :
            new CheckedOutputStream(out, checksum);
        BufferedOutputStream writer = new BufferedOutputStream(
                (checker != null) ? checker : out);
        ZipOutputStream zipper = new ZipOutputStream(writer);
        zipper.setMethod(zipper.DEFLATED);
        zipper.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);
                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);
                        zipper.closeEntry();
                        zipper.putNextEntry(e.getKey());
                        continue;
                    }
                    zipper.putNextEntry(e.getKey());
                    FileInputStream reader = new FileInputStream(e.getValue());
                    try
                    {
                        encryptor.encryptStream(reader, zipper);
                    }
                    finally
                    {
                        zipper.closeEntry();
                        reader.close();
                    }
                }
            }
            zipper.finish();
        }
        finally
        {
            zipper.close();
            writer.close();
            if(checker != null)
                checker.close();
            out.close();
        }
    }
 
    /**
     * Zips the files denoted by the specified paths to the zip file denoted by
     * the specified path using a specified compression level and the specified
     * checksum.
     * @param zipPath the path of the file where you want the specified files
     * to be zipped.
     * @param paths the path of the files to zip.
     * @param level the level of zip compression.
     * @param checksum the checksum to use for zip compression.
     * @throws java.io.IOException if an I/O error occurs during zipping
     * process.
     * @throws java.security.InvalidKeyException if the encryptor's key used
     * for file encryption is invalid for this algorithm.
     * @throws java.io.FileNotFoundException if one of the input files doesn't
     * exist.
     * @see java.util.zip.Deflater for informations on zip compression level.
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_NONE
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_ADLER32
     * @see org.cosmopol.crypto.ZipFileEncryptor#CHECK_CRC32
     */
    public void zip(String zipPath, int level, Checksum checksum, 
        String ... paths)
            throws FileNotFoundException, IOException, InvalidKeyException
    {
        zip(new File(zipPath), level, checksum, buildFiles(paths));
    }
 
    //creates recursively the zip entries for the given files.
    private static 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;
    }
 
    //buils files from their paths.
    private File[] buildFiles(String ... paths)
    {
        File[] files = new File[paths.length];
        for (int i = 0; i < files.length; i++)
            files[i] = new File(paths[i]);
        return files;
    }
}
__________________
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.
Razgriz est déconnecté   Envoyer un message privé 00
Vieux 04/11/2007, 06h30   #73
broumbroum
Membre éclairé
 
Avatar de broumbroum
 
Inscription : août 2006
Messages : 406
Détails du profil
Informations personnelles :
Âge : 29

Informations forums :
Inscription : août 2006
Messages : 406
Points : 383
Points : 383
Par défaut Sprite avec transform et cache (JAI/JIIO) + Animation (compatibles Swing)

Salut à tous !
Après plusieurs essais, voici enfin une première version d'une classe pour afficher une image (appelée "sprite" car elle est synchronisée sur son contenu...) dans un composant Swing ou en active rendering.
Pour utiliser Swing, il faut instancier la classe comme un composant habituel puis valider avant chaque rendu. Cela donne grosso modo un code très réduit qui peut afficher un Sprite en transparence ou opaque :
Code :
1
2
3
4
5
try{
JComponent sprite = new Sprite((String) filename, (boolean) rsrcMode, (String) format, (Dimension) size, (boolean) buf);
sprite.validate();
sprite.repaint();
} catch(URISyntaxException e) { e.printStackTrace(); }

Note: les effets en Composite ou AffineTransform sont appliqués UNE FOIS. Pour ce qui est des fonctions setFlipEnabled() et setZoomEnabled() ils faut les protéger avec une condition if sur leur état :
Code :
1
2
3
4
if(transform != sp.isZoomEnabled() || sp.getZoomValue() != zoom)
            sp.setZoomEnabled(transform, zoom);        
if(transform != sp.isFlipEnabled() || sp.getMirrorValue() != mirror)
            sp.setFlipEnabled(transform, mirror);
NOTE : se munir du cache présenté plus haut dans le forum (page 4).
Fichiers attachés
Type de fichier : zip sprite.zip (35,7 Ko, 6 affichages)
broumbroum est déconnecté   Envoyer un message privé 00
Vieux 05/11/2007, 04h19   #74
broumbroum
Membre éclairé
 
Avatar de broumbroum
 
Inscription : août 2006
Messages : 406
Détails du profil
Informations personnelles :
Âge : 29

Informations forums :
Inscription : août 2006
Messages : 406
Points : 383
Points : 383
Par défaut Après le Sprite, la gestion des Canvas de rendu graphique

Avec les Sprites les références aux resources images sont maintenant facilement exploitables sans perte de vitesse (surtout pour le chargement des images) et procurent un accès facilité au double-buffering. Une classe utilisant ces Sprite's pour afficher en passif ou actif en passant par le double-buffering (déjà disponible avec tous les composants Swing) permet de ne pas perdre du temps à recharger les resources relatives au rendu graphique direct à l'écran. Ainsi, RenderingScene est une classe de rendu graphique pouvant se placer au coeur de toute application nécessitant un cadre scénique pour les animations ou graphisme divers.

Les librairies JAI/JIIO doivent être installées. Des raccourcis clavier ont été implémentés ainsi qu'une console de logging du STDOUT, malheureusement encore en phase de développement. Libre à vous de vous inspirer pour votre propre recherche et/ou développement.

Pour l'utiliser, tout se simplifie grâce à 2 Timers Swing intégrés dont un sert au rendu offscreen :
Code :
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
final Canvas scene = new RenderingScene(new Dimension((int)largeur, (int)hauteur));
// ajouter une action de rendu
((RenderingScene)scene).addActionOffscreen(new AbstractAction() { public void actionPerformed(ActionEvent e) {
       // récupérer le buffer off
       Sprite buffer = ((RenderingScene)scene).getOffscreen();
       Image offscreen = buffer.getImage();
       // et faire son rendu en une passe !
       // par ex. pour dessiner un ovale 30*30 dans le coin superieur droit
       Graphics g = offscreen.getGraphics();
       Color clr = graphics.getColor();
            graphics.setColor(Color.GREEN);
                graphics.drawOval(scene.getWidth() - 30, 0, 30, 30);
                    graphics.fillOval(scene.getWidth() - 30, 0, 30, 30);
            graphics.setColor(clr);
}});
// préparer une fenetre
JFrame frame = new JFrame("rendering scene");
frame.getContentPane().add(scene);
frame.pack();
frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {
       System.exit(0);
}});
frame.setLocationRelativeTo(null);
frame.setVisible(true); 
// démarrer le rendu
((RenderingScene)scene).resume();
// faire un loop si nécessaire pour eviter de quitter en fin de methode
while(frame.isShowing()) {
   System.out.println("-loop-");  
   Thread.sleep(500);
}
Note: Tout se passe bien avec Java 1.5+ sur PC ou Mac (Linux pas testé car je n'ai pas les librairies et le pc.... lol)
Fichiers attachés
Type de fichier : zip scene.zip (30,7 Ko, 3 affichages)
broumbroum est déconnecté   Envoyer un message privé 00
Vieux 10/11/2007, 23h56   #75
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Lecteur simple de fichiers textes

Bonjour,

voici un simple lecteur de fichiers textes :
Code :
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
 
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Vector;
 
/* Une classe pour lire simplement des fichiers textes.
 *
 * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
public class TextFileReader {
 
  // Un vecteur pour stocker les lignes du fichier
  private Vector lines;
 
  // Création de l'objet de lecture
  public TextFileReader(String fileName) {
    lines = new Vector();
    File f = new File(fileName);
    try {
      FileReader fr = new FileReader(fileName);
      BufferedReader br = new BufferedReader(fr);
      while (br.ready())
        lines.add(br.readLine());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  // Récupération des lignes pour utilisation
  public Vector getLines() {
    return lines;
  }
 
  // Exemple d'utilisation
  public static void main(String[] args) {
    TextFileReader tfr = new TextFileReader("ldb/part0.txt");
    Vector v = tfr.getLines();
    int n = v.size();
    for (int i = 0 ; i < n ; i++)
      System.out.println((String)v.get(i));
    while (true);
  }
 
}
Dans le projet commons-io de Jakarta, vous retrouvez la même fonctionnalité avec la méthode readLines(File) qui retourne une List de String. (merci Napalm51)
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 11/11/2007, 01h10   #76
anadoncamille
Membre habitué
 
Avatar de anadoncamille
 
Inscription : juillet 2007
Messages : 222
Détails du profil
Informations forums :
Inscription : juillet 2007
Messages : 222
Points : 118
Points : 118
Par défaut Un générateur de langue de bois

Mesdames, messieurs,
il m'apparait comme capital dans la conjoncture actuelle de vous faire part d'un outil dont les fonctionnalités, outre le fait qu'elles sont nombreuses et variées, sont à la fois d'une grande diversité et d'une grande qualité. Qui plus est, leur nombre conséquent ne devrait pas nous faire oublier que voici donc le code :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
 
import java.util.Random;
 
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
 
/* Un générateur sensible de discours percutants de politicien sérieux
 * permettant au terme d'un délicat apprentissage et d'un perpétuelle remise en question
 * d'atteindre d'immenses sommets de brillant charisme et de profonde hypnose.
 * (cf langue de bois)
 *
 * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
 */
public class Nahko {
 
    // Introduction : focalisation
  private static final String[] part0 = {
    "Mesdames, Messieurs, ",
    "Je reste fondamentalement persuadé que ",
    "Dès lors, sachez que je me battrai pour faire admettre que ",
    "Par ailleurs, c'est en toute connaissance de cause que je peux affirmer aujourd'hui que ",
    "Je tiens à vous dire ici ma détermination sans faille pour clamer haut et fort que ",
    "J'ai depuis longtemps (ai-je besoin de vous le rappeler ?) défendu l'idée que ",
    "Et c'est en toute conscience que je déclare avec conviction que ",
    "Et ce n'est certainement pas vous, mes chers compatriotes, qui me contredirez si je vous dis que ",
  };
 
  // Début de phrase : concentration
  private static final String[] part1 = {
    "la conjoncture actuelle ",
    "la situation d'exclusion que certains d'entre vous connaissent ",
    "l'acuité des problèmes de la vie quotidienne ",
    "la volonté farouche de sortir notre pays de la crise ",
    "l'effort prioritaire en faveur du statut précaire des exclus ",
    "le particularisme dû à notre histoire unique ",
    "l'aspiration plus que légitime de chacun au progrès social ",
    "la nécessité de répondre à votre inquiétude journalière, que vous soyez jeunes ou âgés, ",
  };
 
  // Milieu de phrase : obligation
  private static final String[] part2 = {
    "doit s'intégrer à la finalisation globale ",
    "oblige à la prise en compte encore plus effective ",
    "interpelle le citoyen que je suis et nous oblige tous à aller de l'avant dans la voie ",
    "a pour conséquence obligatoire l'urgente nécessité ",
    "conforte mon désir incontestable d'aller dans le sens ",
    "doit nous amener au choix réellement impératif ",
    "doit prendre en compte les préoccupations de la population de base dans l'élaboration ",
    "entraîne une mission somme toute des plus exaltantes pour moi : l'élaboration ",
  };
 
  // Fin de phrase : distraction
  private static final String[] part3 = {
    "d'un processus allant vers plus d'égalité. ",
    "d'un avenir s'orientant vers plus de progrès et plus de justice. ",
    "d'une restructuration dans laquelle chacun pourra enfin retrouver sa dignité. ",
    "d'une valorisation sans concession de nos caractères spécifiques. ",
    "d'un plan correspondant véritablement aux exigences légitimes de chacun. ",
    "de solutions rapides correspondant aux grands axes sociaux prioritaires. ",
    "d'un programme plus humain, plus fraternel et plus juste. ",
    "d'un projet porteur de véritables espoirs, notamment pour les plus démunis. ",
  };
 
  private boolean[] done0; // tableau des morceaux déjà utilisés pour le cas ou jeMeFicheDuPublic est faux
  private boolean[] done1; // tableau des morceaux déjà utilisés pour le cas ou jeMeFicheDuPublic est faux
  private boolean[] done2; // tableau des morceaux déjà utilisés pour le cas ou jeMeFicheDuPublic est faux
  private boolean[] done3; // tableau des morceaux déjà utilisés pour le cas ou jeMeFicheDuPublic est faux
  private int max; // Nombre maximal de phrase pour le cas ou jeMeFicheDuPublic est faux
  private Random random;
 
  // Construction du générateur de bars à thym
  public Nahko() {
    done0 = new boolean[part0.length];
    done1 = new boolean[part1.length];
    done2 = new boolean[part2.length];
    done3 = new boolean[part3.length];
    max = Math.min(Math.min(part0.length, part1.length), Math.min(part2.length, part3.length));
    random = new Random();
  }
 
  // Initialisation des tables de morceaux déjà utilisés
  private void init() {
    for (int i = 0 ; i < done0.length ; i++)
      done0[i] = false;
    for (int i = 0 ; i < done1.length ; i++)
      done1[i] = false;
    for (int i = 0 ; i < done2.length ; i++)
      done2[i] = false;
    for (int i = 0 ; i < done3.length ; i++)
      done3[i] = false;
  }
 
  // Discours maximal sans répétition, pour s'entrainer à faire comprendre le besoin plus que nécessaire de prendre les mesures appropriées qui, même si elles semblent catastrophiques de prime abord, n'en restent pas moins nécessaires et nous permettront dans un temps limité d'atteindre nos objectifs. 
  public String viteUnDiscours() {
    return viteUnDiscours(max, false);
  }
 
  // Discours de longueur variable avec probables répétitions mais qui, si les circonstances le permettent et que le soleil est au beau fixe devrait nous permettre de nous permettre de toucher un public dont la largeur n'a d'égal que la quantité d'individus le composant.
  public String viteUnDiscours(int longueur) {
    return viteUnDiscours(max, true);
  }
 
  // Construction du discours. Si jeMeFicheDuPublic est faux, le discours évitera les répétitions et sera limité à max phrases, ce qui dans la conjoncture actuelle peut s'&vérer délicat et nécessite de fait la mise en place rapide des variables appropriées dans le cadre imposé.
  public String viteUnDiscours(int longueur, boolean jeMeFicheDuPublic) {
    int c = longueur;
    if (!jeMeFicheDuPublic) {
      init();
      c = Math.min(longueur, max);
    }
    String s = "\n" + faisMaPresentation();
    for (int i = 1 ; i < c ; i++)
      s += "\n" + faisUnePhrase(jeMeFicheDuPublic);
    return s + "\n";
  }
 
  // Construction de la première phrase du discours
  private String faisMaPresentation() {
    String s = "      " + part0[0] + "      ";
    done0[0] = true;
    int c = random.nextInt(part1.length);
    s += "\n      " + part1[c] + "      ";
    done1[c] = true;
    c = random.nextInt(part2.length);
    s += "\n      " + part2[c] + "      ";
    done2[c] = true;
    c = random.nextInt(part3.length);
    s += "\n      " + part3[c] + "      ";
    done3[c] = true;
    return s;
  }
 
  // Construction d'une phrase quelconque du discours
  private String faisUnePhrase(boolean jeMeFicheDuPublic) {
    String s = "";
    int c = random.nextInt(done0.length);
    while ((done0[c]) && (!jeMeFicheDuPublic))
      c = random.nextInt(done0.length);
    s += "\n      " + part0[c] + "      ";
    done0[c] = true;
    c = random.nextInt(done1.length);
    while ((done1[c]) && (!jeMeFicheDuPublic))
      c = random.nextInt(done1.length);
    s += "\n      " + part1[c] + "      ";
    done1[c] = true;
    c = random.nextInt(done2.length);
    while ((done2[c]) && (!jeMeFicheDuPublic))
      c = random.nextInt(done2.length);
    s += "\n      " + part2[c] + "      ";
    done2[c] = true;
    c = random.nextInt(done3.length);
    while ((done3[c]) && (!jeMeFicheDuPublic))
      c = random.nextInt(done3.length);
    s += "\n      " + part3[c] + "      ";
    done3[c] = true;
    return s;
  }
 
  // Tests, exemples d'utilisation
  public static void main(String[] args) {
    Nahko nahko = new Nahko();
    JFrame frm = new JFrame("2007 Sylvain Tournois - http://sylv.tournois.free.fr/");
    frm.setDefaultCloseOperation(frm.EXIT_ON_CLOSE);
    JTextArea text = new JTextArea(nahko.viteUnDiscours());
//    JTextArea text = new JTextArea(nahko.viteUnDiscours(10, true));
    frm.getContentPane().add(new JScrollPane(text));
    frm.pack();
    frm.setVisible(true);
  }
 
}
Pour le voir en action, cliquez ici.
__________________
__________________________________
| +
| Sylvain Tournois - Création logicielle.
|
| http://www.anadoncamille.com/
|
anadoncamille est déconnecté   Envoyer un message privé 00
Vieux 21/11/2007, 07h05   #77
broumbroum
Membre éclairé
 
Avatar de broumbroum
 
Inscription : août 2006
Messages : 406
Détails du profil
Informations personnelles :
Âge : 29

Informations forums :
Inscription : août 2006
Messages : 406
Points : 383
Points : 383
Par défaut Modèle pour Java2D animé et interactif

Cette classe de Model peut s'utiliser dans un environnement ludique afin de maîtriser l'interactivité avec l'utilisateur pour diriger une série d'animation correspondant à un objet quelconque du jeu. Il répond aux actions clavier définies par une touche ou une séquence de touche lesquelles seront liées à une Map d'identifiant pour chaque Animation du modèle.
Elle s'intègre facilement en tant que Composant Swing ou en rendu direct (active rendering).
Code :
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
 
class Scene extends JFrame {
static { // ici un model avec 3 animations que l'on trouvera par 
// monModel/XXXXX.png (XXXXX remplacé par le numéro de l'image 
// compris entre les accolades, 2 entiers pour donner l'intervalle) 
// et un son d'effet que l'on trouvera par sfx/leNomDeFichierSonore
          JComponent model = new InteractiveModel("monModel",
                HIGH,
                30,
                new Dimension(576,230),
                new Dimension(85, 105),
                new int[][] {
                      {19457,19461},{19472,19479}, {19488,19505}
                },
                new String[]{
                       "intro", "stance", "jump forwards", "forwards", 
                       "forwards LP", "forwards MP", "forwards HP",
                       "forwards LK", "forwards MK", "forwards HK", 
                        "jump forwards LK"
                },
                new String[]{"monSoundFX.wav"}
                );
// il est nécessaire de spécifier l'attribut player comme ceci pour identifier
// les touches correspondantes (voir la classe Fighter.java en mode statique 
// encore en cours de prog.)
model.setAttribute("player", "ONE");
       // deuxièmement, la chose TRES IMPORTANTE A SPECIFIER pour le 
// modèle interactif est le temps alloué à l'utilisateur pour donner une 
// séquence entière détectable par les Timer's. Tous les timings sont
// spécifiés en MILLISECONDES SVP. On ajoute donc un mapping "blanc"
// de 3 sec. généralement, selon la longeurs des séquences (par ex. une 
// séquence avec une pression de 2 sec. puis une combinaisons de touches 
// aura besoin de 2 sec au minimum pour être détectée.)
        model.addKeyEventWrapperMapping(new KeyEventWrapper(-1, -1, 3000), "");
        // pour faire le lien entre Animation et identifiant voici la méthode, 
// l'entier correspond à l'indice du tableau spécifié dans le constructeur du 
// modèle
        model.addAnimMap("intro", 0);
        model.addAnimMap("stance", 1);
        model.addAnimMap("forwards", 2);
        // ensuite, pour activer les touches clavier, ajouter un mapping 
// avec le code KeyEvent.VK_XXXX de la touche correspondante
        model.addKeyEventWrapperMapping(new KeyEventWrapper(keyCodeMap.get(model.getAttribute("player") + "-forwards"), 
              KeyEvent.KEY_PRESSED), "forwards");
        // finalement, pour mapper une séquence de touches, la classe 
// KeyEventWrapper permet de spécifier la séquence EXACTE des touches 
// concernées avec le timing souhaité (ceci doit être encore évalué, car les 
// tests viennent de débuter :))
model.addAnimMap("forwards LP", 41); // pour l'animation 41, ici fictive
        seq = new Vector<KeyEventWrapper>();
        seq.add(new KeyEventWrapper(keyCodeMap.get(model.getAttribute("player") + "-forwards"),
              KeyEvent.KEY_PRESSED));
        seq.add(new KeyEventWrapper(keyCodeMap.get(model.getAttribute("player") + "-LP"), KeyEvent.KEY_PRESSED));
        model.addKeyEventWrapperMapping(new KeyEventWrapper(seq), "forwards LP");
        // ajoutons le son et puis ensuite, lorsque le model retournera "intro" 
// comme animation courante, le son indexé en 0 sera chargé lorsque 
// l'animation commencera (pour l'instant cette impl. est désactivée)
        model.addSoundMap("intro", 0);
// le CHARGEMENT est totalement sécurisé en mémoire "dure" c'est-à-dire 
// que les animations et leurs sprites sont chargées en cache et chargées en 
// mémoire RAM au fur et à mesure des requêtes utilisateur. il faut donc 
// protéger le rendu par un appel à (Model).isLoaded() pour ne pas faire 
// interférence au chargement du modèle. Il est à noter que le modèle peut 
// être exporté ((Model).exportModel()) en fichier et réimporté ((Model).exportModel()) ultérieurement pour un chargement 
// décuplé, mais l'appel à (Model).loadResource() est obligatoire pour le 
// chargement en mémoire cache. La limite de mémoire Heap n'a ainsi plus lieu 
// d'etre pour la totalité du modèle, bien que si les dimensions d'affichage 
// sont trop démesurées, Java peut tomber en erreur.
        model.loadResource();
// l'ultime pré-requis est l'affectation du modèle au gestionnaire clavier 
// courant                             
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(model);
        }
// (constructeur de votre composant de rendu, etc.)
 
// ici la méthode du rendu de la scene est donc surchargée avec les entrées 
// du modèle, ceci se fait plus ou mois aisément en 3-4 lignes
public void paintComponent(Graphics g) {
            boolean complete = true;
            Graphics2D g2 = (Graphics2D)g;
            if (model.isLoaded()) {
                 character.setDisplaySize(new Dimension((int)largeur, (int)hauteur));
                // processKeyEventsStack() est la méthode issue de 
                // l'interactivité recherchée
                character.processKeyEventsStack();
                Point pos = new Point(0,0);
                model.setTransformEnabled(true);
                model.setFlipEnabled(true, Animation.HORIZONTAL);
                // le rendu peut se spécialiser avec un effet d'ombre ou de reflet 
                // assez sympa en switchant les deux derniers arguments de la 
                // méthode draw() ((ImageObserver)obs, (Graphics2D)g2, 
                // (int)x, (int)y, (boolean)reflet, (boolean)ombre) façon Street 
                // Fighter MUGEN 8O
                complete = complete && model.draw((Component)this, g2, pos.x, pos.y, false, true);
                if(complete)
                       System.out.println("le model " + model + " est chargé et a été rendu correctement.");
            } else
                System.out.println("le model " + model + " n'est pas encore chargé en mémoire .");
}
}
NOTE: les valeurs statiques peuvent être modifiées dans les classes SpritesChar.java et Fighter.java pour l'instant en cours de finalisation (surtout la dernière, car elle ne gère pas le déplacement sur l'écran du modèle à l'heure où je publie ce post, donc voilà voilà.... )
Fichiers attachés
Type de fichier : zip model-src.zip (59,2 Ko, 16 affichages)
broumbroum est déconnecté   Envoyer un message privé 00
Vieux 14/02/2008, 16h33   #78
dingoth
Membre Expert
 
Inscription : mai 2004
Messages : 1 253
Détails du profil
Informations personnelles :
Localisation : Belgique

Informations forums :
Inscription : mai 2004
Messages : 1 253
Points : 1 298
Points : 1 298
Par défaut Comparaison de noms de fichiers

Il est souvent demandé d'avoir un tri de fichier en ordre naturel plutôt qu'alphanumérique. On les trie donc généralement en faisant file1.compareTo(file2), ce qui les trie de manière alphanumérique :
Code :
1
2
3
4
5
6
7
8
9
10
11
fichier1.txt
fichier10.txt
fichier11.txt
fichier2.txt
fichier3.txt
fichier4.txt
fichier5.txt
fichier6.txt
fichier7.txt
fichier8.txt
fichier9.txt
Or on souhaite avoir la liste suivante :
Code :
1
2
3
4
5
6
7
8
9
10
11
fichier1.txt
fichier2.txt
fichier3.txt
fichier4.txt
fichier5.txt
fichier6.txt
fichier7.txt
fichier8.txt
fichier9.txt
fichier10.txt
fichier11.txt
Cette classe est un comparateur qui le permet :
Code :
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
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
 
public class FileNameWithNumberComparator
		implements Comparator<File> {
	public int compare(File file1, File file2) {
		String fileName1 = file1.getName();
		String fileName2 = file2.getName();
 
		int i1 = 0;
		int i2 = 0;
		Character c1, c2;
		String sub1, sub2;
		// Pour chaque caractère,
		while (i1 < fileName1.length() && i2 < fileName2.length()) {
			c1 = fileName1.charAt(i1);
			c2 = fileName2.charAt(i2);
			// si c'est un chiffre,
			if (Character.isDigit(c1) && Character.isDigit(c2)) {
				// on lit tout le nombre qui suit
				sub1 = readNumber(fileName1, i1);
				sub2 = readNumber(fileName2, i2);
				// On compare ces deux nombres
				int c = Integer.parseInt(sub1) - Integer.parseInt(sub2);
				// S'ils ne sont pas identiques, on renvoie la réponse appropriée
				if (c != 0)
					return c;
				// s'ils ont une notation différente, on repasse en comparaison alphanumérique.
				if (!sub1.equals(sub2)) {
					return sub1.compareTo(sub2);
				}
 
				i1 += sub1.length();
				i2 += sub2.length(); // sub1.length peut être différent de sub1.length. 
			} else {
				// sinon, on repasse en comparaison standard.
				int c = c1.compareTo(c2);
				// Si File001.xml == file001.xml, décommenter la ligne suivante
				// et commenter la précédente
				// int c = c1.toUpperCase().compareTo(c2.toUpperCase());
				if (c != 0)
					return c;
				i1++;
				i2++;
			}
		}
		// en cas d'égalité, le plus court passe devant.
		return (fileName1.length() - i1) - (fileName2.length() - i2);
	}
 
	private static String readNumber(String fileName, int offset) {
		for (int i = offset + 1; i < fileName.length(); i++) {
			if (!Character.isDigit(fileName.charAt(i))) {
				return fileName.substring(offset, i);
			}
		}
		return fileName.substring(offset);
	}
 
	public static void main(String... args) {
		HashSet<File> files = new HashSet<File>();
		for (int i = 1; i < 50; i++) {
			files.add(new File(i + ".xml"));
		}
 
		for (int i = 1; i < 50; i++) {
			files.add(new File("toto"+(i < 10 ? "0" : "") + i+".xml"));
		}
 
		for (int i = 1; i < 50; i++) {
			files.add(new File("tata"+i+".xml"));
		}
 
		for (int i = 1; i < 50; i++) {
			files.add(new File("toto0"+(i < 10 ? "0" : "") + i+".xml"));
		}
 
 
		ArrayList<File> orderedFiles = new ArrayList<File>(files);
 
		System.out.println("unordered files:");
		for (File fileName : orderedFiles) {
			System.out.println(fileName.getName());
		}
 
		Collections.sort(orderedFiles, new FileNameWithNumberComparator());
 
		System.out.println("Ordered files:");
		for (File fileName : orderedFiles) {
			System.out.println(fileName.getName());
		}
	}
}
Il reste quelques rares cas à gérer (comme toto01.test.xml < toto1.dev.xml alors qu'on préférerait sans doute toto1.dev.xml < toto01.test.xml), mais elle fait déjà la plupart des cas possibles. Si ce code ferait mieux d'aller en sources, je l'y placerai.
dingoth est déconnecté   Envoyer un message privé 00
Vieux 05/03/2008, 12h51   #79
Claythest
Membre éprouvé
 
Avatar de Claythest
 
Inscription : mai 2003
Messages : 550
Détails du profil
Informations forums :
Inscription : mai 2003
Messages : 550
Points : 465
Points : 465
Par défaut ComponentSplitPane

Bonjour,

Une petite contribution sans prétention : un JSplitPane avec pour "splitteur" un JComponent. Vous pouvez donc mettre pour "splitteur" n'importe quel composant graphique de votre choix, comme un JLabel par exemple.

Combiné avec un "setBorder(BorderFactory.createEmptyBorder());" sur le JSplitPane, cela donne un rendu pas mal...

Si vous avez des remarques, n'hésitez pas

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package componentsplit;
 
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JSplitPane;
 
/**
 *
 * @author Claythest
 */
public class ComponentSplitPane extends JSplitPane {
 
    public ComponentSplitPane(JComponent component) {
        setUI(new ComponentSplitPaneUI(component));
    }
}
Code :
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
package componentsplit;
 
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicSplitPaneDivider;
import javax.swing.plaf.basic.BasicSplitPaneUI;
 
/**
 *
 * @author Claythest
 */
public class ComponentSplitPaneUI extends BasicSplitPaneUI {
 
    private JComponent component;
 
    /**
     * Creates a new instance of ComponentSplitPaneUI
     */
    public ComponentSplitPaneUI(JComponent component) {
        super();
        this.component = component;
    }
 
    /**
     * Creates the default divider.
     */
    @Override
    public BasicSplitPaneDivider createDefaultDivider() {
        return new ComponentSplitPaneDivider(this, component);
    }
}
Code :
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
package componentsplit;
 
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComponent;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicSplitPaneDivider;
import javax.swing.plaf.basic.BasicSplitPaneUI;
 
/**
 *
 * @author  Claythest
 */
public class ComponentSplitPaneDivider extends BasicSplitPaneDivider {
 
    private JComponent component;
 
    /**
     * Creates a new ComponentSplitPaneDivider
     */
    public ComponentSplitPaneDivider(BasicSplitPaneUI ui, JComponent component) {
        super(ui);
        this.component = component;
        setLayout(new GridBagLayout());
        GridBagConstraints gbd = new GridBagConstraints();
        gbd.weightx = 1.0;
        gbd.weighty = 0.0;
        gbd.fill = GridBagConstraints.HORIZONTAL;
        gbd.gridwidth = GridBagConstraints.REMAINDER;
        gbd.gridheight = 1;
        add(component, gbd);
    }
 
    @Override
    public Dimension getMaximumSize() {
        return getPreferredSize();
    }
 
    @Override
    public Dimension getMinimumSize() {
        return getPreferredSize();
    }
 
    @Override
    public Dimension getPreferredSize() {
        return component.getPreferredSize();
    }
 
    @Override
    public void setBorder(Border border) {
    }
}
Fichiers attachés
Type de fichier : java ComponentSplitPane.java (336 octets, 2 affichages)
Type de fichier : java ComponentSplitPaneUI.java (696 octets, 2 affichages)
Type de fichier : java ComponentSplitPaneDivider.java (1,4 Ko, 2 affichages)
Claythest est déconnecté   Envoyer un message privé 00
Vieux 06/03/2008, 16h53   #80
millie
Rédacteur/Modérateur
 
Avatar de millie
 
Inscription : juin 2006
Messages : 6 935
Détails du profil
Informations personnelles :
Localisation : Luxembourg

Informations forums :
Inscription : juin 2006
Messages : 6 935
Points : 9 062
Points : 9 062
Comment créer un dossier temporaire en Java

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	public static File getTempFolder(String prefix, String suffix) throws IOException {
		do {
		File temp = File.createTempFile(prefix, suffix, directory);
 
		if(!temp.delete())
			throw new IOException("Erreur suppression fichier temporaire");
 
		folder = new File(temp.getAbsolutePath());
 
		}
		while(folder==null || !folder.mkdir());
 
		return folder;
	}
J'ai utilisé une technique bourrine qui consite à créer un fichier temporaire, à choper son nom, à le supprimer et à créer un dossier de ce même nom.
__________________
Je ne répondrai à aucune question technique en privé
millie est déconnecté   Envoyer un message privé 00
Discussion fermée Actualité déjà publiée
Outils de la discussion

Navigation rapide


Fuseau horaire GMT +2. Il est actuellement 18h48.


 
 
 
 
Partenaires

Hébergement Web