begin process at 2012 02 09 09:59:10
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Api

 > JCONFIGURATIONMANAGER - GESTION DES CONFIGURATIONS

JCONFIGURATIONMANAGER - GESTION DES CONFIGURATIONS


 Information sur la source

Note :
Aucune note
Catégorie :Api Classé sous :fichier, configuration, xml Niveau :Débutant Date de création :31/10/2008 Vu :3 551

Auteur : Francks11

Ecrire un message privé
Commentaire sur cette source (1)
Ajouter un commentaire et/ou une note

 Description

Une classe qui permet de récupérer des paramètres de configuration à partir d'un fichier xml. Pour pouvoir utiliser cette classe, il faut également posséder la librairie jdom.

Voici un exemple de fichier de configuration :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<!-- Configuration générale -->
<section name="Workbook">
<entry key="DestinationFile" value="C:\\output.xls" />
<entry key="RowStart" value="0" />
<entry key="ColStart" value="0" />
<entry key="MonthColor" value="17" />
<entry key="SaturdayColor" value="34" />
<entry key="SundayColor" value="10" />
</section>

<!-- Police pour la case contenant le mois -->
<section name="Police1">
<entry key="Name" value="ARIAL" />
<entry key="Size" value="12" />
</section>

<!-- Police pour le reste du document -->
<section name="Police2">
<entry key="Name" value="ARIAL" />
<entry key="Size" value="10" />
</section>

</configuration>

Pour récupérer ces paramètres dans une application en utilisant cette classe, il est nécessaire tout d'abord d'effectuer l'initialisation :

-soit en utilisant la méthode Initialize sans paramètre. Par défaut, le fichier de configuration est recherché dans le dossier /META-INF/app.config.xml.

-soit en utilisant la méthode Initialize avec comme paramètre le chemin du fichier de configuration

Par la suite, pour récupérer les paramètres de configuration, il suffit d'utiliser :

JConfiguration.getValue("nomsection","nomcle")

Source

  • package jcm.JConfigurationManager;
  • import java.io.File;
  • import java.io.IOException;
  • import java.util.Enumeration;
  • import java.util.Hashtable;
  • import java.util.List;
  • import org.jdom.input.SAXBuilder;
  • import org.jdom.*;
  • public class JConfigurationManager
  • {
  • /**
  • * Collection which contains configuration
  • */
  • private static Hashtable<String,String> htConfiguration = new Hashtable<String,String>();
  • /**
  • * Path where the configuration file is searched
  • */
  • private static String filePath = "./META-INF/app.config.xml";
  • @SuppressWarnings("unchecked")
  • private static void loadConfiguration() throws Exception
  • {
  • SAXBuilder sxb = new SAXBuilder();
  • org.jdom.Document document;
  • Element root;
  • String key;
  • // build the document
  • document = sxb.build(new File(filePath));
  • // get root elements
  • root = document.getRootElement();
  • // for all childs whose name is section
  • for(Element e : (List<Element>)root.getChildren("section"))
  • {
  • // for all childs whose name is entry
  • for(Element e2 : (List<Element>)e.getChildren("entry"))
  • {
  • // build the key
  • key = String.format("%s.%s", e.getAttributeValue("name"), e2.getAttributeValue("key"));
  • // check if the key already exists
  • if(htConfiguration.containsKey(key))
  • {
  • throw new Exception(
  • String.format("JConfigurationManager : La clé %s existe déja!",key));
  • }
  • htConfiguration.put(key, e2.getAttributeValue("value"));
  • }
  • }
  • }
  • /**
  • * Initialize the configuration manager
  • * @throws Exception Throw an exception if the file doesn't exists or if the file doesn't can read
  • */
  • public static void Initialize() throws Exception
  • {
  • File f = new File(filePath);
  • // check that the file exists
  • if(!f.exists())
  • {
  • throw new IOException("JConfigurationManager : Le fichier app.config.xml est introuvable!");
  • }
  • if(!f.canRead())
  • {
  • throw new IOException("JConfigurationManager : Impossible de lire le fichier app.config.xml!");
  • }
  • // load the configuration
  • loadConfiguration();
  • }
  • /**
  • * Initialize the configuration manager
  • * @param fileName Exception Throw an exception if the file doesn't exists or if the file doesn't can read
  • */
  • public static void Initialize(String fileName) throws Exception
  • {
  • filePath = fileName;
  • Initialize();
  • }
  • /**
  • * Get a value from the section name and key name
  • * @param sectionName Name of the section
  • * @param key Name of the key
  • * @return The corresponding value
  • */
  • public static String getValue(String sectionName, String key)
  • {
  • return htConfiguration.get(String.format("%s.%s", sectionName,key));
  • }
  • /**
  • * Get a hash table from the section name
  • * @param sectionName Name of the section
  • * @return The corresponding hash table
  • */
  • public static Hashtable<String,String> getValues(String sectionName)
  • {
  • Hashtable<String,String> values = new Hashtable<String,String>();
  • String element;
  • for (Enumeration<String> e = htConfiguration.keys() ; e.hasMoreElements() ;)
  • {
  • element = e.nextElement();
  • // if the key contains the section name
  • if(element.substring(0,element.indexOf(".")).equals(sectionName))
  • {
  • // add the element to the list
  • values.put(element, htConfiguration.get(element));
  • }
  • }
  • return values;
  • }
  • }
