Author: tchemit Date: 2008-07-25 21:38:49 +0000 (Fri, 25 Jul 2008) New Revision: 915 Added: trunk/commandline/commandline-core/src/main/java/org/codelutin/option/ContextProvider.java Log: introduce ContextProvider which lookup for the commandline unique context as service (using java ServiceLoader mecanism). in that way we can use the context in some module which does not known the Context real implementation. Added: trunk/commandline/commandline-core/src/main/java/org/codelutin/option/ContextProvider.java =================================================================== --- trunk/commandline/commandline-core/src/main/java/org/codelutin/option/ContextProvider.java (rev 0) +++ trunk/commandline/commandline-core/src/main/java/org/codelutin/option/ContextProvider.java 2008-07-25 21:38:49 UTC (rev 915) @@ -0,0 +1,58 @@ +/** + * # #% Copyright (C) 2008 Code Lutin, Tony Chemit + * This program is free software; you + * can redistribute it and/or modify it under the terms of the GNU General + * Public License as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. This program is + * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU General Public License for more details. You + * should have received a copy of the GNU General Public License along with this + * program; if not, write to the Free Software Foundation, Inc., 59 Temple Place + * - Suite 330, Boston, MA 02111-1307, USA. + * # #% + */ +package org.codelutin.option; + +import java.util.Iterator; +import java.util.ServiceLoader; + +/** + * Cette classe permet de trouver dynamiquement le contexte Commandline en utilisant le + * m�canisme java de {@link java.util.ServiceLoader}. + * <p/> + * Le contexte trouv� lors du premier appel � la m�thode {@link #getContext()} est cach�� dans le champ {@link #context}. + * <p/> + * Il est possible de supprimer un context charg� via la m�thode {@link #reset()}. + * <p/> + * <b>Note : Attention, un seul contexte commandline peut �tre d�fini.</b> + * + * @author chemit + */ +public class ContextProvider { + /** + * share instance of the context + */ + private static Context context; + + public static synchronized Context getContext() { + if (context == null) { + ServiceLoader<Context> loader = ServiceLoader.load(Context.class); + Iterator<Context> iterator = loader.iterator(); + if (!iterator.hasNext()) { + throw new IllegalStateException("could not find a " + Context.class + " service"); + } + context = iterator.next(); + if (iterator.hasNext()) { + // not authorized! + reset(); + throw new IllegalStateException("only one " + Context.class + " service can be defined in classpath"); + } + } + return context; + } + + public static void reset() { + context = null; + } +}