begin process at 2010 03 16 12:27:33
  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 :1 978

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 Zip Source avec une capture LETMESEE : CAPTURE D'ÉCRAN À INTERVALLE RÉGULIER : UTILISATI... par pyo656
ENVOI D'UNE ARBORESSENCE EN JAVA VERS SERVEUR FTP par moumou95
ENREGISTRER L'ARBORESCENCE D'UN JTREE DANS UN XML AVEC JDOM par coltman
Source avec Zip WIZARD JAVA API par aissam36
Source avec Zip Source avec une capture FRAGMENTER, DÉFRAGMENTER UN FICHIER par Chatbour

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture ZFS GESTION DU BOOTLOADER par 78.ultima
Source avec Zip JAVA SERVER PAGE par pasteure
Source avec Zip Source avec une capture IHM CONFIGURABLE POUR FICHIER PROPERTIES par benmor
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 Hibernate et HSQLDB [ par LordBob ] Bonsoir a tous, voila je me décide à poster un message car la je ne m'en sort pas trop bien avec Hibernate que je tente malgrès moi de découvrir. J'ut Fichier xml et service web [ par sche44 ] Bonjour,J'ai creé un service web sous myeclipse (xfire), ensuite j'ai ajouter un API a ce service, le problème c que cet API utilise un fichier xml po Statistiques sur fichiers XML [ par GoldPegaz ] Bonjour, Petite question (demande de piste de recherche) : Connaisser vous un moyen de générer des stats sur des fichier XML. J'ai plusieur fichier XM générer un fichier xml à aprtir d'une classe java [ par ajan ] Bonjour, je voualis savoir s'il existe une méthode simple pour générer un fichier xml à partir d'une classe java. Il y aurait dans ce fichier tous les chemin du fichier xml [ par breathfromhell ] salut tout le monde bah voila j ai un fichier xml je l ai nomme "connexion.xml" il contient qq information qui vont m etre util dans l instanciation d XSD à l'intérieur d'un fichier xml [ par DARKSIDIOUS ] Bonjour à tous,Est-ce qu'il est possible d'intégrer un xsd directement dans un fichier XML ? C'est-à-dire, est-ce qu'il est possible de stocker dans l parcourir un fichier xml [ par tarekcom ] Bonjour tout le monde   Voila mon fichier xml "stat.xml": &lt;? xml version < enregistrer un fichier xml sur le serveur en java [ par touirek ] dans le cadre de mon projet de fin d'étude, je me trouve avec le probleme suivant, j'ai un client en java qui a pour tâche de créer un fichier xml de


Nos sponsors


Sondage...

CalendriCode

Mars 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728
293031    

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 : 0,468 sec (3)

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