package jcm.JConfigurationManager;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import org.jdom.input.SAXBuilder;
import org.jdom.*;

public class JConfigurationManager
{
	/**
	 * Collection which contains configuration
	 */
	private static Hashtable<String,String> htConfiguration = new Hashtable<String,String>();
	
	/**
	 * Path where the configuration file is searched
	 */
	private static String filePath = "./META-INF/app.config.xml";
	
	@SuppressWarnings("unchecked")
	private static void loadConfiguration() throws Exception
	{
		SAXBuilder sxb = new SAXBuilder();
		org.jdom.Document document;
		Element root;
		String key;
		
		// build the document
	    document = sxb.build(new File(filePath));
	    
	    // get root elements
	    root = document.getRootElement();
	    	    
	    // for all childs whose name is section
	    for(Element e : (List<Element>)root.getChildren("section"))
	    {	    	
	    	// for all childs whose name is entry
	    	for(Element e2 : (List<Element>)e.getChildren("entry"))
	    	{
	    		// build the key
	    		key = String.format("%s.%s", e.getAttributeValue("name"), e2.getAttributeValue("key"));
	    		
	    		// check if the key already exists
	    		if(htConfiguration.containsKey(key))
	    		{
	    			throw new Exception(
	    					String.format("JConfigurationManager : La clé %s existe déja!",key));
	    		}
	    		
	    		htConfiguration.put(key, e2.getAttributeValue("value"));
	    	}
	    }
	}
		
	/**
	 * Initialize the configuration manager
	 * @throws Exception Throw an exception if the file doesn't exists or if the file doesn't can read
	 */
	public static void Initialize() throws Exception
	{
		File f = new File(filePath);
		
		// check that the file exists
		if(!f.exists())
		{
			throw new IOException("JConfigurationManager : Le fichier app.config.xml est introuvable!");
		}
		
		if(!f.canRead())
		{
			throw new IOException("JConfigurationManager : Impossible de lire le fichier app.config.xml!");			
		}
		
		// load the configuration
		loadConfiguration();
	}
	
	/**
	 * Initialize the configuration manager
	 * @param fileName Exception Throw an exception if the file doesn't exists or if the file doesn't can read
	 */
	public static void Initialize(String fileName) throws Exception
	{
		filePath = fileName;
		Initialize();
	}
	
	/**
	 * Get a value from the section name and key name
	 * @param sectionName Name of the section
	 * @param key Name of the key
	 * @return The corresponding value
	 */
	public static String getValue(String sectionName, String key)
	{
		return htConfiguration.get(String.format("%s.%s", sectionName,key));
	}
	
