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

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

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

Page Sources Java libres - participez ici [Sources]


Sujet :

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

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite
    Avatar de thecaptain
    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Décembre 2003
    Messages
    919
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

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

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

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

    La classe (bon le code est pas méga-top ) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    import java.io.*;
    import java.util.*;
     
    public class WebPartDeployer
    {
    	public static void main(String[] args) throws Exception
    	{
    		//explication des paramètres
    		if (args.length != 2)
    		{
    			System.out.println("Utilisation :");
    			System.out.println("java -cp . WebPartDeployer nomDeWebPart.dll webConfig.config");
    			return;
    		}
     
    		String wp = args[0];
    		String wc = args[1];
    		File wpf = new File(wp);
    		File wcf = new File(wc);
     
    		//test l'existence du fichier
    		if (!wpf.exists())
    		{
    			throw new RuntimeException("Le fichier "+wpf.getAbsolutePath()+" n'existe pas !");
    		}
     
    		if (!wcf.exists())
    		{
    			throw new RuntimeException("Le fichier "+wcf.getAbsolutePath()+" n'existe pas !");
    		}
     
    		savePublicToken(wpf);
    		installWebPart(wpf, wcf);
     
    	}
     
    	private static String publicKeyToken;
    	private static void savePublicToken(File f) throws Exception
    	{
    		final String dataPath = "data.txt";
     
    		File d = new File(dataPath);
     
    		BufferedReader br = new BufferedReader(new FileReader(d));
    		StringBuffer sb = new StringBuffer();
    		String line;
     
    		while((line = br.readLine()) != null)
    		{
    			sb.append(line+"\n");
    		}
     
    		//récupération du public key token
    		String data = sb.toString();
    		int index = data.indexOf("PublicKeyToken=");
    		publicKeyToken = data.substring(index+15, index+31);
     
    		br.close();
    	}
     
    	private static void installWebPart(File wpf, File wcf) throws Exception
    	{
    		String nodeToAdd = getNode(wpf);
     
    		FileReader fr = new FileReader(wcf);
    		BufferedReader br = new BufferedReader(fr);
    		StringBuffer sb = new StringBuffer();
     
     
    		//lecture du fichier ligne par ligne
    		String line;
    		boolean isInLine = false;
    		boolean finished = false;
    		while ((line = br.readLine()) != null)
    		{
    			//on check si on rentre dans la balise
    			if (!isInLine)
    			{
    				if (line.indexOf("<SafeControls>") != -1)
    				{
    					isInLine = true;
    				}
    			}
    			else if (!finished)
    			{
    				if (line.indexOf("</SafeControls>") != -1)
    				{
    					finished = true;
    					sb.append(nodeToAdd+"\n");
    				}
    			}
     
    			sb.append(line+"\n");	
    		}
     
    		fr.close();
    		br.close();
     
    		//réécriture du fichier
    		FileWriter fw = new FileWriter(wcf);
    		PrintWriter pw = new PrintWriter(fw);
     
    		String[] lines = sb.toString().split("\n");
    		for (int i=0 ; i<lines.length ; i++)
    		{
    			pw.println(lines[i]);
    		}
     
    		fw.close();
    		pw.close();
    	}
     
    	private static String getNode(File wpf)
    	{
    		String name = getNameOnly(wpf);
    		return "<SafeControl Assembly=\""+name+", Version=1.0.0.0, Culture=neutral, PublicKeyToken="+publicKeyToken+"\" Namespace=\""+name+"\" TypeName=\"*\" Safe=\"True\" />";
    	}
     
    	private static String getNameOnly(File wpf)
    	{
    		String name = wpf.getName();
    		int id = name.lastIndexOf(".");
     
    		return name.substring(0, id);
    	}
    }
    pour l'utiliser, il faut le lauch.bat correspondant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @echo off
     
    SET assembly=WPSubscription
    SET config=web.config
     
    echo Enregistrement de %assembly% dans le GAC...
    "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -i %assembly%.dll
     
    echo.
    echo Enregistrement des donnees dans data.txt...
    "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" /l %assembly% > data.txt
     
    echo.
    echo Generation du fichier xml %assembly%.dll
    "C:\Program Files\Java\jdk1.5.0_07\bin\java" -cp "." WebPartDeployer %assembly%.dll %config%
    cmd
    Ensuite il suffit de remplacer les 2 ligne suivantes par
    - le nom de la webpart
    - l'url du web.config à modifier (pour enregistrer la webpart)
    SET assembly=WPSubscription
    SET config=web.config
    Il faut juste au préalable mettre le dll de la webpart dans le même dossier que le lauch.bat. D'autre part, l'utilisation de cette méthode nécessite d'avoir visual studio 2005 installé (ou du moins l'utilitaire gacutil). Vous l'aurez compris, c'est pour du windows only

    En espérant que ca serve à quelqun !

    @++
      0  0

  2. #2
    Membre éclairé
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Octobre 2005
    Messages
    244
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : Philippines

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

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

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    public final class Pair<A, B> {
     
    	private A aVal;
    	private B bVal;
     
    	public Pair ( A first, B second) {
    		aVal = first;
    		bVal = second;
    	}
     
    	public void setFirst(A first) {
    		aVal = first;
    	}
     
    	public void setSecond(B second) {
    		bVal = second;
    	}
     
    	public A getFirst() {
    		return aVal;
    	}
     
    	public B getSecond() {
    		return bVal;
    	}
     
            public boolean equals(Object o) {
                    if(o instanceof Pair) {
                       return (aVal.equals((Pair)o.getFirst()) && bVal.equals((Pair)o.getSecond());
                    } else return false;
    }

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

    La classe principale:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
     
    import java.util.WeakHashMap;
     
    public class ThreadDescriptor {
     
    	static WeakHashMap < Thread, ThreadLineInfo> map;
     
    	static {
    		map = new WeakHashMap < Thread, ThreadLineInfo>();
    	}
     
    	static final public void notify (Thread t, String s ) {
     
    		Exception e = new Exception();
    		StackTraceElement[] traces = e.getStackTrace();
     
    		if(traces.length > 1) {
    			StackTraceElement trace = traces[1];
    			map.put(t, new ThreadLineInfo(s, trace) );
    		}
     
    	}
     
     
    	static final public void notify ( String s ) {
    		notify(Thread.currentThread(), s);
    	}
     
    	static final public ThreadLineInfo getInfo(Thread t) {
    		if(!map.containsKey(t))
    			return null;
    		return map.get(t);
    	}
     
    	public ThreadDescriptor() {
    		super();
    	}
     
    }
    Et voici la classe "donnée"

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    public final class ThreadLineInfo {
     
    	String  comment		;
    	int 	line		;
    	String 	fileName	;
    	String 	className	;
    	String 	methodName	;
     
    	public String getClassName() {
    		return className;
    	}
     
    	public String getComment() {
    		return comment;
    	}
     
    	public String getFileName() {
    		return fileName;
    	}
     
    	public int getLine() {
    		return line;
    	}
     
    	public String getMethodName() {
    		return methodName;
    	}
     
    	protected ThreadLineInfo(String comment, StackTraceElement e) {
    		this.comment 	= comment;
    		this.line 		= e.getLineNumber();
    		this.fileName	= e.getFileName();
    		this.className	= e.getClassName();
    		this.methodName	= e.getMethodName();
    	}
     
    }
      0  0

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

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

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

      0  0

  4. #4
    Futur Membre du Club
    Profil pro
    Inscrit en
    Mars 2007
    Messages
    4
    Détails du profil
    Informations personnelles :
    Âge : 61
    Localisation : France

    Informations forums :
    Inscription : Mars 2007
    Messages : 4
    Par défaut Charger un fichier Excel dans une base Ms Access
    Bonjour,

    Je viens par le présent message remercier toutes les personnes qui ont répondu aux questions d’autres développeurs bloqués durant leur développement JAVA. Je m’initie actuellement à l’écriture de programme JAVA, et j’ai trouvé une aide précieuse sur ce site. Pour se faire, je viens déposer ma contribution pour les futurs développeurs JAVA.

    Mes principaux problèmes étaient de lire un fichier Excel pour enregistrer les données dans une base MS Access. De ce fait, j’ai rencontré un certain nombre de problèmes. Je vais lister des mots clés qui m’ont permis de trouver les informations requises sur le Net afin de faciliter la recherche.
    • Lecture / Connection / Déclaration / MS Access
    • Lecture / Connection / Déclaration / Fichier Excel grâce à « JexcelApi »
    • Formater les décimales avec une virgules / Remplacer un point par une virgule pour la décimale avec java.text.NumberFormat
    • Formater une date / Format date AAAA/MM/JJ / Format date yyyy/MM/dd avec java.text.DateFormat
    • Créer / Déclarer / une base MS Access dans ODBC sous Windows


    1. L’installation de « JexcelApi » :
      Après avoir récupérer le fichier sur le site http://jexcelapi.sourceforge.net/, créer un sous répertoire « jexcelapi » dans votre répertoire « Java ». Copier l’ensemble du fichier « .zip ». Ajouter le fichier « jxl.jar » avec son chemin complet dans votre CLASSPATH (Poste de travail => Avancé => Variable d’environnement => Variable système).

    2. Configuration d’ODBC sous Winsows :
      Tout d’abord, nous avons accès sur nos Pc à cet outil de la manière suivante : Démarrer => Paramètres => Panneau de configuration => Outil d’administration => Source de données ODBC.
      S’il vous manque des pilotes ODBC, vous devrez faire comme moi, les chercher sur le Net.

    3. Formater en fonction des paramètres régionaux de votre Pc :
      Suivant les cas, vous aurez besoin de transformer le point décimal par une virgule décimale, ajouter le symbole monétaire correspondant à votre pays, afficher une date dans un format spécifique ou un pourcentage. Vous trouverez de l’aide avec l’url http://java.sun.com/developer/TechTi...0/tt0411.html.

    Pour finir, je colle mon programme dans ce message afin de vous aider à comprendre les différentes classes. Certains diront qu’il est possible d’optimiser certaines commandes, alors je leur serai grès de bien vouloir préciser comment avec la reprise de mon code.

    Merci à tous pour votre lecture.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
     
    import java.io.File;
    import java.io.IOException;
     
    import jxl.Workbook;
    import jxl.Sheet;
    import jxl.Cell;
    import jxl.CellType;
    import jxl.DateCell;
    import jxl.LabelCell;
    import jxl.NumberCell;
     
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.SQLException;
    import java.sql.ResultSet;
    import java.sql.DriverManager;
     
    import java.util.Date;
    import java.util.Locale;
     
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
     
     
     
    public class T07_LectureExcel extends Frame implements ActionListener, WindowListener
    {
    	// ---------------------------------------
    	// Variable communes
    	// ---------------------------------------
     
    	TextArea TarTexte = new TextArea();	// La zone de TarTexte pour l'affichage
    	String StrgEdit = "";			// Zone de conservation d'affichage
    	Statement StatDB = null;		// Intentiation d'une commande sur la base
    	ResultSet RstQuery = null;		// Résultat d'une resquête SQL
    	String StrgQuery = "";			// Zone de commande SQL
    	int intRes = 0;				// Test ajout enregistrement
     
    	// Definition des formatages français
    	NumberFormat NumForDecimal = NumberFormat.getInstance(Locale.FRENCH);
     	NumberFormat NumForMonnaie = NumberFormat.getCurrencyInstance(Locale.FRENCH);
    	NumberFormat NumForPourcent = NumberFormat.getPercentInstance(Locale.FRENCH);
    	DateFormat dtfDevis = new SimpleDateFormat("yyyy/MM/dd");
     
    	//-----------------------------------------------------------------------
    	// Construction de la class EdText
    	// D‚finition et affichage de la boŒte de dialogue
    	//-----------------------------------------------------------------------
    	T07_LectureExcel()
    	{
    		// Titre de la fenêtre et zone de TarTexte
    		super("Liste de fichiers");
    		add("Center", TarTexte);
     
    		Locale loc = Locale.getDefault();
     
    		// Définition et affichage du système de menus
    		MenuBar mb = new MenuBar();
    		Menu ml = new Menu("Fichier");
    		mb.add(ml);
     
    		// Définition et affichage du système de sous menu du menu 01
    		MenuItem il1 = new MenuItem("Chargement Devis");
    		MenuItem il2 = new MenuItem("Quitter");
    		ml.add(il1);
    		ml.add(il2);
    		setMenuBar(mb);
     
    		il1.setActionCommand("Chargement");
    		il2.setActionCommand("Quitter");
     
    		il1.addActionListener(this);
    		il2.addActionListener(this);
     
    		// Taille par défaut de la Frame
    		setSize(600,350);
    	}
     
    	//-----------------------------------------------------------------------------
    	// Gestion de l'événement Case de fermeture
    	//-----------------------------------------------------------------------------
    	public void windowClosing(WindowEvent event)
    	{
    		System.exit(0);
    	}
    	public void windowClosed(WindowEvent event)
    	{
    	}
    	public void windowDeiconified(WindowEvent event)
    	{
    	}	
    	public void windowIconified(WindowEvent event)
    	{
    	}	
    	public void windowActivated(WindowEvent event)
    	{
    	}	
    	public void windowDeactivated(WindowEvent event)
    	{
    	}	
    	public void windowOpened(WindowEvent event)
    	{
    	}
     
    	//-----------------------------------------------------------------------------
    	// Capture des événements liés au systême de menus
    	//-----------------------------------------------------------------------------
    	public void actionPerformed(ActionEvent evt)
    	{
     
    		//-----------------------------------------------------------------------
    		// Commande Fichier => Chargement Devis
    		//-----------------------------------------------------------------------
    		if (evt.getActionCommand().equals("Chargement"))
    		{
    			FileDialog fichier = new FileDialog(this, "Ouvrir", FileDialog.LOAD);
    			fichier.show();
     
    			String StrgNom = fichier.getFile();
    			String StrgDir = fichier.getDirectory();
     
    			// ---------------------------------------			
    			// Affichage du Contenu du fichier.
    			// ---------------------------------------
    			try
    			{
    				// =====================================
    				// Ouverture de la base MS Access
    				// =====================================
     
    				// Chargement du pilote JDBC
    				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     
    				// URL de connexion
    				String StrgUrl = "jdbc:odbc:2007DB";
     
    				// Connexion
    				Connection ConDB = DriverManager.getConnection(StrgUrl);
     
    				// =====================================
    				// Ouverture du fichier Excel
    				// =====================================
     
    				Workbook WbFichier = Workbook.getWorkbook(new File(StrgDir+StrgNom));
     
    				// Ouverture de la première feuille, la seconde est 1, etc. 
    				Sheet ShtFeuille = WbFichier.getSheet(0); 
     
    				// *************************************
    				// **         TABLE DEVIS             **
    				// *************************************
     
    				// Récupération de la valeur d'une cellule
    				Cell cel01 = ShtFeuille.getCell("J4"); 		// Numéro de devis 
    				Cell cel02 = ShtFeuille.getCell("O2"); 		// Date du devis
    				Cell cel03 = ShtFeuille.getCell("C10"); 	// Nom du contact
    				Cell cel04 = ShtFeuille.getCell("C11"); 	// Nom de la société
    				Cell cel05 = ShtFeuille.getCell("C12"); 	// Adresse 1
    				Cell cel06 = ShtFeuille.getCell("C13"); 	// Adresse 2
    				Cell cel07 = ShtFeuille.getCell("Q9"); 		// Classe tarif
    				Cell cel08 = ShtFeuille.getCell("R9"); 		// Coefficient tarif
    				Cell cel09 = ShtFeuille.getCell("Q12"); 	// Nombre de mois gratuit
    				Cell cel10 = ShtFeuille.getCell("Q14"); 	// Durée du contrat
     
    				// Convertion de données
    				double DblNumDevis = 0;
    				String StrgNumDevis = "";
    				Date dtDevis = null;
    				String StrgNomContact = "";
    				String StrgNomSociete = "";
    				String StrgNomAdresse1 = "";
    				String StrgNomAdresse2 = "";
    				String StrgClasseTarif = "";
    				double dblCoefTarif = 0;
    				double dblNbMoisGratuit = 0;
    				double dblDureeContrat = 0;
     
    				// ---------------------------------
    				// Contrôle du format de la cellule
    				// ---------------------------------
     
    				// 01 - Vérifie si la valeur est un nombre
    				if (cel01.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel01; 
    					DblNumDevis = nc.getValue();
    					StrgNumDevis = "" + (int) DblNumDevis;
    				}
     
    				// 01 - Vérifie si la valeur est une chaîne
    				if (cel01.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel01; 
    					StrgNumDevis = lc.getString(); 
    				} 
     
    				// 02 - Vérifie si la valeur est un date 
    				if (cel02.getType() == CellType.DATE) 
    				{ 
    					DateCell dc = (DateCell) cel02; 
    					dtDevis = dc.getDate();
    				} 
     
    				// 03 - Vérifie si la valeur est une chaîne
    				//if (cel03.getType() != CellType.EMPTY) 
     
    				if (cel03.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel03; 
    					StrgNomContact = lc.getString(); 
    				}
     
    				// 04 - Vérifie si la valeur est une chaîne
    				if (cel04.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel04; 
    					StrgNomSociete = lc.getString(); 
    				}
     
    				// 05 - Vérifie si la valeur est une chaîne
    				if (cel05.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel05; 
    					StrgNomAdresse1 = lc.getString(); 
    				}
     
    				// 06 - Vérifie si la valeur est une chaîne
    				if (cel06.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel06; 
    					StrgNomAdresse2 = lc.getString(); 
    				}
     
    				// 07 - Vérifie si la valeur est une chaîne
    				if (cel07.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel07; 
    					StrgClasseTarif = lc.getString(); 
    				}
     
    				// 08 - Vérifie si la valeur est un nombre
    				if (cel08.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel08; 
    					dblCoefTarif = nc.getValue(); 
    				}
     
    				// 09 - Vérifie si la valeur est un nombre
    				if (cel09.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel09; 
    					dblNbMoisGratuit = nc.getValue(); 
    				}
     
    				// 10 - Vérifie si la valeur est un nombre
    				if (cel10.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel10; 
    					dblDureeContrat = nc.getValue(); 
    				}
     
    				// Affichage de la sélection dans l'éditeur
    				StrgEdit =	"*************************" + "\n" +
    						"**      TABLE DEVIS    **" + "\n" +
    						"*************************" + "\n" +
    						"Fichier                : " + StrgDir+StrgNom + "\n" +
    						"Numéro de devis        : " + StrgNumDevis + "\n" + 
    						"Date du devis          : " + dtfDevis.format(dtDevis) + "\n" +
    						"Contact                : " + StrgNomContact + "\n" + 
    						"Nom de la société      : " + StrgNomSociete + "\n" + 
    						"Ligne n°1 de l'adresse : " + StrgNomAdresse1 + "\n" + 
    						"Ligne n°2 de l'adresse : " + StrgNomAdresse2 + "\n" + 
    						"Classe tarif           : " + StrgClasseTarif + "\n" + 
    						"Coefficient tarif      : " + NumForDecimal.format(dblCoefTarif) + "\n" + 
    						"Nombre de mois gratuit : " + (int) dblNbMoisGratuit + "\n" + 
    						"Durée du contrat       : " + (int) dblDureeContrat + "\n\n";
    				TarTexte.setText(StrgEdit);
     
    				// Affichage de la requête dans l'éditeur
    				StrgEdit = StrgEdit +	"********************************" + "\n" +
    							"**  CONTROLE DU DEVIS  **" + "\n" +
    							"********************************" + "\n\n";
     
    				// Construction de la requête de selection
    				StrgQuery = "SELECT Devis.* FROM Devis WHERE Devis.NumDevis = '" + StrgNumDevis + "'";
    				StrgEdit = StrgEdit + StrgQuery + "\n\n";
     
    				// Contrôle d'existance du devis dans la table DEVIS
    				// -> Penser à déclarer les Field Summary pour utiliser certaines méthodes 
    				StatDB = ConDB.createStatement(	ResultSet.TYPE_SCROLL_INSENSITIVE, 
    								ResultSet.CONCUR_UPDATABLE );
    				RstQuery = StatDB.executeQuery(StrgQuery);
     
    				// Positionner le curseur en fin de sélection
    				RstQuery.last();
    				// Récupérer le nombre de lignes
    				int intRes = RstQuery.getRow();
    				// Re positionner le curseur au début de sélection
    				RstQuery.first();
     
    				// Test si un enregistrement est trouvé
    				if (intRes == 0)
    				{
    					// Initialisation du nouvel enregistrement dans la table DEVIS
    					StrgQuery = "INSERT INTO Devis VALUES ( '" + StrgNumDevis + "', " +
    										"'" + dtfDevis.format(dtDevis) + "', " +
    										"'" + StrgDir+StrgNom + "', " +
    										"'" + StrgNomContact + "', " +
    										"'" + StrgNomSociete + "', " + 
    										"'" + StrgNomAdresse1 + "', " + 
    										"'" + StrgNomAdresse2 + "', " + 
    										"'" + StrgClasseTarif + "', " + 
    										"'" + NumForDecimal.format(dblCoefTarif) + "', " +
    										"'" + (int) dblNbMoisGratuit + "', " + 
    										"'" + (int) dblDureeContrat + "', " + 
    										"'" + dtfDevis.format(new Date()) +
    										"', null, null)";										
    					StrgEdit = StrgEdit + StrgQuery + "\n\n";
     
    					// Enregistrement du nouvel enregistrement dans la table DEVIS
    					intRes = StatDB.executeUpdate(StrgQuery);
     
    					// Test si l'enregistrement a bien été enregistré
    					if (intRes == 1 )
    						StrgEdit = StrgEdit + "Nouveau devis '" + StrgNumDevis + "' crée dans la table DEVIS. \n\n";
    				}
    				else
    					StrgEdit = StrgEdit + "Le devis '" + StrgNumDevis + "' existe déjà dans la table DEVIS. \n\n";							
     
     
    				// Affichage de la requête dans l'éditeur
    				TarTexte.setText(StrgEdit);
     
    				// ---------------------------------------
    				// Fermeture du fichier
    				// ---------------------------------------
    				WbFichier.close();
    				ConDB.close();
    			}
     
    			// ---------------------------------------			
    			// Gestion des erreurs
    			// ---------------------------------------
    			catch(jxl.read.biff.BiffException biffE)
    			{ 
    				biffE.printStackTrace();
    				System.exit(1);
    			}
    			catch(IOException ioe)
    			{ 
    				ioe.printStackTrace();
    				System.exit(1);
    			}
    			catch(ClassNotFoundException cnfee) 
    			{
    				cnfee.printStackTrace();
    				System.exit(1);
    			}
    			catch(SQLException sqle) 
    			{
    				System.out.println("SQLException : " + sqle.getErrorCode());
    				switch (sqle.getErrorCode())
    				{
    					default :
    					{
    						sqle.printStackTrace();
    						System.exit(1);
    					}
    				}
    			}
     
    		}
     
    		//-----------------------------------------------------------------------
    		// Commande Fichier/Quitter
    		//-----------------------------------------------------------------------
    		if (evt.getActionCommand().equals("Quitter"))
    		{
    			System.exit(0);
    		}
    	}
     
    	//----------------------------------------------------------------------------------
    	// D‚finition d'une frame pour l'application et affichage de la
    	// boŒte de dialogue
    	//----------------------------------------------------------------------------------
    	public static void main(String args[])
    	{
    		T07_LectureExcel editer = new T07_LectureExcel();
    		editer.show();
    		editer.addWindowListener(editer);
    	}		
    }
      0  0

  5. #5
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Message de progression dans la console
    Voici une classe qui permet d'afficher la progression d'un travail à priori non graphique dans la console texte.

    L'avantage est la lisibilité du message, il tient et se rafraîchit sur une seule ligne, ça n'inonde pas la console et ça permet par exemple de trouver à quel pas un processus plante ou ralentit, ou de visualiser la progression d'un algorithme de compression ou de cryptage.

    Auteur : anadoncamille
    Merci à ®om

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
     
    import java.util.Date;
    import java.text.SimpleDateFormat;
    /*
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
     
    public class ProgressMessage {
     
      /* Une fonction qui affiche sur une ligne de console la progression d'une tâche.
       *
       * Elle s'utilise par exemple dans une boucle for ou dans tout processus qui 
       * contient un nombre d'étapes bien défini.
       *
       * Les messages sont en anglais, libre à vous de les modifier
       */
      public static void printPercent(float step, float stepsCount) {
        // Calcul du pourcentage de progression
        float step_1 = step + 1;
        int percent = Math.round(step_1 * 100 / stepsCount);
        // Si la tâche n'est pas encore finie, ne pas afficher 100%, mais s'arrêter à 99%
        if (percent >= 100)
          percent = 99;
        // Stockge du pourcentage
        String message = "" + percent + "%";
        // Si le pourcentage est inférieur à 10, ajouter un esapce devant
        if (percent < 10)
          message = " " + message; 
        if (step_1 >= stepsCount)
          // Si le boulot est fini, changer de message, afficher lengthfait que c'est fini
          message = "job done, " + (int)stepsCount + " steps.                                                     \n";
        else
          // Sinon, ajouter l'heure au message, puis le pas en cours et le nombre de pas
          message = message + " - " + getHour() + " - step " + (int)(step_1) + "/" + (int)stepsCount;
        // Ramener le curseur en début de ligne
        System.out.print("\r");
        // Si c'est le premier pas, afficher le message de début et retourner à la ligne
        if (step == 0)
          System.out.println("  " + getHour() + "  Starting job.");
        // Si c'est le dernier pas, afficher l'heure
        if (step_1 >= stepsCount)
          System.out.print("  " + getHour());
        // Afficher lengthmessage créé
        System.out.print("  Working : " + message);
      }
     
      // Une fonction très simple pour obtenir l'heure formattée sous forme de chaîne de caractères
      public static String getHour() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
      }
     
      // Exemple d'utilisation, une boucle infinie permet d'apprécier l'affichage de fin :)
      public static void main(String[] args) {
        int count = 9999;
        for (int i = 0 ; i < count ; i++) {
          /* Votre code ici, 
           * évitez les messages dans System.out
           */
          printPercent(i, count);
        }
        System.out.println("\n2007 Sylvain Tournois - http://sylv.tournois.free.fr/");
        System.out.println("\nPressez Ctrl-C pour terminer le programme.");
        while (true);
      }
     
    }
      0  0

  6. #6
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut ZIP / UNZIP simple, efficace
    Bonjour,

    Voici le code d'un zipper/dézippeur simple à utiliser, rapide et efficace.

    Auteur : anadoncamille

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
     
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.RandomAccessFile;
     
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;
     
    import java.util.zip.ZipOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
     
    /* Un (dé)compresseur simple d'utilisation, rapide et efficace.
     *
     * Deux méthodes principales :
     *
     * Deux méthodes principales : 
     *   - zip(String directory) // compresse un dossier dans un fichier de même nom
     *   - unzip(String file) // décompresse un fichier dans un dossier de même nom
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class Ziper {
     
      // Compresse le répertoire "monDossier" dans le fichier "monDossier.zip"
      public static void zip(String directory) {
        System.out.println("Archiving directory " + directory + " in file " + directory + ".zip :");
        try {
          FileOutputStream fos = new FileOutputStream(directory + ".zip");
          ZipOutputStream zos = new ZipOutputStream(fos);
          Vector entries = getFileList(directory, "*");
          int n = entries.size();
          String s;
          String s2;
          ZipEntry ze;
          RandomAccessFile raf = null;
          byte[] bb;
          int l = directory.length() + 1;
          for (int i = 0 ; i < n ; i++) {
            s = (String)entries.get(i);
            s2 = s.substring(l);
            raf = new RandomAccessFile(s, "r");
            bb = new byte[(int)raf.length()];
            raf.read(bb);
            ze = new ZipEntry(s2);
            zos.putNextEntry(ze);
            zos.write(bb);
            raf.close();
            printPercent(i, n);
          }
          zos.finish();
          System.out.println("\nArchiving done. Thank you for using me!");
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Décompresse le fichier "monFichier.zip" dan le répertoire "monFichier"
      public static void unzip(String file) {
        try {
          String directory = file.substring(0, file.lastIndexOf(".")) + "/";
          System.out.println("Extracting file " + file + " in directory " + directory + " :");
          ZipFile zf = new ZipFile(file);
          ZipEntry ze;
          Hashtable ht = new Hashtable();
          int nf = 0;
          Enumeration e = zf.entries();
          for ( ; e.hasMoreElements() ; ) {
            ze = (ZipEntry)e.nextElement();
            ht.put(ze.getName(), ze);
            nf++;
          }
          RandomAccessFile raf = new RandomAccessFile(file, "r");
          byte[] bb = new byte[(int)raf.length()];
          raf.read(bb);
          raf.close();
          ByteArrayInputStream bais = new ByteArrayInputStream(bb);
          ZipInputStream zis = new ZipInputStream(bais);
          ze = zis.getNextEntry();
          String s;
          int i;
          int n;
          int l;
          int n2 = 0;
          while (ze != null) {
            ze = (ZipEntry)ht.get(ze.getName());
            s = directory + ze.getName();
            bb = new byte[(int)ze.getSize()];
            i = 0;
            l = bb.length;
            while (l > 0) {
              n = zis.read(bb, i, l);
              i += n;
              l -= n;
            }
            createFile(s);
            raf = new RandomAccessFile(s, "rw");
            raf.write(bb);
            raf.close();
            ze = zis.getNextEntry();
            printPercent(n2, nf);
            n2++;
          }
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        System.out.println("\nExtracting done. Thank you for using me!");
      }
     
      // Crée un fichier vide de nom "monDossier/mesRubriques/monFichier.machin" et le chemin qui y mène
      public static void createFile(String fileName) {
        if (fileName.indexOf('/') > 0) {
          File f = new File(fileName.substring(0, fileName.lastIndexOf('/')));
          f.mkdirs();
        }
        File f = new File(fileName);
        try {
          FileWriter fw = new FileWriter(fileName, false);
          fw.close();
        }
        catch (Exception e) {
        }
      }
     
      // Transforme un nom de fichier "a\b\..\c\d.txt" en "a/c/d.txt"
      public static String reduceFileName(String s) {
        String s2 = s.replace('\\', '/');
        String[] words = s2.split("/");
        boolean[] ok = new boolean[words.length];
        for (int i = 0 ; i < words.length ; i++) 
          ok[i] = true;
        for (int i = words.length - 1 ; i >= 0 ; i--) {
          if (words[i].equals("..")) {
            int j = i - 1;
            while ((j >= 0) && ((words[j].equals("..")) || (!ok[j])))
              j--;
            if (j >= 0) {
              ok[i] = false;
              ok[j] = false;
            }
          }
        }
        s2 = "";
        for (int i = 0 ; i < words.length - 1 ; i++)
          if (ok[i])
            s2 += words[i] + "/";
        return s2 + words[words.length - 1];
      }
     
      // Affiche la progression de la (dé)compression
      public static void printPercent(float step, float stepsCount) {
        float step_1 = step + 1;
        int percent = Math.round(step_1 * 100 / stepsCount);
        if (percent >= 100)
          percent = 99;
        String message = "" + percent + "%";
        if (percent < 10)
          message = " " + message; 
        if (step_1 >= stepsCount)
          message = "job done, " + (int)stepsCount + " steps.                                                     \n";
        else
          message = message + " - " + getHour() + " - step " + (int)(step_1) + "/" + (int)stepsCount;
        System.out.print("\r");
        if (step == 0)
          System.out.println("  " + getHour() + "  Starting job.");
        if (step_1 >= stepsCount)
          System.out.print("  " + getHour());
        System.out.print("  Working : " + message);
      }
     
      // Renvoie l'heure dans une chaîne de caractères
      public static String getHour() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
      }
     
      // Renvoie la liste des fihiers "*.monExtension" contenus contenue dans l'arborescence "monDossier"
      public static Vector getFileList(String directory, String extension) {
        return getFileList(directory, "", extension);
      }
     
      // Renvoie la liste des fichiers "monDebut*.monExtension" contenus contenue dans l'arborescence "monDossier"
      public static Vector getFileList(String directory, String start, String extension) {
        Vector result = new Vector();
        File f = new File(directory);
        File[] list = f.listFiles(new DirFileFilter());
        if ((list != null) && (list.length != 0))
          for (int i = 0 ; i < list.length ; i++)
            result.addAll(getFileList(f.getPath() + "\\" + list[i].getName(), extension));
        list = f.listFiles(new GenFileFilter(start, extension));
        String n;
        if ((list != null) && (list.length != 0))
          for (int i = 0 ; i < list.length ; i++) {
            n = reduceFileName(f.getPath() + "\\" + list[i].getName());
            result.add(n);
          }
        return result;
      }
     
      // Cette classe sert à filtrer les répertoires dans les fichiers
      private static class DirFileFilter implements FileFilter {
     
        public DirFileFilter() {
        }
     
        public boolean accept(File f) {
          return f.isDirectory();
        }
     
      }
     
      // Une classe filtre générique, sélectionne les fichiers "monDebut*.monExtension"
      private static class GenFileFilter implements FileFilter {
     
        private String start;
        private String extension;
        private boolean allFiles;
        private boolean allExts;
     
        public GenFileFilter(String ext) {
          start = "";
          extension = new String(ext);
          extension = extension.toLowerCase();
          allExts = extension.equals("*");
          allFiles = allExts;
        }
     
        public GenFileFilter(String s, String ext) {
          start = new String(s);
          start = start.toLowerCase();
          extension = new String(ext);
          extension = extension.toLowerCase();
          allExts = extension.equals("*");
          allFiles = allExts && start.equals("*");
        }
     
        public boolean accept(File f) {
          if (!f.isFile())
            return false;
          if (allFiles)
            return true;
          String n = f.getName();
          if (n.length() < start.length())
            return false;
          n = n.toLowerCase();
          String tst = n.substring(0, start.length());
          if (!tst.equals(start))
            return false;
          if (allExts)
            return true;
          if (n.lastIndexOf(".") < 0)
            return false;
          tst = n.substring(n.lastIndexOf(".") + 1, n.length());
          return tst.equals(extension);
        }
     
      }
     
    }
      0  0

  7. #7
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Ajouter du mystère dans mon programme, Java
    Bonjour,

    Suite au post suivant http://www.developpez.net/forums/sho...36#post2361336 sur une façon d'ajouter du mystère dans un programme, voici un code qui montre différentes façon d'utiliser la classe Random du langage Java.

    L'application est une JFrame très simple qui affiche des codes et les résultats associés, 4 exemples de programmation autour de la classe Random.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
    /* Voici un code peu commenté mais fait pour montrer les potentiels et limites de 
     * la classe Random, fournisseuse de nombres pour Java.
     *
     * En faisant fonctionner ce programme, vous verrez les résultats produits par 
     * différentes utilisation de la classe Random.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class RandomDemo extends JFrame implements MouseMotionListener {
     
      // Affichage des résultats
      private void boucle() {
        long refreshDate = System.currentTimeMillis();
        Random cyclic = new Random(refreshDate);
        long x = new Random().nextLong();
        userData = refreshDate;
        while (true) {
          Random rand = new Random();
          Random dead = new Random(x);
          Random alive = new Random(userData);
          labels[NUMBER0].setText("r0 == " + cyclic.nextLong() + "\nr1 == " + cyclic.nextLong() + "\nr2 == " + cyclic.nextLong());
          labels[NUMBER1].setText("r0 == " + rand.nextLong() + "\nr1 == " + rand.nextLong() + "\nr2 == " + rand.nextLong());
          labels[NUMBER2].setText("x == " + x + "\nr0 == " + dead.nextLong() + "\nr1 == " + dead.nextLong() + "\nr2 == " + dead.nextLong());
          labels[NUMBER3].setText("y == " + userData + "\nr0 == " + alive.nextLong() + "\nr1 == " + alive.nextLong() + "\nr2 == " + alive.nextLong());
          if (System.currentTimeMillis() > refreshDate) {
            x++;
            refreshDate += 1111;
          }
        }
      }
     
      // Modification de la variable userData
      public void mouseMoved(MouseEvent mouseEvent) {
        userData += mouseEvent.getX() + mouseEvent.getY();
        System.out.println("Mouse moved");
      }
     
      // Modification de la variable userData
      public void mouseDragged(MouseEvent mouseEvent) {
        userData += mouseEvent.getX() * mouseEvent.getY();
        System.out.println("Mouse dragged");
      }
     
      // Point d'entrée Java
      public static void main(String[] args) {
        new RandomDemo();
      }
     
      private static final int NAME0 = 0;
      private static final int NAME1 = 2;
      private static final int NAME2 = 4;
      private static final int NAME3 = 6;
      private static final int NUMBER0 = 1;
      private static final int NUMBER1 = 3;
      private static final int NUMBER2 = 5;
      private static final int NUMBER3 = 7;
      private static final int LABELS_COUNT = 8;
      private static final String[] TEXTS = {
        "Random rand = new Random();\nwhile(true) {\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
        "while(true) {\n  Random rand = new Random();\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
        "while(true){\n  Random rand = new Random(x);\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
        "while(true){\n  y += userActions()\n  Random rand = new Random(y);\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
      };
     
      private JTextArea[] labels;
      private long userData;
     
      public RandomDemo() {
        super("Potentiel du Random et Random potentiel - 2007 Sylvain Tournois - http://sylv.tournois.free.fr/");
        System.out.println("Potentiel du Random et Random potentiel");
        System.out.println("\n Copyright 2007   Sylvain Tournois\n\n http://sylv.tournois.free.fr/\n");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            exit();
          }
        });
        setBounds(0, 0, 640, 480);
        setLayout(new GridLayout(LABELS_COUNT / 2, 4));
        labels = new JTextArea[LABELS_COUNT];
        for (int i = 0 ; i < LABELS_COUNT ; i++) {
          labels[i] = new JTextArea(TEXTS[i]);
          labels[i].addMouseMotionListener(this);
          add(labels[i]);
        }
        addMouseMotionListener(this);
        setVisible(true);
        requestFocus();
        boucle();
      }
     
      private void exit() {
        System.exit(0);
      }
     
    }
      0  0

  8. #8
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Sauver des images opaques JPG, PNG, GIF
    Pour faire des screen shots ou enregistrer des images rendues, voici un enregistreur d'images simple, bien commenté :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
     
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.File;
     
    /* Un simple  enregistreur d'images.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class ImageSaver {
     
      // Enregistre une image et indique si l'opération s'est bien déroulée
      public static boolean save(BufferedImage img, String s) {
        // si l'image n'a pas de contenu ou si le nom est vide, sortir en indiquant l'échec
        if ((img == null) || (s == null))
          return false;
        // récupère le format dans le nom : "png", "jpg" ou "gif"
        String format = s.substring(s.lastIndexOf(".") + 1).toUpperCase();
        // affiche un message dans la console
        System.out.print("Saving image " + s + " (" + format + ") : ");
        // Crée un objet fichier
        File file = new File(s);
        // Complète l'arborescence qui mène au fichier
        file.mkdirs();
        // Récupération d'exceptions
        try {
          // Ecriture du fichier, enregistrement de l'image
          ImageIO.write(img, format, file);
        }
        // En cas d'erreur
        catch (Exception e) {
          System.out.println("ERROR!");
          // Afficher le message de l'exception
          e.printStackTrace();
          // Sortir de la fonction en indiquant l'échec
          return false;
        }
        // On n'est pas sorti => pas d'erreur
        // Afficher le message de bon déroulement
        System.out.println("OK.");
        // Sortir de la fonction en indiquant la réussite
        return true;
      }
     
    }
      0  0

  9. #9
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Une JFrame qui enregistre son affichage
    Bonjour,

    voici une JFrame qui peut faire des impressions d'écran.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
     
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.imageio.*;
    import java.io.*;
     
    /* Une JFrame pour faire des screen shots
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class JFrameScreenShot extends JFrame implements KeyListener {
     
      // Configuration graphique de l'environnement de travail
      public static final GraphicsConfiguration DGC = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
     
      // Notre buffer de capture, de même taille que notre Frame
      private BufferedImage buffer;
      // Le fournisseur de services graphiques associé au buffer
      private Graphics2D graphics;
     
      public JFrameScreenShot(int width, int height) {
        // Crée la Frame
        super("test");
     
        // crée le buffer de la même taille que la fenêtre
        buffer = DGC.createCompatibleImage(width, height);
        // crée le fournisseur de services associé au buffer
        graphics = buffer.createGraphics();
     
        // Par défaut : on quitte l'application en fermant la fenêtre
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            exit();
          }
        });
     
        // Paramètres de position et taille de la fenêtre : 
        // position = 0, 0
        // taille = width X height
        setBounds(0, 0, width, height);
     
        // Afficher la fenêtre
        setVisible(true);
     
        // L'application est sensible au clavier
        addKeyListener(this);
     
        // Demande de focus (pour connecter au clavier)
        requestFocus();
      }
     
      private void exit() {
        System.exit(0);
      }
     
      // Point d'entrée Java
      public static void main(String[] args) {
        new JFrameScreenShot(640, 480);
      }
     
      // Cas de touche enfoncée
      public void keyPressed(KeyEvent keyEvent) {
      }
     
      // Cas de touche relâchée
      public void keyReleased(KeyEvent keyEvent) {
        // Capture de JFrame
        screenShot();
      }
     
      // Cas de caractère écrit
      public void keyTyped(KeyEvent keyEvent) {
      }
     
      // Capture de JFrame
      public void screenShot() {
        // Peint les composants de la JFrame dans le buffer
        paintAll(graphics);
        // Enregistre le buffer 
        save(buffer, "test.png");
      }
     
      // Enregistre une image
      public static boolean save(BufferedImage img, String s) {
        if ((img == null) || (s == null))
          return false;
        String format = s.substring(s.lastIndexOf(".") + 1).toUpperCase();
        System.out.print("Saving image " + s + " (" + format + ") : ");
        File file = new File(s);
        file.mkdirs();
        try {
          ImageIO.write(img, format, file);
        }
        catch (Exception e) {
          System.out.println("ERROR!");
          e.printStackTrace();
          return false;
        }
        System.out.println("OK.");
        return true;
      }
     
    }
      0  0

  10. #10
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Enregistrer des fichiers textes
    Voici une classe simple pour enregistrer des fichiers texte :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
     
    import java.io.File;
    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.util.Vector;
     
    /* Une classe pour écrire simplement des fichiers textes.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class TextFileWriter {
     
      private String fileName;
     
      // Crée un fichier en mode création
      public TextFileWriter(String fileName) {
        this(fileName, false);
      }
     
      // Crée un fichier en mode ajout o/n (si n, mode création)
      public TextFileWriter(String fileName, boolean append) {
        if (fileName.indexOf('/') > 0) {
          File f = new File(fileName.substring(0, fileName.lastIndexOf('/')));
          f.mkdirs();
        }
        this.fileName = new String(fileName);
        File f = new File(fileName);
        try {
          FileWriter fw = new FileWriter(fileName, append);
          fw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Ajoute une ligne
      public void addLine(String line) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
          bw.write(line);
          bw.newLine();
          bw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Ajoute plusieurs lignes
      public void addLines(Vector lines) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
          int n = lines.size();
          String s;
          for (int i = 0 ; i < n ; i++) {
            s = (String)lines.get(i);
            if (s != null) {
              bw.write(s);
              bw.newLine();
            }
          }
          bw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Ajoute plusieurs lignes
      public void addLines(String[] lines) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
          for (int i = 0 ; i < lines.length ; i++) {
            if (lines[i] != null) {
              bw.write(lines[i]);
              bw.newLine();
            }
          }
          bw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Exemples d'utilisation
      public static void main(String[] args) {
        TextFileWriter tfw = new TextFileWriter("test.txt");
        tfw.addLine("Coucou");
        tfw.addLine("\n Copyright 2007   Sylvain Tournois\n\n www.anadoncamille.com\n");
        Vector v = new Vector();
        v.add("Ceci est un test");
        v.add("pour la classe");
        v.add("TextFileWriter");
        tfw.addLines(v);
      }
     
    }
    Dans le projet commons-io de Jakarta, vous retrouvez la même fonctionnalité avec la méthode writeLines(File, List). (merci Napalm51)
      0  0

  11. #11
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    /* 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);
      }
     
    }
      0  0

  12. #12
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Générateur de BufferedImage
    Salut,

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

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    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);
      }
     
    }
      0  0

  13. #13
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
     
    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/");
      }
     
    }
      0  0

  14. #14
    Membre expérimenté
    Avatar de vahid
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    228
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 228
    Par défaut
    Fonction split en 1.3 (Java ME)
    Impossible de travailler sans

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
    	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;
    	}
      0  0

  15. #15
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    Par défaut Player midi
    Auteur : anadoncamille

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

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
     
    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");
      }
     
    }
      0  0

  16. #16
    Membre expérimenté
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Billets dans le blog
    1
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
     
    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;
        }
     
      }
     
    }
      0  0

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

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

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
     
    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();
            }
        }
     
    }
      0  0

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

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

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
     
    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.
      0  0

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

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

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
     
    /*
     * 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);
        }
    }
      0  0

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

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

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
     
    /*
     * 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;
    }
      0  0

Discussions similaires

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

Partager

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