Jconfigurationmanager - gestion des configurations

Contenu du snippet

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 / Exemple :


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; } }

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.