	/**
	 * Get a hash table from the section name
	 * @param sectionName Name of the section
	 * @return The corresponding hash table
	 */
	public static Hashtable<String,String> getValues(String sectionName)
	{
		Hashtable<String,String> values = new Hashtable<String,String>();
		String element;
		
		for (Enumeration<String> e = htConfiguration.keys() ; e.hasMoreElements() ;)
		{
			element = e.nextElement();
			
			// if the key contains the section name
			if(element.substring(0,element.indexOf(".")).equals(sectionName))
			{
				// add the element to the list
		         values.put(element, htConfiguration.get(element));
			}
		}
		
		return values;
	}
}



 Sources de la même categorie

Source avec une capture AUTO FOLLOW/UNFOLLOW AVEC JTWITTER/OAUTHSIGNPOSTCLIENT ET SW... par GeroXXXX
Source avec Zip LOGICIEL MESSAGERIE par layeure
Source avec Zip Source avec une capture CRÉER DES GRAPHIQUES : UTILISATION DE JFREECHART par Julien39
EJB3-BEAN ENTITÉ : RELATIONS BIDIRECTIONNELLES par SoftDeath
Source avec Zip Source avec une capture LETMESEE : CAPTURE D'ÉCRAN À INTERVALLE RÉGULIER : UTILISATI... par pyo656

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture CRYPTEUR-DÉCRYPTEUR AES par dragooon74
Source avec Zip Source avec une capture PROGRAMME DE PARTAGE DE FICHIER EN RESEAUX par billatosco
DÉTERMINER LE CHEMIN D'UN FICHIER DANS UN RÉPERTOIRE DONNÉ par mFattoumi
Source avec Zip GESTION DE FICHIER DE CONFIGURATION .INI par tank22
Source avec Zip TRAITEMENT D'UN FICHIER XML par sky13

Commentaires et avis

Commentaire de EagleUnderscoreOne le 01/11/2008 11:37:13

Cool ta source, bien utile à  vrai dire.
Une idée d'amélioration peut être : Une classe qui crée une fenêtre qui permet de modifier les paramètres en s'adaptant au nombre et au nom des paramètres du fichier xml.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

charger des parmètres de configuration à partir d'un fichier XML [ par mnasri_riadh ] Salut,Je voudrais utiliser des param&#232;tres de configuration &#224; partir d'un fichier XML (lecture de noeuds et d'attributs).C'est &#224; dire, j configuration du fichier web.xml [ par naddou1985 ] bonjour tt le monde je veux executer une servlet et il me reste la configuration du fichier web.xml ,c'est la premiere fois que je travaille avec des Configuration de Maven avec testNG [ par mael974 ] Bonjour, je cherche a lancer mes testNG via maven. Jai configurer des groups au sein du fichier suite afin de lancer les tests uniquement sur ces gro Fichier XML-[Fatal Error] Content is not allowed in trailing section [ par kharachou ] Bonsoir, Je me permet de vous présenter mon problème,en fait j'ai réussi à envoyer un fichier xml depuis une application client vers un serveur en uli Problème Java / Hibernate [ par TorTukiTu ] Bonjour, Je vous écris car j'ai un bug très étrange : Je cherche simplement à utiliser Hibernate pour ma persistence. J'ai donc besoin d'utiliser un probléme avec jdom et xml [ par sny2009 ] salut, je veux modifier un élément dans un fichier xml ce fichier contient des étudiants quand je clique sur le bouton modifier tout les anciens info navigation avec netbeans [ par youssouffa ] Bonjour, Dans netbeans 6.9 sous Windows XP je ne trouve plus le fichier faces-config.xml qui permet de définir la navigation entre les pages par contr Manipuler un fichier XML [ par mizou1khane ] Bonjour tt le monde, Veuillez m'aidez sur ce truc dont j'ai passé plusieurs jours dedans, j'ai un fichier XML : <![CDATA[is ISC Hibernate/struts+webapplication+eclipse [ par langagec08 ] Bonjour tout le monde, je suis débutante en hibernate/struts et franchement je galère....tous les tutos que j'ai vu ne m'amène nul part...donc j'aimer liaison entre servlet et page html [ par mdh12 ] salut, mon but est gérer un statistique selon des donnes récupérer d'après un fichier .xml j'ai un code qui tourne et qui affiche un statistique sou


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2012
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
272829    

Consulter la suite du CalendriCode

Photothèque

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 3,884 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales