[Buix-commits] r1408 - in jaxx/trunk: jaxx-swing-action/src/main/java/org jaxx-swing-action/src/main/java/org/nuiton jaxx-swing-action/src/main/java/org/nuiton/jaxx/action jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab jaxx-swing-action/src/main/java/org/nuiton/jaxx/util jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config jaxx-swing-action/src/test/java maven-jaxx-plugin/src/main/java/org maven-jaxx-plugin/src/main/java/org/nuiton maven-jaxx-plugin/src/main/java/org/nuiton/jaxx maven-jaxx-plugi
Author: tchemit Date: 2009-05-16 02:03:26 +0000 (Sat, 16 May 2009) New Revision: 1408 Added: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java Removed: jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java jaxx/trunk/jaxx-swing-action/src/test/java/jaxx/ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfig.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionNameProvider.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderAnnotation.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfig.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfig.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabContentConfig.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabFactory.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabModel.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIModel.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIProvider.java jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUI.java jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/TemplateGenerator.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1722Test.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1750Test.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1751Test.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/CompilerTest.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/CompilerValidatorTest.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/DecoratorTest.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/I18nTest.java jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/NodeItemTest.java Log: migrate to nuiton part 2 Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton (from rev 1405, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin) Property changes on: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton ___________________________________________________________________ Name: svn:mergeinfo + Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/AbstractActionConfigurationResolver.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,70 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import javax.swing.JComponent; - -/** - * Common abstract class of a resolver of action configuration. - * <p/> - * The class implements the logic of research of the configuration annotation. - * - * @author chemit - */ -public abstract class AbstractActionConfigurationResolver<A extends java.lang.annotation.Annotation, C extends JComponent> implements ActionConfigurationResolver<A, C> { - - /** the type of configuration's annotation */ - protected final Class<A> annotationImpl; - - /** the type of component that can fire an action */ - protected final Class<C> componentImpl; - - /** - * The typed method (on component) to apply configuration on the action and component. - * - * @param component the component which fires the action - * @param action the given action - * @return the configuration's annotation - */ - protected abstract A applyConfiguration0(C component, MyAbstractAction action); - - protected AbstractActionConfigurationResolver(Class<A> annotationImpl, Class<C> componentImpl) { - this.annotationImpl = annotationImpl; - this.componentImpl = componentImpl; - } - - public A resolveConfiguration(MyAbstractAction action) { - if (action.hasDelegate()) { - return resolveConfiguration(action.getDelegate()); - } - return action.getClass().getAnnotation(annotationImpl); - } - - @SuppressWarnings({"unchecked"}) - public A applyConfiguration(JComponent component, MyAbstractAction action) { - if (component != null && componentImpl.isAssignableFrom(component.getClass())) - return applyConfiguration0((C) component, action); - - return null; - } - - public Class<A> getAnnotationImpl() { - return annotationImpl; - } - - public Class<C> getComponentImpl() { - return componentImpl; - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/AbstractActionConfigurationResolver.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/AbstractActionConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,77 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import javax.swing.JComponent; + +/** + * Common abstract class of a resolver of action configuration. + * <p/> + * The class implements the logic of research of the configuration annotation. + * + * @param <A> type of annotation + * @param <C> type of component + * @author chemit + */ +public abstract class AbstractActionConfigurationResolver<A extends java.lang.annotation.Annotation, C extends JComponent> implements ActionConfigurationResolver<A, C> { + + /** the type of configuration's annotation */ + protected final Class<A> annotationImpl; + + /** the type of component that can fire an action */ + protected final Class<C> componentImpl; + + /** + * The typed method (on component) to apply configuration on the action and component. + * + * @param component the component which fires the action + * @param action the given action + * @return the configuration's annotation + */ + protected abstract A applyConfiguration0(C component, MyAbstractAction action); + + protected AbstractActionConfigurationResolver(Class<A> annotationImpl, Class<C> componentImpl) { + this.annotationImpl = annotationImpl; + this.componentImpl = componentImpl; + } + + @Override + public A resolveConfiguration(MyAbstractAction action) { + if (action.hasDelegate()) { + return resolveConfiguration(action.getDelegate()); + } + return action.getClass().getAnnotation(annotationImpl); + } + + @SuppressWarnings({"unchecked"}) + @Override + public A applyConfiguration(JComponent component, MyAbstractAction action) { + if (component != null && componentImpl.isAssignableFrom(component.getClass())) { + return applyConfiguration0((C) component, action); + } + + return null; + } + + @Override + public Class<A> getAnnotationImpl() { + return annotationImpl; + } + + @Override + public Class<C> getComponentImpl() { + return componentImpl; + } +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionAnnotationProcessing.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,395 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import javassist.CannotCompileException; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.LoaderClassPath; -import javassist.NotFoundException; -import org.codelutin.util.SortedProperties; - -import javax.annotation.processing.AbstractProcessor; -import javax.annotation.processing.ProcessingEnvironment; -import javax.annotation.processing.RoundEnvironment; -import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedOptions; -import javax.annotation.processing.SupportedSourceVersion; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.AnnotationValue; -import javax.lang.model.element.AnnotationValueVisitor; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.SimpleAnnotationValueVisitor6; -import javax.tools.FileObject; -import javax.tools.JavaFileObject; -import javax.tools.StandardLocation; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; - - -@SupportedAnnotationTypes(value = {"org.codelutin.jaxx.action.*"}) -@SupportedSourceVersion(SourceVersion.RELEASE_6) -@SupportedOptions({"jaxx.verbose"}) -/** - * Annotation processor to compute actions mapping. - * - * @author chemit */ -public class ActionAnnotationProcessing extends AbstractProcessor { - - /** the {@link ActionProvider} service declaration relative path */ - protected String providerDeclarationLocation = "META-INF/services/" + ActionProvider.class.getName(); - - /** the relative path where to store actions mapping, will be complete with the name of base action to use */ - protected String actionsFileLocation = ActionProviderFromProperties.actionsFileLocation; - - /** verbose flag (can be activated by passing an annotation parameter to compiler via <code>-Ai18n.verbose</code>) */ - protected boolean verbose; - - /** the list of class processed by the processor */ - protected java.util.List<String> processedClass; - - /** the map of actions processed, keys are the action commaned and values are fqn of implementations */ - protected Properties actions; - - /** Extractor of values of annotations found */ - protected AnnotationValueVisitor<Object, Void> annotationValueExtractor; - - /** the type element of the base action to be used by {@link ActionProvider} */ - protected TypeElement baseActionElement; - - /** the fqn of the action provider to generate */ - protected String providerFQN; - - /** the fqn of the base action class to be used */ - protected String baseFQN; - - @Override - public synchronized void init(ProcessingEnvironment processingEnv) { - super.init(processingEnv); - parseOptions(); - printDebug("verbose : " + verbose); - printDebug("FileLocation : " + actionsFileLocation); - processedClass = new ArrayList<String>(); - actions = new SortedProperties(); - } - - @Override - public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { - for (TypeElement annotation : annotations) { - - Set<? extends Element> annotatedWith = roundEnv.getElementsAnnotatedWith(annotation); - - if (annotation.getQualifiedName().toString().equals(ActionProviderAnnotation.class.getName())) { - // init provider - if (annotatedWith.size() != 1) { - throw new IllegalStateException("can have only one provider defined by the annotation " + ActionProviderAnnotation.class); - } - - baseActionElement = (TypeElement) annotatedWith.iterator().next(); - - //fixme it is not possible to know if baseActionElement is assigned from MyAbstractAction, since we - // can NOT garanted at this stage thaht the class was compiled... - - baseFQN = baseActionElement.asType().toString(); - int index = baseFQN.lastIndexOf(".") + 1; - String baseSimpleName = baseFQN.substring(index); - String packageName = baseFQN.substring(0, index); - - providerFQN = packageName + baseSimpleName + "Provider"; - printDebug("providerFQN " + providerFQN); - actionsFileLocation = String.format(actionsFileLocation, baseSimpleName); - continue; - } - - for (Element e : annotatedWith) { - String className = e.toString(); - - if (processedClass.contains(className)) { - printWarning("class already processed " + className); - // do not process class twice - continue; - } - - boolean wasTreated = registerActionsForClass(annotation.asType(), e); - if (wasTreated) { - printDebug("process class " + className); - processedClass.add(className); - } else { - printDebug("class was not processed " + e); - } - } - } - - if ((roundEnv.processingOver())) { - printDebug("round is over " + roundEnv); - try { - if (baseActionElement != null) { - // found the base action class to be compiled, so we have to write provider things... - writeProviderClass(); - writeProviderServiceDeclaration(); - } else { - - // baseActionClass was not compiled at this time, must find it back - // this means they should have an already mapping file written - - actionsFileLocation = findMappingFile(); - - printInfo("reused actionFilesLocation " + actionsFileLocation); - } - - writeActionMapping(); - - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - processedClass.clear(); - actions.clear(); - } - } - - return true; - } - - protected String findMappingFile() throws IOException { - String path = String.format(actionsFileLocation, "dummy_" + System.nanoTime()); - - - FileObject oldFo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", path); - File dummyFile = new File(oldFo.toUri().toString()).getParentFile(); - File[] files = dummyFile.listFiles(new FilenameFilter() { - - public boolean accept(File dir, String name) { - return name.startsWith("jaxx-") && name.endsWith("-actions.properties"); - } - }); - if (files.length < 1) { - // this is not normal, should have exactly one file here - throw new IllegalStateException("no provider name found, you must add on baseaction the annotation " + ActionProviderAnnotation.class); - } - File f = files[0]; - int index = f.getAbsolutePath().indexOf("META-INF"); - - return f.getAbsolutePath().substring(index); - } - - protected boolean registerActionsForClass(TypeMirror annotationType, Element e) { - boolean doTreate = false; - for (AnnotationMirror mirror : e.getAnnotationMirrors()) { - if (!mirror.getAnnotationType().equals(annotationType)) { - // do not treate other annotations - continue; - } - doTreate = true; - printDebug("found a annotation to treate : " + mirror + " for action : " + e.toString()); - for (String name : getActionNames(mirror)) { - actions.put("action." + name, e.toString()); - printDebug("registerActionForClass " + name + " : " + e.toString()); - } - } - return doTreate; - } - - protected void parseOptions() { - java.util.Map options = processingEnv.getOptions(); - verbose = options.containsKey("jaxx.verbose"); - } - - protected void writeProviderClass() throws IOException, NotFoundException, CannotCompileException, ClassNotFoundException { - OutputStream outputStream = null; - try { - - ClassPool pool = ClassPool.getDefault(); - - pool.appendClassPath(new LoaderClassPath(ActionProviderFromProperties.class.getClassLoader())); - - CtClass superClass = pool.get(ActionProviderFromProperties.class.getName()); - CtClass clazz = pool.makeClass(providerFQN); - // define the base action class in javassist pool to make possible compilation - pool.makeClass(baseFQN); - clazz.setSuperclass(superClass); - // add constructor - CtConstructor constructor = new CtConstructor(null, clazz); - constructor.setBody("super( " + baseFQN + ".class);"); - clazz.addConstructor(constructor); - byte[] byteCode = clazz.toBytecode(); - - JavaFileObject fo = processingEnv.getFiler().createClassFile(providerFQN); - printInfo("writing " + fo.toUri()); - outputStream = fo.openOutputStream(); - outputStream.write(byteCode); - - } finally { - if (outputStream != null) - outputStream.close(); - } - } - - protected void writeProviderServiceDeclaration() throws IOException { - BufferedWriter w = null; - try { - FileObject fo = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", providerDeclarationLocation); - printInfo("writing " + fo.toUri()); - w = new BufferedWriter(fo.openWriter()); - w.append("# generated by ").append(getClass().getName()).append("\n").toString(); - w.append("#").append(new java.util.Date().toString()).append("\n").toString(); - w.append(providerFQN); - } finally { - if (w != null) - w.close(); - } - } - - protected void writeActionMapping() throws IOException { - if (actions.isEmpty()) { - // nothing to write or overwrite - return; - } - - BufferedWriter w = null; - try { - Properties oldProps = loadOldActionMapping(); - if (oldProps != null) { - oldProps.putAll(actions); - actions = oldProps; - } - // ecriture de toutes les actions trouvees - FileObject fo = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", actionsFileLocation); - printInfo("writing " + fo.toUri()); - w = new BufferedWriter(fo.openWriter()); - actions.store(w, "generated by " + getClass().getName()); - } finally { - if (w != null) - w.close(); - } - } - - protected Properties loadOldActionMapping() throws IOException { - // reprise sur une ancienne compilation - FileObject oldFo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", actionsFileLocation); - if (!new File(oldFo.toUri().toString()).exists()) { - return null; - } - Properties oldProps = new SortedProperties(); - InputStream inputStream = null; - try { - inputStream = oldFo.openInputStream(); - if (inputStream != null) { - oldProps.load(inputStream); - } - oldFo.delete(); - } finally { - if (inputStream != null) { - inputStream.close(); - } - } - - return oldProps; - } - - /** - * Obtain the array of names to be used by the annotation - * - * @param element the dictonnary of values found in a annotation - * @return thee array of names detected in the annotation - */ - @SuppressWarnings({"unchecked"}) - protected String[] getActionNames(AnnotationMirror element) { - String[] result = null; - for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : element.getElementValues().entrySet()) { - ExecutableElement type = entry.getKey(); - String name = type.getSimpleName().toString(); - - if ("actionCommands".equals(name)) { - List<String> stringList = (List<String>) entry.getValue().accept(getAnnotationValueExtractor(), null); - result = stringList.toArray(new String[stringList.size()]); - // a actionCommands field means - break; - } - if ("actionCommandProvider".equals(name)) { - TypeMirror t = (TypeMirror) entry.getValue().accept(getAnnotationValueExtractor(), null); - String classname = t.toString(); - printDebug("actionCommandProvider = " + classname); - if (classname.equals(ActionNameProvider.class.getName())) { - continue; - } - - // means there is a runtime names provider - result = new String[]{":" + classname}; - break; - } - if ("actionCommand".equals(name)) { - result = new String[]{(String) entry.getValue().accept(getAnnotationValueExtractor(), null)}; - } - } - - return result; - } - - protected AnnotationValueVisitor<Object, Void> getAnnotationValueExtractor() { - if (annotationValueExtractor == null) { - annotationValueExtractor = new SimpleAnnotationValueVisitor6<Object, Void>() { - - @Override - protected Object defaultAction(Object o, Void aVoid) { - return o; - } - - @Override - public Object visitArray(List<? extends AnnotationValue> vals, Void aVoid) { - List<Object> realVals = new java.util.ArrayList<Object>(); - for (AnnotationValue val : vals) { - realVals.add(val.accept(this, aVoid)); - } - return realVals; - } - - public Object visitType(TypeMirror t, Void aVoid) { - return t; - } - }; - } - return annotationValueExtractor; - } - - protected void printWarning(String msg) { - System.out.println("[WARN] " + getClass().getName() + " : " + msg); - } - - protected void printInfo(String msg) { - System.out.println("[INFO] " + getClass().getName() + " : " + msg); - } - - protected void printDebug(String msg) { - if (verbose) { - System.out.println("[DEBUG] " + getClass().getName() + " : " + msg); - } - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionAnnotationProcessing.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionAnnotationProcessing.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,398 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.LoaderClassPath; +import javassist.NotFoundException; +import org.nuiton.util.SortedProperties; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.AnnotationValueVisitor; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.SimpleAnnotationValueVisitor6; +import javax.tools.FileObject; +import javax.tools.JavaFileObject; +import javax.tools.StandardLocation; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; + + +@SupportedAnnotationTypes(value = {"org.nuiton.jaxx.action.*"}) +@SupportedSourceVersion(SourceVersion.RELEASE_6) +@SupportedOptions({"jaxx.verbose"}) +/** + * Annotation processor to compute actions mapping. + * + * @author chemit */ +public class ActionAnnotationProcessing extends AbstractProcessor { + + /** the {@link ActionProvider} service declaration relative path */ + protected String providerDeclarationLocation = "META-INF/services/" + ActionProvider.class.getName(); + + /** the relative path where to store actions mapping, will be complete with the name of base action to use */ + protected String actionsFileLocation = ActionProviderFromProperties.actionsFileLocation; + + /** verbose flag (can be activated by passing an annotation parameter to compiler via <code>-Ai18n.verbose</code>) */ + protected boolean verbose; + + /** the list of class processed by the processor */ + protected java.util.List<String> processedClass; + + /** the map of actions processed, keys are the action commaned and values are fqn of implementations */ + protected Properties actions; + + /** Extractor of values of annotations found */ + protected AnnotationValueVisitor<Object, Void> annotationValueExtractor; + + /** the type element of the base action to be used by {@link ActionProvider} */ + protected TypeElement baseActionElement; + + /** the fqn of the action provider to generate */ + protected String providerFQN; + + /** the fqn of the base action class to be used */ + protected String baseFQN; + + @Override + public synchronized void init(ProcessingEnvironment processingEnv) { + super.init(processingEnv); + parseOptions(); + printDebug("verbose : " + verbose); + printDebug("FileLocation : " + actionsFileLocation); + processedClass = new ArrayList<String>(); + actions = new SortedProperties(); + } + + @Override + public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + + Set<? extends Element> annotatedWith = roundEnv.getElementsAnnotatedWith(annotation); + + if (annotation.getQualifiedName().toString().equals(ActionProviderAnnotation.class.getName())) { + // init provider + if (annotatedWith.size() != 1) { + throw new IllegalStateException("can have only one provider defined by the annotation " + ActionProviderAnnotation.class); + } + + baseActionElement = (TypeElement) annotatedWith.iterator().next(); + + //fixme it is not possible to know if baseActionElement is assigned from MyAbstractAction, since we + // can NOT garanted at this stage thaht the class was compiled... + + baseFQN = baseActionElement.asType().toString(); + int index = baseFQN.lastIndexOf(".") + 1; + String baseSimpleName = baseFQN.substring(index); + String packageName = baseFQN.substring(0, index); + + providerFQN = packageName + baseSimpleName + "Provider"; + printDebug("providerFQN " + providerFQN); + actionsFileLocation = String.format(actionsFileLocation, baseSimpleName); + continue; + } + + for (Element e : annotatedWith) { + String className = e.toString(); + + if (processedClass.contains(className)) { + printWarning("class already processed " + className); + // do not process class twice + continue; + } + + boolean wasTreated = registerActionsForClass(annotation.asType(), e); + if (wasTreated) { + printDebug("process class " + className); + processedClass.add(className); + } else { + printDebug("class was not processed " + e); + } + } + } + + if ((roundEnv.processingOver())) { + printDebug("round is over " + roundEnv); + try { + if (baseActionElement != null) { + // found the base action class to be compiled, so we have to write provider things... + writeProviderClass(); + writeProviderServiceDeclaration(); + } else { + + // baseActionClass was not compiled at this time, must find it back + // this means they should have an already mapping file written + + actionsFileLocation = findMappingFile(); + + printInfo("reused actionFilesLocation " + actionsFileLocation); + } + + writeActionMapping(); + + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + processedClass.clear(); + actions.clear(); + } + } + + return true; + } + + protected String findMappingFile() throws IOException { + String path = String.format(actionsFileLocation, "dummy_" + System.nanoTime()); + + + FileObject oldFo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", path); + File dummyFile = new File(oldFo.toUri().toString()).getParentFile(); + File[] files = dummyFile.listFiles(new FilenameFilter() { + + public boolean accept(File dir, String name) { + return name.startsWith("jaxx-") && name.endsWith("-actions.properties"); + } + }); + if (files.length < 1) { + // this is not normal, should have exactly one file here + throw new IllegalStateException("no provider name found, you must add on baseaction the annotation " + ActionProviderAnnotation.class); + } + File f = files[0]; + int index = f.getAbsolutePath().indexOf("META-INF"); + + return f.getAbsolutePath().substring(index); + } + + protected boolean registerActionsForClass(TypeMirror annotationType, Element e) { + boolean doTreate = false; + for (AnnotationMirror mirror : e.getAnnotationMirrors()) { + if (!mirror.getAnnotationType().equals(annotationType)) { + // do not treate other annotations + continue; + } + doTreate = true; + printDebug("found a annotation to treate : " + mirror + " for action : " + e.toString()); + for (String name : getActionNames(mirror)) { + actions.put("action." + name, e.toString()); + printDebug("registerActionForClass " + name + " : " + e.toString()); + } + } + return doTreate; + } + + protected void parseOptions() { + java.util.Map options = processingEnv.getOptions(); + verbose = options.containsKey("jaxx.verbose"); + } + + protected void writeProviderClass() throws IOException, NotFoundException, CannotCompileException, ClassNotFoundException { + OutputStream outputStream = null; + try { + + ClassPool pool = ClassPool.getDefault(); + + pool.appendClassPath(new LoaderClassPath(ActionProviderFromProperties.class.getClassLoader())); + + CtClass superClass = pool.get(ActionProviderFromProperties.class.getName()); + CtClass clazz = pool.makeClass(providerFQN); + // define the base action class in javassist pool to make possible compilation + pool.makeClass(baseFQN); + clazz.setSuperclass(superClass); + // add constructor + CtConstructor constructor = new CtConstructor(null, clazz); + constructor.setBody("super( " + baseFQN + ".class);"); + clazz.addConstructor(constructor); + byte[] byteCode = clazz.toBytecode(); + + JavaFileObject fo = processingEnv.getFiler().createClassFile(providerFQN); + printInfo("writing " + fo.toUri()); + outputStream = fo.openOutputStream(); + outputStream.write(byteCode); + + } finally { + if (outputStream != null) { + outputStream.close(); + } + } + } + + protected void writeProviderServiceDeclaration() throws IOException { + BufferedWriter w = null; + try { + FileObject fo = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", providerDeclarationLocation); + printInfo("writing " + fo.toUri()); + w = new BufferedWriter(fo.openWriter()); + w.append("# generated by ").append(getClass().getName()).append("\n").toString(); + w.append("#").append(new java.util.Date().toString()).append("\n").toString(); + w.append(providerFQN); + } finally { + if (w != null) { + w.close(); + } + } + } + + protected void writeActionMapping() throws IOException { + if (actions.isEmpty()) { + // nothing to write or overwrite + return; + } + + BufferedWriter w = null; + try { + Properties oldProps = loadOldActionMapping(); + if (oldProps != null) { + oldProps.putAll(actions); + actions = oldProps; + } + // ecriture de toutes les actions trouvees + FileObject fo = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", actionsFileLocation); + printInfo("writing " + fo.toUri()); + w = new BufferedWriter(fo.openWriter()); + actions.store(w, "generated by " + getClass().getName()); + } finally { + if (w != null) { + w.close(); + } + } + } + + protected Properties loadOldActionMapping() throws IOException { + // reprise sur une ancienne compilation + FileObject oldFo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", actionsFileLocation); + if (!new File(oldFo.toUri().toString()).exists()) { + return null; + } + Properties oldProps = new SortedProperties(); + InputStream inputStream = null; + try { + inputStream = oldFo.openInputStream(); + if (inputStream != null) { + oldProps.load(inputStream); + } + oldFo.delete(); + } finally { + if (inputStream != null) { + inputStream.close(); + } + } + + return oldProps; + } + + /** + * Obtain the array of names to be used by the annotation + * + * @param element the dictonnary of values found in a annotation + * @return thee array of names detected in the annotation + */ + @SuppressWarnings({"unchecked"}) + protected String[] getActionNames(AnnotationMirror element) { + String[] result = null; + for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : element.getElementValues().entrySet()) { + ExecutableElement type = entry.getKey(); + String name = type.getSimpleName().toString(); + + if ("actionCommands".equals(name)) { + List<String> stringList = (List<String>) entry.getValue().accept(getAnnotationValueExtractor(), null); + result = stringList.toArray(new String[stringList.size()]); + // a actionCommands field means + break; + } + if ("actionCommandProvider".equals(name)) { + TypeMirror t = (TypeMirror) entry.getValue().accept(getAnnotationValueExtractor(), null); + String classname = t.toString(); + printDebug("actionCommandProvider = " + classname); + if (classname.equals(ActionNameProvider.class.getName())) { + continue; + } + + // means there is a runtime names provider + result = new String[]{":" + classname}; + break; + } + if ("actionCommand".equals(name)) { + result = new String[]{(String) entry.getValue().accept(getAnnotationValueExtractor(), null)}; + } + } + + return result; + } + + protected AnnotationValueVisitor<Object, Void> getAnnotationValueExtractor() { + if (annotationValueExtractor == null) { + annotationValueExtractor = new SimpleAnnotationValueVisitor6<Object, Void>() { + + @Override + protected Object defaultAction(Object o, Void aVoid) { + return o; + } + + @Override + public Object visitArray(List<? extends AnnotationValue> vals, Void aVoid) { + List<Object> realVals = new java.util.ArrayList<Object>(); + for (AnnotationValue val : vals) { + realVals.add(val.accept(this, aVoid)); + } + return realVals; + } + + public Object visitType(TypeMirror t, Void aVoid) { + return t; + } + }; + } + return annotationValueExtractor; + } + + protected void printWarning(String msg) { + System.out.println("[WARN] " + getClass().getName() + " : " + msg); + } + + protected void printInfo(String msg) { + System.out.println("[INFO] " + getClass().getName() + " : " + msg); + } + + protected void printDebug(String msg) { + if (verbose) { + System.out.println("[DEBUG] " + getClass().getName() + " : " + msg); + } + } +} Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfig.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionConfig.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfig.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -16,7 +16,7 @@ * 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.jaxx.action; +package org.nuiton.jaxx.action; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -51,10 +51,10 @@ /** * @return the class to obtain at runtime the array of names to be used in actions mapping. * <p/> - * <b>Note : the special value {@link org.codelutin.jaxx.action.ActionNameProvider} is used to says not to used + * <b>Note : the special value {@link org.nuiton.jaxx.action.ActionNameProvider} is used to says not to used * œthis mecanism since we can not set a null value in a annotation</b> */ - Class<? extends ActionNameProvider> actionCommandProvider() default org.codelutin.jaxx.action.ActionNameProvider.class; + Class<? extends ActionNameProvider> actionCommandProvider() default org.nuiton.jaxx.action.ActionNameProvider.class; /** * @return la clef i18n du texte de l'action, si vide ignoré Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionConfigConfigurationResolver.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,67 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import static org.codelutin.i18n.I18n._; - -import javax.swing.AbstractButton; -import javax.swing.Action; - -/** - * Implementation of configuration's resolver for annotation {@link ActionConfig} - * - * @author chemit - */ -public class ActionConfigConfigurationResolver extends AbstractActionConfigurationResolver<ActionConfig, AbstractButton> { - - public ActionConfigConfigurationResolver() { - super(ActionConfig.class, AbstractButton.class); - } - - protected ActionConfig applyConfiguration0(AbstractButton component, MyAbstractAction action) { - ActionConfig anno = resolveConfiguration(action); - if (anno == null) { - return null; - } - // inject les données - if (!anno.name().isEmpty()) { - //System.out.println("found action with name : " + anno.name()); - action.putValue(Action.NAME, _(anno.name())); - } - //if (!anno.shortDescription().isEmpty()) { - action.putValue(Action.SHORT_DESCRIPTION, _(anno.shortDescription())); - //} - if (!anno.smallIcon().isEmpty()) { - action.putValue(Action.SMALL_ICON, org.codelutin.jaxx.util.UIHelper.createImageIcon(anno.smallIcon())); - } - if (anno.mnemonic() != '\0') { - action.putValue(Action.MNEMONIC_KEY, anno.mnemonic()); - } else if (component != null) { - action.putValue(Action.MNEMONIC_KEY, component.getMnemonic()); - } - //TODO Convert it from String action.putValue(Action.ACCELERATOR_KEY, anno.accelerator()); - - if (component == null) { - action.putValue("hideActionText", anno.hideActionText()); - } else { - boolean actionText = component.getHideActionText(); - action.putValue("hideActionText", anno.hideActionText() || actionText); - } - action.putValue(Action.SELECTED_KEY, anno.selected()); - action.setEnabled(anno.enabled()); - - return anno; - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionConfigConfigurationResolver.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,68 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import static org.nuiton.i18n.I18n._; + +import javax.swing.AbstractButton; +import javax.swing.Action; + +/** + * Implementation of configuration's resolver for annotation {@link ActionConfig} + * + * @author chemit + */ +public class ActionConfigConfigurationResolver extends AbstractActionConfigurationResolver<ActionConfig, AbstractButton> { + + public ActionConfigConfigurationResolver() { + super(ActionConfig.class, AbstractButton.class); + } + + @Override + protected ActionConfig applyConfiguration0(AbstractButton component, MyAbstractAction action) { + ActionConfig anno = resolveConfiguration(action); + if (anno == null) { + return null; + } + // inject les données + if (!anno.name().isEmpty()) { + //System.out.println("found action with name : " + anno.name()); + action.putValue(Action.NAME, _(anno.name())); + } + //if (!anno.shortDescription().isEmpty()) { + action.putValue(Action.SHORT_DESCRIPTION, _(anno.shortDescription())); + //} + if (!anno.smallIcon().isEmpty()) { + action.putValue(Action.SMALL_ICON, org.nuiton.jaxx.util.UIHelper.createImageIcon(anno.smallIcon())); + } + if (anno.mnemonic() != '\0') { + action.putValue(Action.MNEMONIC_KEY, anno.mnemonic()); + } else if (component != null) { + action.putValue(Action.MNEMONIC_KEY, component.getMnemonic()); + } + //TODO Convert it from String action.putValue(Action.ACCELERATOR_KEY, anno.accelerator()); + + if (component == null) { + action.putValue("hideActionText", anno.hideActionText()); + } else { + boolean actionText = component.getHideActionText(); + action.putValue("hideActionText", anno.hideActionText() || actionText); + } + action.putValue(Action.SELECTED_KEY, anno.selected()); + action.setEnabled(anno.enabled()); + + return anno; + } +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionConfigurationResolver.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,52 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import javax.swing.JComponent; - -/** - * The contract to be realized to resolve an {@link MyAbstractAction} configuration. - * <p/> - * Configuration is done by a Annotation of type {@link A} placed on the action class. - * <p/> - * If the instanciated action box the real action, we should always search on the boxed action. - * <p/> - * Moreover, a action can only be fired by a certain type of component (for example a Button or a ComboBox), the class - * of the component type is given by the {@link C} class. - * - * @author chemit - */ -public interface ActionConfigurationResolver<A extends java.lang.annotation.Annotation, C extends JComponent> { - /** - * Search the annotation that configure the given action (or the boxed action). - * - * @param action current action - * @return the configuration of the action - */ - A resolveConfiguration(MyAbstractAction action); - - /** - * @param component widget that requires the action - * @param action given action - * @return the configuration of the action - */ - A applyConfiguration(JComponent component, MyAbstractAction action); - - /** @return the configuration annotation dealed by this resolver */ - Class<A> getAnnotationImpl(); - - /** @return the class of the component which can fired the action */ - Class<C> getComponentImpl(); -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionConfigurationResolver.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,54 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import javax.swing.JComponent; + +/** + * The contract to be realized to resolve an {@link MyAbstractAction} configuration. + * <p/> + * Configuration is done by a Annotation of type {@link A} placed on the action class. + * <p/> + * If the instanciated action box the real action, we should always search on the boxed action. + * <p/> + * Moreover, a action can only be fired by a certain type of component (for example a Button or a ComboBox), the class + * of the component type is given by the {@link C} class. + * + * @param <A> type of annotation for config + * @param <C> type of component + * @author chemit + */ +public interface ActionConfigurationResolver<A extends java.lang.annotation.Annotation, C extends JComponent> { + /** + * Search the annotation that configure the given action (or the boxed action). + * + * @param action current action + * @return the configuration of the action + */ + A resolveConfiguration(MyAbstractAction action); + + /** + * @param component widget that requires the action + * @param action given action + * @return the configuration of the action + */ + A applyConfiguration(JComponent component, MyAbstractAction action); + + /** @return the configuration annotation dealed by this resolver */ + Class<A> getAnnotationImpl(); + + /** @return the class of the component which can fired the action */ + Class<C> getComponentImpl(); +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionFactory.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,149 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import jaxx.runtime.JAXXObject; - -import javax.swing.JComponent; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * Action factory using the <code>ActionConfig-like</code> annotations to configure actions. - * <p/> - * <p/> - * An {@link ActionFactory} builds actions always on a same type <code>A</code> and obtain them from some - * {@link ActionProvider} via methods {@link #newAction(String, JComponent)} and {@link #newAction(String)} . - * <p/> - * If the action coming from the provider is not on the same type <code>A</code>, then the action is boxed in a * - * action <code>A</code> and use the generic mecanism of delegation provided by {@link MyAbstractAction}. - * <p/> - * Use after the {@link #loadActions(jaxx.runtime.JAXXObject)} to instanciate actions in ui with id equals a known - * action... - * <p/> - * All actions instanciated are stored in a cache that you can request via method {@link #getActionFromCache(String)}, - * {@link #cacheEntrySet()} and {@link #resetCache()}. - * <p/> - * You can also from this factory fires some action via the methods {@link #fireAction(String, Object, JComponent)} , - * {@link #fireAction(String, Object)} , {@link #fireAction0(String, Object, MyAbstractAction)}. - * <p/> - * Finally, a {@link #dispose()} method is there to shut down all instanciated action when you want to dispose all uis. - * - * @author chemit - * @see ActionProvider - * @see MyAbstractAction - */ -public interface ActionFactory<A extends MyAbstractAction> { - - /** - * Method to init the dictionary of knwon action implementations. - * - * @return the dictionary of known action implementations - */ - Map<String, Class<? extends MyAbstractAction>> init(); - - /** @return the class of the base action of the factory. */ - Class<A> getBaseClass(); - - /** @return the set of all the action's classes known by the factory. */ - Set<Entry<String, Class<? extends MyAbstractAction>>> implsEntrySet(); - - /** @return the array of names of all actions known by the factory */ - String[] getActionNames(); - - /** @return the set of all actions cached in factory indexed by their name */ - Set<Entry<String, A>> cacheEntrySet(); - - /** - * @param actionKey the action's key - * @return the action in cache or <code>null</code> if action is not in cache - */ - MyAbstractAction getActionFromCache(String actionKey); - - /** clear the cache of instanciated actions. */ - void resetCache(); - - /** - * @param actionKey the key of an action - * @return the action with this key from cache, or <code>null</code> if this action is not in cache - */ - - //A get(String actionKey); - - /** - * For a given ui, load all actions registred in factory. - * <p/> - * The id of the widget in ui is directly mapped to a action key. - * - * @param ui the ui to treate - */ - void loadActions(JAXXObject ui); - - /** - * Obtain an action instance given his key and widget - * - * @param actionKey the key of action - * @param component the component using the action - * @return the instanciated action (could come from cache if already instanciated {@link #getActionFromCache(String)} - */ - A newAction(String actionKey, JComponent component); - - /** - * Obtain an action instance given his key (should call {@link #newAction(String, JComponent)} - * <p/> - * This is a convinient method when you want to obtain an action with no attached widget. - * - * @param actionKey the key of action - * @return the instanciated action (could come from cache if already instanciated {@link #getActionFromCache(String)} - */ - A newAction(String actionKey); - - - /** - * Fire an action given his key, his source and tthe widget responsible of action - * - * @param actionKey the action's key - * @param source the object source of action - * @param component the component doing the action - */ - void fireAction(String actionKey, Object source, JComponent component); - - /** - * Fire an action given his key and his source, no widget are involved here - * - * @param actionKey the action's key - * @param source the object source of action - */ - void fireAction(String actionKey, Object source); - - /** - * Fire an action given his action's key, his source and the real action. - * <p/> - * This is a convinient method when you need to modified action before fire it. - * - * @param actionKey action's key - * @param source source of action - * @param action real action - */ - void fireAction0(String actionKey, Object source, A action); - - - /** - * dispose all actions in cache using {@link MyAbstractAction#disposeUI()} on each - * action, then {@link #resetCache()} - */ - void dispose(); -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionFactory.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactory.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,150 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import jaxx.runtime.JAXXObject; + +import javax.swing.JComponent; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Action factory using the <code>ActionConfig-like</code> annotations to configure actions. + * <p/> + * <p/> + * An {@link ActionFactory} builds actions always on a same type <code>A</code> and obtain them from some + * {@link ActionProvider} via methods {@link #newAction(String, JComponent)} and {@link #newAction(String)} . + * <p/> + * If the action coming from the provider is not on the same type <code>A</code>, then the action is boxed in a * + * action <code>A</code> and use the generic mecanism of delegation provided by {@link MyAbstractAction}. + * <p/> + * Use after the {@link #loadActions(jaxx.runtime.JAXXObject)} to instanciate actions in ui with id equals a known + * action... + * <p/> + * All actions instanciated are stored in a cache that you can request via method {@link #getActionFromCache(String)}, + * {@link #cacheEntrySet()} and {@link #resetCache()}. + * <p/> + * You can also from this factory fires some action via the methods {@link #fireAction(String, Object, JComponent)} , + * {@link #fireAction(String, Object)} , {@link #fireAction0(String, Object, MyAbstractAction)}. + * <p/> + * Finally, a {@link #dispose()} method is there to shut down all instanciated action when you want to dispose all uis. + * + * @param <A> type of boxed action + * @author chemit + * @see ActionProvider + * @see MyAbstractAction + */ +public interface ActionFactory<A extends MyAbstractAction> { + + /** + * Method to init the dictionary of knwon action implementations. + * + * @return the dictionary of known action implementations + */ + Map<String, Class<? extends MyAbstractAction>> init(); + + /** @return the class of the base action of the factory. */ + Class<A> getBaseClass(); + + /** @return the set of all the action's classes known by the factory. */ + Set<Entry<String, Class<? extends MyAbstractAction>>> implsEntrySet(); + + /** @return the array of names of all actions known by the factory */ + String[] getActionNames(); + + /** @return the set of all actions cached in factory indexed by their name */ + Set<Entry<String, A>> cacheEntrySet(); + + /** + * @param actionKey the action's key + * @return the action in cache or <code>null</code> if action is not in cache + */ + MyAbstractAction getActionFromCache(String actionKey); + + /** clear the cache of instanciated actions. */ + void resetCache(); + + /** + * @param actionKey the key of an action + * @return the action with this key from cache, or <code>null</code> if this action is not in cache + */ + + //A get(String actionKey); + + /** + * For a given ui, load all actions registred in factory. + * <p/> + * The id of the widget in ui is directly mapped to a action key. + * + * @param ui the ui to treate + */ + void loadActions(JAXXObject ui); + + /** + * Obtain an action instance given his key and widget + * + * @param actionKey the key of action + * @param component the component using the action + * @return the instanciated action (could come from cache if already instanciated {@link #getActionFromCache(String)} + */ + A newAction(String actionKey, JComponent component); + + /** + * Obtain an action instance given his key (should call {@link #newAction(String, JComponent)} + * <p/> + * This is a convinient method when you want to obtain an action with no attached widget. + * + * @param actionKey the key of action + * @return the instanciated action (could come from cache if already instanciated {@link #getActionFromCache(String)} + */ + A newAction(String actionKey); + + + /** + * Fire an action given his key, his source and tthe widget responsible of action + * + * @param actionKey the action's key + * @param source the object source of action + * @param component the component doing the action + */ + void fireAction(String actionKey, Object source, JComponent component); + + /** + * Fire an action given his key and his source, no widget are involved here + * + * @param actionKey the action's key + * @param source the object source of action + */ + void fireAction(String actionKey, Object source); + + /** + * Fire an action given his action's key, his source and the real action. + * <p/> + * This is a convinient method when you need to modified action before fire it. + * + * @param actionKey action's key + * @param source source of action + * @param action real action + */ + void fireAction0(String actionKey, Object source, A action); + + + /** + * dispose all actions in cache using {@link MyAbstractAction#disposeUI()} on each + * action, then {@link #resetCache()} + */ + void dispose(); +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionFactoryFromProvider.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,457 +0,0 @@ -/* -* ##% Copyright (C) 2007, 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.jaxx.action; - -import jaxx.runtime.JAXXObject; -import jaxx.runtime.swing.JAXXToggleButton; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codelutin.util.Resource; - -import javax.swing.AbstractButton; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import java.awt.event.ActionEvent; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.ServiceLoader; -import java.util.Set; -import java.util.TreeMap; - -/** - * A simple implementation of {@link ActionFactory} using some {@link ActionProvider} to seek actions. - * <p/> - * <p/> - * An entry is in that form : <code>action.actionName=fqn</code> where - * <p/> - * <code>actionName</code> is the key of action used in factory, and - * <code>fqn</code> is the fully qualified name of the implemented action class. - * <p/> - * A special clase is to have for a given entry a key like this : <code>action.:fqn'=fqn</code>, in that case, - * le fqn' is a classe of type {@link org.codelutin.jaxx.action.ActionNameProvider} which gives us at - * runtime the names of each entry to put in cache for the givne action fqn. - * - * @author chemit - */ -public class ActionFactoryFromProvider<A extends MyAbstractAction> implements ActionFactory<A> { - - protected static Log log = LogFactory.getLog(ActionFactoryFromProvider.class); - - public static <A extends MyAbstractAction> ActionFactory<A> newInstance(Class<A> klazz) { - return new ActionFactoryFromProvider<A>(klazz); - } - - /** class of encapsuling action */ - protected Class<A> baseImpl; - - /** dictionary of known actions implementations */ - private Map<String, Class<? extends MyAbstractAction>> impls; - - /** dictionary of instanciated actions */ - private Map<String, A> cache; - - protected final ActionConfigConfigurationResolver actionConfigInitializer; - protected final ToggleActionConfigConfigurationResolver toggleActionConfigInitializer; - protected final SelectActionConfigConfigurationResolver selectActionConfigInitializer; - - protected List<AbstractActionConfigurationResolver> configurationResolvers; - - protected ActionFactoryFromProvider(Class<A> baseImpl) { - this.baseImpl = baseImpl; - this.impls = init(); - this.cache = new TreeMap<String, A>(); - this.configurationResolvers = new java.util.ArrayList<AbstractActionConfigurationResolver>(); - - this.toggleActionConfigInitializer = registerInitializer(ToggleActionConfigConfigurationResolver.class); - this.actionConfigInitializer = registerInitializer(ActionConfigConfigurationResolver.class); - this.selectActionConfigInitializer = registerInitializer(SelectActionConfigConfigurationResolver.class); - } - - public Class<A> getBaseClass() { - return baseImpl; - } - - public void resetCache() { - cache.clear(); - } - - /*public A get(String actionKey) { - return cache.get(actionKey); - }*/ - - public void loadActions(JAXXObject ui) { - if (log.isDebugEnabled()) { - log.debug("for ui " + ui.getClass()); - } - for (Map.Entry<String, Class<? extends MyAbstractAction>> entry : implsEntrySet()) { - String actionKey = entry.getKey(); - Object comp = ui.getObjectById(actionKey); - if (comp == null || !(comp instanceof AbstractButton || comp instanceof JComboBox)) { - // nothing to do - continue; - } - if (log.isTraceEnabled()) { - log.trace("detect action " + actionKey); - } - if (comp instanceof AbstractButton) { - AbstractButton component = (AbstractButton) comp; - A action = newAction(actionKey, component); - - component.setAction(action); - - if (component instanceof JAXXToggleButton) { - JAXXToggleButton glueComponent = (JAXXToggleButton) component; - glueComponent.setIcon((Icon) action.getValue(Action.SMALL_ICON)); - Integer integer = (Integer) action.getValue(Action.MNEMONIC_KEY); - if (integer != null) { - glueComponent.setNormalMnemonic(integer); - } - glueComponent.setSelectedIcon((Icon) action.getValue(Action.SMALL_ICON + 2)); - integer = (Integer) action.getValue(Action.MNEMONIC_KEY + 2); - if (integer != null) { - glueComponent.setGlueMnemonic(integer); - } - glueComponent.setGlueText((String) action.getValue(Action.NAME + 2)); - glueComponent.setGlueTooltipText((String) action.getValue(Action.SHORT_DESCRIPTION + 2)); - - glueComponent.setNormalText((String) action.getValue(Action.NAME)); - glueComponent.setNormalTooltipText((String) action.getValue(Action.SHORT_DESCRIPTION)); - } - - Boolean value = (Boolean) action.getValue("hideActionText"); - component.setHideActionText(value != null && value); - action.setEnabled(true); - continue; - } - // is JComboBox - JComboBox component = (JComboBox) comp; - A action = newAction(actionKey, component); - - component.setAction(action); - Integer val = (Integer) action.getValue("selectedIndex"); - if (val != null && val != -1 && val < component.getItemCount() && val != component.getSelectedIndex()) { - component.setSelectedIndex(val); - } - } - } - - /** - * @param actionKey le nom de l'action tel que définie dans le fichier - * de mapping (sans le prefix action.) - * @param component le button où rattacher l'action - * @return une nouvelle instance de l'action associée à sa clef. - */ - public A newAction(String actionKey, JComponent component) { - // try first in cache - A result = getActionFromCache(actionKey); - if (result != null) { - return result; - } - - try { - result = newActionInstance(actionKey); - } catch (Exception e) { - throw new RuntimeException(e); - } - - if (log.isDebugEnabled()) { - log.debug("create <" + actionKey + " : " + result + ">"); - } - - // recherche de l'annotation de configuration - ActionConfigurationResolver<?, ?> configurationResolver = resolveActionConfiguration(result); - - if (configurationResolver != null) { - configurationResolver.applyConfiguration(component, result); - } - - try { - - if (configurationResolver != null) { - if (AbstractButton.class.isAssignableFrom(configurationResolver.getComponentImpl())) { - finalizeNewAction((AbstractButton) component, result, configurationResolver); - } - - if (JComboBox.class.isAssignableFrom(configurationResolver.getComponentImpl())) { - finalizeNewAction((JComboBox) component, result, configurationResolver); - } - - return result; - } - - if (component == null || component instanceof AbstractButton) { - finalizeNewAction((AbstractButton) component, result, configurationResolver); - return result; - } - - if (component instanceof JComboBox) { - finalizeNewAction((JComboBox) component, result, configurationResolver); - } - } finally { - // save result in cache - cache.put(actionKey, result); - } - - return result; - } - - public A newAction(String actionKey) { - return newAction(actionKey, null); - } - - public String[] getActionNames() { - return impls.keySet().toArray(new String[impls.size()]); - } - - public Set<Entry<String, Class<? extends MyAbstractAction>>> implsEntrySet() { - return impls.entrySet(); - } - - public Set<Entry<String, A>> cacheEntrySet() { - return cache.entrySet(); - } - - public void fireAction(String actionKey, Object source, JComponent component) { - A action = newAction(actionKey, component); - fireAction0(actionKey, source, action); - } - - public void fireAction(String actionKey, Object source) { - fireAction(actionKey, source, null); - } - - /** - * @param actionKey la clef de l'action - * @return l'action deja stockee dans le cache d'action, ou <code>null</code> si non trouvée. - */ - public A getActionFromCache(String actionKey) { - // on vérifie que l'action existe bien - checkRegistredAction(actionKey); - - A action = null; - // try in cache - if (cache.containsKey(actionKey)) { - // use cached action - action = cache.get(actionKey); - if (log.isDebugEnabled()) { - log.debug("use cache action " + action); - } - } - return action; - } - - public void dispose() { - if (log.isInfoEnabled()) { - log.info(this); - } - for (String actionKey : getActionNames()) { - MyAbstractAction action = getActionFromCache(actionKey); - if (action != null) { - action.disposeUI(); - } - } - resetCache(); - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - resetCache(); - impls.clear(); - } - - /** - * @param component le button où rattacher l'action - * @param action action - * @param configurationResolver initializer - */ - protected void finalizeNewAction(AbstractButton component, MyAbstractAction action, ActionConfigurationResolver<?, ?> configurationResolver) { - - if (configurationResolver == null) { - // no configurationResolver matching, - if (component != null) { - action.putValue(Action.ACTION_COMMAND_KEY, component.getName()); - action.putValue(Action.SHORT_DESCRIPTION, component.getToolTipText()); - action.putValue(Action.SMALL_ICON, component.getIcon()); - action.putValue(Action.NAME, component.getText()); - action.putValue(Action.MNEMONIC_KEY, component.getMnemonic()); - action.putValue("hideActionText", component.getHideActionText()); - if (component instanceof JAXXToggleButton) { - JAXXToggleButton glueComponent = (JAXXToggleButton) component; - action.putValue(Action.SHORT_DESCRIPTION, glueComponent.getNormalTooltipText()); - action.putValue(Action.NAME, glueComponent.getNormalText()); - action.putValue(Action.SMALL_ICON, glueComponent.getIcon()); - action.putValue(Action.MNEMONIC_KEY, glueComponent.getNormalMnemonic()); - action.putValue(Action.SHORT_DESCRIPTION + 2, glueComponent.getGlueTooltipText()); - action.putValue(Action.NAME + 2, glueComponent.getGlueText()); - action.putValue(Action.SMALL_ICON + 2, glueComponent.getSelectedIcon()); - action.putValue(Action.MNEMONIC_KEY + 2, glueComponent.getGlueMnemonic()); - } - } - - } - - String text = (String) action.getValue(Action.NAME); - Integer mnemo = (Integer) action.getValue(Action.MNEMONIC_KEY); - if (mnemo != null && mnemo != '\0') { - int pos = text.indexOf((char) mnemo.intValue()); - if (pos == -1) { - pos = text.indexOf(Character.toLowerCase((char) mnemo.intValue())); - } - action.putValue(Action.DISPLAYED_MNEMONIC_INDEX_KEY, pos); - } - - } - - /** - * @param component le select box où rattacher l'action - * @param action action - * @param configurationResolver initializer - */ - protected void finalizeNewAction(JComboBox component, MyAbstractAction action, ActionConfigurationResolver<?, ?> configurationResolver) { - - if (configurationResolver == null) { - action.putValue(Action.ACTION_COMMAND_KEY, component.getName()); - action.putValue(Action.SHORT_DESCRIPTION, component.getToolTipText()); - //result.putValue("selectedIndex", component.getSelectedIndex()); - } - - } - - protected ActionConfigurationResolver resolveActionConfiguration(MyAbstractAction action) { - for (ActionConfigurationResolver resolver : configurationResolvers) { - if (resolver.resolveConfiguration(action) != null) { - return resolver; - } - } - return null; - } - - protected <I extends AbstractActionConfigurationResolver> I registerInitializer(Class<I> initizalizer) { - try { - I instance = initizalizer.newInstance(); - configurationResolvers.add(instance); - return instance; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public void fireAction0(String actionKey, Object source, A action) { - if (action == null) { - log.warn("could not find action " + actionKey); - return; - } - ActionEvent event = new ActionEvent(source, ActionEvent.ACTION_FIRST, actionKey); - action.actionPerformed(event); - } - - protected void checkRegistredAction(String actionKey) { - if (!impls.containsKey(actionKey)) { - throw new IllegalStateException("can not find a registered action for key " + actionKey); - } - } - - - @SuppressWarnings({"unchecked"}) - protected A newActionInstance(String actionKey) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { - Class<? extends MyAbstractAction> klazz = impls.get(actionKey); - MyAbstractAction result; - result = klazz.getConstructor(String.class).newInstance(actionKey); - result.putValue(Action.ACTION_COMMAND_KEY, actionKey); - if (!getBaseClass().isAssignableFrom(klazz)) { - // the instanciated action must be boxed in the base Action of the factory - result = getBaseClass().getConstructor(MyAbstractAction.class).newInstance(result); - } - return (A) result; - } - - - public Map<String, Class<? extends MyAbstractAction>> init() { - if (log.isDebugEnabled()) { - log.debug("start loading " + this); - } - URLClassLoader newCL = fixClassLoader(getClass()); - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - if (newCL != null) { - // replace current cl by our fiexed cl - Thread.currentThread().setContextClassLoader(newCL); - } - // obtain a ServiceLoader on ActionProvider - ServiceLoader<ActionProvider> loader = ServiceLoader.load(ActionProvider.class); - Map<String, Class<? extends MyAbstractAction>> cache = new TreeMap<String, Class<? extends MyAbstractAction>>(); - - for (ActionProvider<?> actionProvider : loader) { - if (log.isDebugEnabled()) { - log.debug("found " + actionProvider); - } - cache.putAll(actionProvider.getClasses()); - } - if (newCL != null) { - // to avoid side effects, push back old cl - Thread.currentThread().setContextClassLoader(cl); - } - return cache; - } - - /** - * Fix the class loader when application is launched from a java -jar - * The ServiceLoader seems not to find services from jar manifest... - * <p/> - * Our solution is to get all jar from the jar manifest and create a URLClassLoader, this is not perfect but works. - * <p/> - * TODO Put this nice code in a ServiceLoaderUtil in lutinutil... - * - * @param klass class to use to obtain classloader - * @return the fixed classloader - */ - public static URLClassLoader fixClassLoader(Class klass) { - ClassLoader l = klass.getClassLoader(); - URLClassLoader cl; - if (!(l instanceof URLClassLoader)) { - log.warn("using cl is not a URL classloader " + l); - cl = new URLClassLoader(new URL[0], l); - } else { - cl = (URLClassLoader) l; - } - if (cl.getURLs().length == 1) { - // come from a java -jar, must expand all jar to make possible ServiceLoader to work - try { - //todo put this in lutinutil ServiceLoaderUtil - URL[] urls = Resource.getClassPathURLsFromJarManifest(cl.getURLs()[0]); - URLClassLoader newCL = new URLClassLoader(urls); - if (log.isTraceEnabled()) { - for (URL url : newCL.getURLs()) { - log.trace(url); - } - } - return newCL; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - return null; - } - -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionFactoryFromProvider.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionFactoryFromProvider.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,470 @@ +/* +* ##% Copyright (C) 2007, 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.nuiton.jaxx.action; + +import jaxx.runtime.JAXXObject; +import jaxx.runtime.swing.JAXXToggleButton; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.Resource; + +import javax.swing.AbstractButton; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import java.awt.event.ActionEvent; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.ServiceLoader; +import java.util.Set; +import java.util.TreeMap; + +/** + * A simple implementation of {@link ActionFactory} using some {@link ActionProvider} to seek actions. + * <p/> + * <p/> + * An entry is in that form : <code>action.actionName=fqn</code> where + * <p/> + * <code>actionName</code> is the key of action used in factory, and + * <code>fqn</code> is the fully qualified name of the implemented action class. + * <p/> + * A special clase is to have for a given entry a key like this : <code>action.:fqn'=fqn</code>, in that case, + * le fqn' is a classe of type {@link org.nuiton.jaxx.action.ActionNameProvider} which gives us at + * runtime the names of each entry to put in cache for the givne action fqn. + * + * @param <A> the type of action + * @author chemit + */ +public class ActionFactoryFromProvider<A extends MyAbstractAction> implements ActionFactory<A> { + + protected static Log log = LogFactory.getLog(ActionFactoryFromProvider.class); + + public static <A extends MyAbstractAction> ActionFactory<A> newInstance(Class<A> klazz) { + return new ActionFactoryFromProvider<A>(klazz); + } + + /** class of encapsuling action */ + protected Class<A> baseImpl; + + /** dictionary of known actions implementations */ + private Map<String, Class<? extends MyAbstractAction>> impls; + + /** dictionary of instanciated actions */ + private Map<String, A> cache; + + protected final ActionConfigConfigurationResolver actionConfigInitializer; + protected final ToggleActionConfigConfigurationResolver toggleActionConfigInitializer; + protected final SelectActionConfigConfigurationResolver selectActionConfigInitializer; + + protected List<AbstractActionConfigurationResolver> configurationResolvers; + + protected ActionFactoryFromProvider(Class<A> baseImpl) { + this.baseImpl = baseImpl; + this.impls = init(); + this.cache = new TreeMap<String, A>(); + this.configurationResolvers = new java.util.ArrayList<AbstractActionConfigurationResolver>(); + + this.toggleActionConfigInitializer = registerInitializer(ToggleActionConfigConfigurationResolver.class); + this.actionConfigInitializer = registerInitializer(ActionConfigConfigurationResolver.class); + this.selectActionConfigInitializer = registerInitializer(SelectActionConfigConfigurationResolver.class); + } + + @Override + public Class<A> getBaseClass() { + return baseImpl; + } + + @Override + public void resetCache() { + cache.clear(); + } + + /*public A get(String actionKey) { + return cache.get(actionKey); + }*/ + + @Override + public void loadActions(JAXXObject ui) { + if (log.isDebugEnabled()) { + log.debug("for ui " + ui.getClass()); + } + for (Map.Entry<String, Class<? extends MyAbstractAction>> entry : implsEntrySet()) { + String actionKey = entry.getKey(); + Object comp = ui.getObjectById(actionKey); + if (comp == null || !(comp instanceof AbstractButton || comp instanceof JComboBox)) { + // nothing to do + continue; + } + if (log.isTraceEnabled()) { + log.trace("detect action " + actionKey); + } + if (comp instanceof AbstractButton) { + AbstractButton component = (AbstractButton) comp; + A action = newAction(actionKey, component); + + component.setAction(action); + + if (component instanceof JAXXToggleButton) { + JAXXToggleButton glueComponent = (JAXXToggleButton) component; + glueComponent.setIcon((Icon) action.getValue(Action.SMALL_ICON)); + Integer integer = (Integer) action.getValue(Action.MNEMONIC_KEY); + if (integer != null) { + glueComponent.setNormalMnemonic(integer); + } + glueComponent.setSelectedIcon((Icon) action.getValue(Action.SMALL_ICON + 2)); + integer = (Integer) action.getValue(Action.MNEMONIC_KEY + 2); + if (integer != null) { + glueComponent.setGlueMnemonic(integer); + } + glueComponent.setGlueText((String) action.getValue(Action.NAME + 2)); + glueComponent.setGlueTooltipText((String) action.getValue(Action.SHORT_DESCRIPTION + 2)); + + glueComponent.setNormalText((String) action.getValue(Action.NAME)); + glueComponent.setNormalTooltipText((String) action.getValue(Action.SHORT_DESCRIPTION)); + } + + Boolean value = (Boolean) action.getValue("hideActionText"); + component.setHideActionText(value != null && value); + action.setEnabled(true); + continue; + } + // is JComboBox + JComboBox component = (JComboBox) comp; + A action = newAction(actionKey, component); + + component.setAction(action); + Integer val = (Integer) action.getValue("selectedIndex"); + if (val != null && val != -1 && val < component.getItemCount() && val != component.getSelectedIndex()) { + component.setSelectedIndex(val); + } + } + } + + /** + * @param actionKey le nom de l'action tel que définie dans le fichier + * de mapping (sans le prefix action.) + * @param component le button où rattacher l'action + * @return une nouvelle instance de l'action associée à sa clef. + */ + @Override + public A newAction(String actionKey, JComponent component) { + // try first in cache + A result = getActionFromCache(actionKey); + if (result != null) { + return result; + } + + try { + result = newActionInstance(actionKey); + } catch (Exception e) { + throw new RuntimeException(e); + } + + if (log.isDebugEnabled()) { + log.debug("create <" + actionKey + " : " + result + ">"); + } + + // recherche de l'annotation de configuration + ActionConfigurationResolver<?, ?> configurationResolver = resolveActionConfiguration(result); + + if (configurationResolver != null) { + configurationResolver.applyConfiguration(component, result); + } + + try { + + if (configurationResolver != null) { + if (AbstractButton.class.isAssignableFrom(configurationResolver.getComponentImpl())) { + finalizeNewAction((AbstractButton) component, result, configurationResolver); + } + + if (JComboBox.class.isAssignableFrom(configurationResolver.getComponentImpl())) { + finalizeNewAction((JComboBox) component, result, configurationResolver); + } + + return result; + } + + if (component == null || component instanceof AbstractButton) { + finalizeNewAction((AbstractButton) component, result, configurationResolver); + return result; + } + + if (component instanceof JComboBox) { + finalizeNewAction((JComboBox) component, result, configurationResolver); + } + } finally { + // save result in cache + cache.put(actionKey, result); + } + + return result; + } + + @Override + public A newAction(String actionKey) { + return newAction(actionKey, null); + } + + @Override + public String[] getActionNames() { + return impls.keySet().toArray(new String[impls.size()]); + } + + @Override + public Set<Entry<String, Class<? extends MyAbstractAction>>> implsEntrySet() { + return impls.entrySet(); + } + + @Override + public Set<Entry<String, A>> cacheEntrySet() { + return cache.entrySet(); + } + + @Override + public void fireAction(String actionKey, Object source, JComponent component) { + A action = newAction(actionKey, component); + fireAction0(actionKey, source, action); + } + + @Override + public void fireAction(String actionKey, Object source) { + fireAction(actionKey, source, null); + } + + /** + * @param actionKey la clef de l'action + * @return l'action deja stockee dans le cache d'action, ou <code>null</code> si non trouvée. + */ + @Override + public A getActionFromCache(String actionKey) { + // on vérifie que l'action existe bien + checkRegistredAction(actionKey); + + A action = null; + // try in cache + if (cache.containsKey(actionKey)) { + // use cached action + action = cache.get(actionKey); + if (log.isDebugEnabled()) { + log.debug("use cache action " + action); + } + } + return action; + } + + @Override + public void dispose() { + if (log.isInfoEnabled()) { + log.info(this); + } + for (String actionKey : getActionNames()) { + MyAbstractAction action = getActionFromCache(actionKey); + if (action != null) { + action.disposeUI(); + } + } + resetCache(); + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + resetCache(); + impls.clear(); + } + + /** + * @param component le button où rattacher l'action + * @param action action + * @param configurationResolver initializer + */ + protected void finalizeNewAction(AbstractButton component, MyAbstractAction action, ActionConfigurationResolver<?, ?> configurationResolver) { + + if (configurationResolver == null) { + // no configurationResolver matching, + if (component != null) { + action.putValue(Action.ACTION_COMMAND_KEY, component.getName()); + action.putValue(Action.SHORT_DESCRIPTION, component.getToolTipText()); + action.putValue(Action.SMALL_ICON, component.getIcon()); + action.putValue(Action.NAME, component.getText()); + action.putValue(Action.MNEMONIC_KEY, component.getMnemonic()); + action.putValue("hideActionText", component.getHideActionText()); + if (component instanceof JAXXToggleButton) { + JAXXToggleButton glueComponent = (JAXXToggleButton) component; + action.putValue(Action.SHORT_DESCRIPTION, glueComponent.getNormalTooltipText()); + action.putValue(Action.NAME, glueComponent.getNormalText()); + action.putValue(Action.SMALL_ICON, glueComponent.getIcon()); + action.putValue(Action.MNEMONIC_KEY, glueComponent.getNormalMnemonic()); + action.putValue(Action.SHORT_DESCRIPTION + 2, glueComponent.getGlueTooltipText()); + action.putValue(Action.NAME + 2, glueComponent.getGlueText()); + action.putValue(Action.SMALL_ICON + 2, glueComponent.getSelectedIcon()); + action.putValue(Action.MNEMONIC_KEY + 2, glueComponent.getGlueMnemonic()); + } + } + + } + + String text = (String) action.getValue(Action.NAME); + Integer mnemo = (Integer) action.getValue(Action.MNEMONIC_KEY); + if (mnemo != null && mnemo != '\0') { + int pos = text.indexOf((char) mnemo.intValue()); + if (pos == -1) { + pos = text.indexOf(Character.toLowerCase((char) mnemo.intValue())); + } + action.putValue(Action.DISPLAYED_MNEMONIC_INDEX_KEY, pos); + } + + } + + /** + * @param component le select box où rattacher l'action + * @param action action + * @param configurationResolver initializer + */ + protected void finalizeNewAction(JComboBox component, MyAbstractAction action, ActionConfigurationResolver<?, ?> configurationResolver) { + + if (configurationResolver == null) { + action.putValue(Action.ACTION_COMMAND_KEY, component.getName()); + action.putValue(Action.SHORT_DESCRIPTION, component.getToolTipText()); + //result.putValue("selectedIndex", component.getSelectedIndex()); + } + + } + + protected ActionConfigurationResolver resolveActionConfiguration(MyAbstractAction action) { + for (ActionConfigurationResolver resolver : configurationResolvers) { + if (resolver.resolveConfiguration(action) != null) { + return resolver; + } + } + return null; + } + + protected <I extends AbstractActionConfigurationResolver> I registerInitializer(Class<I> initizalizer) { + try { + I instance = initizalizer.newInstance(); + configurationResolvers.add(instance); + return instance; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void fireAction0(String actionKey, Object source, A action) { + if (action == null) { + log.warn("could not find action " + actionKey); + return; + } + ActionEvent event = new ActionEvent(source, ActionEvent.ACTION_FIRST, actionKey); + action.actionPerformed(event); + } + + protected void checkRegistredAction(String actionKey) { + if (!impls.containsKey(actionKey)) { + throw new IllegalStateException("can not find a registered action for key " + actionKey); + } + } + + + @SuppressWarnings({"unchecked"}) + protected A newActionInstance(String actionKey) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + Class<? extends MyAbstractAction> klazz = impls.get(actionKey); + MyAbstractAction result; + result = klazz.getConstructor(String.class).newInstance(actionKey); + result.putValue(Action.ACTION_COMMAND_KEY, actionKey); + if (!getBaseClass().isAssignableFrom(klazz)) { + // the instanciated action must be boxed in the base Action of the factory + result = getBaseClass().getConstructor(MyAbstractAction.class).newInstance(result); + } + return (A) result; + } + + + public Map<String, Class<? extends MyAbstractAction>> init() { + if (log.isDebugEnabled()) { + log.debug("start loading " + this); + } + URLClassLoader newCL = fixClassLoader(getClass()); + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (newCL != null) { + // replace current cl by our fiexed cl + Thread.currentThread().setContextClassLoader(newCL); + } + // obtain a ServiceLoader on ActionProvider + ServiceLoader<ActionProvider> loader = ServiceLoader.load(ActionProvider.class); + Map<String, Class<? extends MyAbstractAction>> cache = new TreeMap<String, Class<? extends MyAbstractAction>>(); + + for (ActionProvider<?> actionProvider : loader) { + if (log.isDebugEnabled()) { + log.debug("found " + actionProvider); + } + cache.putAll(actionProvider.getClasses()); + } + if (newCL != null) { + // to avoid side effects, push back old cl + Thread.currentThread().setContextClassLoader(cl); + } + return cache; + } + + /** + * Fix the class loader when application is launched from a java -jar + * The ServiceLoader seems not to find services from jar manifest... + * <p/> + * Our solution is to get all jar from the jar manifest and create a URLClassLoader, this is not perfect but works. + * <p/> + * TODO Put this nice code in a ServiceLoaderUtil in lutinutil... + * + * @param klass class to use to obtain classloader + * @return the fixed classloader + */ + public static URLClassLoader fixClassLoader(Class<?> klass) { + ClassLoader l = klass.getClassLoader(); + URLClassLoader cl; + if (!(l instanceof URLClassLoader)) { + log.warn("using cl is not a URL classloader " + l); + cl = new URLClassLoader(new URL[0], l); + } else { + cl = (URLClassLoader) l; + } + if (cl.getURLs().length == 1) { + // come from a java -jar, must expand all jar to make possible ServiceLoader to work + try { + //todo put this in lutinutil ServiceLoaderUtil + URL[] urls = Resource.getClassPathURLsFromJarManifest(cl.getURLs()[0]); + URLClassLoader newCL = new URLClassLoader(urls); + if (log.isTraceEnabled()) { + for (URL url : newCL.getURLs()) { + log.trace(url); + } + } + return newCL; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return null; + } + +} \ No newline at end of file Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionNameProvider.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionNameProvider.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionNameProvider.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -12,7 +12,7 @@ * - Suite 330, Boston, MA 02111-1307, USA. * ##% */ -package org.codelutin.jaxx.action; +package org.nuiton.jaxx.action; /** * Contrat pour obtenir les noms d'une action de maniere dynamique. Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionProvider.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,35 +0,0 @@ -/** - * ##% 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.jaxx.action; - -/** - * Contract to be realized by a provider of Actions. - * <p/> - * A provider of actions is based on a certain type of {@link MyAbstractAction} (<code>A</code>) with an accessor - * {@link #getBaseClass()} and deliver some implementations of such actions indexed by their logical names via the - * method {#link #getClasses()}. - * - * @author chemit - * @see MyAbstractAction - */ -public interface ActionProvider<A extends MyAbstractAction> { - - /** @return the base classe of provided actions */ - Class<A> getBaseClass(); - - /** @return the provided actions classes */ - java.util.Map<String, Class<? extends A>> getClasses(); - -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionProvider.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProvider.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,36 @@ +/** + * ##% 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.nuiton.jaxx.action; + +/** + * Contract to be realized by a provider of Actions. + * <p/> + * A provider of actions is based on a certain type of {@link MyAbstractAction} (<code>A</code>) with an accessor + * {@link #getBaseClass()} and deliver some implementations of such actions indexed by their logical names via the + * method {#link #getClasses()}. + * + * @param <A> type of action boxed + * @author chemit + * @see MyAbstractAction + */ +public interface ActionProvider<A extends MyAbstractAction> { + + /** @return the base classe of provided actions */ + Class<A> getBaseClass(); + + /** @return the provided actions classes */ + java.util.Map<String, Class<? extends A>> getClasses(); + +} Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderAnnotation.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionProviderAnnotation.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderAnnotation.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -12,7 +12,7 @@ * - Suite 330, Boston, MA 02111-1307, USA. * ##% */ -package org.codelutin.jaxx.action; +package org.nuiton.jaxx.action; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionProviderFromProperties.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,135 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import static org.codelutin.i18n.I18n._; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -/** @author chemit */ -public class ActionProviderFromProperties<A extends MyAbstractAction> implements ActionProvider<A> { - - /** default prefix for an entryin mapping file. */ - protected static final String ACTION_KEY_PREFIX = "action."; - - protected static final String actionsFileLocation = "META-INF/jaxx-%1$s-actions.properties"; - - protected String propertiesPath; - - protected static Log log = LogFactory.getLog(ActionProviderFromProperties.class); - - protected Class<A> baseClass; - - protected Map<String, Class<? extends A>> actions; - - - protected ActionProviderFromProperties(Class<A> baseClass) { - - this.baseClass = baseClass; - this.propertiesPath = "/" + String.format(actionsFileLocation, baseClass.getSimpleName()); - this.actions = initCache(); - } - - public Class<A> getBaseClass() { - return baseClass; - } - - public Map<String, Class<? extends A>> getClasses() { - return actions; - } - - @Override - public String toString() { - return super.toString() + "<baseClass:" + baseClass.getSimpleName() + ">"; - } - - protected void clearCache() { - if (actions != null) { - actions.clear(); - actions = null; - } - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - clearCache(); - } - - @SuppressWarnings({"unchecked"}) - protected Map<String, Class<? extends A>> initCache() { - - InputStream inputStream = null; - - Properties properties = new Properties(); - - try { - inputStream = getClass().getResourceAsStream(propertiesPath); - if (inputStream == null) { - //throw new NullPointerException("could not find action file " + propertiesPath); - // actually, there is nothing to load, this is not an error - } else { - log.info("load " + propertiesPath); - properties.load(inputStream); - } - } catch (IOException e) { - String message = _("jaxx.error.load.actions.file", e.getMessage()); - log.warn(message); - throw new RuntimeException(message); - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - log.warn(_("jaxx.error.close.actions.file", e.getMessage())); - //throw new RuntimeException(_("jaxx.error.load.actions.file", e.getMessage())); - } - } - } - - Map<String, Class<? extends A>> cache = new TreeMap<String, Class<? extends A>>(); - int prefix = ACTION_KEY_PREFIX.length(); - for (Map.Entry<Object, Object> entry : properties.entrySet()) { - String key = entry.getKey() + ""; - String qfn = entry.getValue() + ""; - try { - Class<? extends A> implCass; - implCass = (Class<? extends A>) Class.forName(qfn); - String actionKey = key.substring(prefix); - if (actionKey.startsWith(":")) { - // this is a RuntimeActionNameProvider - Class<ActionNameProvider> klazz = (Class<ActionNameProvider>) Class.forName(actionKey.substring(1)); - for (String s : klazz.newInstance().getActionCommands()) { - log.debug("found action <" + s + " : " + implCass + ">"); - cache.put(s, implCass); - } - continue; - } - log.debug("found action <" + actionKey + " : " + implCass + ">"); - cache.put(actionKey, implCass); - } catch (Exception e) { - throw new RuntimeException(_("jaxx.error.load.actions.class", key, qfn), e); - } - } - - return cache; - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ActionProviderFromProperties.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ActionProviderFromProperties.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,135 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import static org.nuiton.i18n.I18n._; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + +/** @author chemit */ +public class ActionProviderFromProperties<A extends MyAbstractAction> implements ActionProvider<A> { + + /** default prefix for an entryin mapping file. */ + protected static final String ACTION_KEY_PREFIX = "action."; + + protected static final String actionsFileLocation = "META-INF/jaxx-%1$s-actions.properties"; + + protected String propertiesPath; + + protected static Log log = LogFactory.getLog(ActionProviderFromProperties.class); + + protected Class<A> baseClass; + + protected Map<String, Class<? extends A>> actions; + + + protected ActionProviderFromProperties(Class<A> baseClass) { + + this.baseClass = baseClass; + this.propertiesPath = "/" + String.format(actionsFileLocation, baseClass.getSimpleName()); + this.actions = initCache(); + } + + public Class<A> getBaseClass() { + return baseClass; + } + + public Map<String, Class<? extends A>> getClasses() { + return actions; + } + + @Override + public String toString() { + return super.toString() + "<baseClass:" + baseClass.getSimpleName() + ">"; + } + + protected void clearCache() { + if (actions != null) { + actions.clear(); + actions = null; + } + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + clearCache(); + } + + @SuppressWarnings({"unchecked"}) + protected Map<String, Class<? extends A>> initCache() { + + InputStream inputStream = null; + + Properties properties = new Properties(); + + try { + inputStream = getClass().getResourceAsStream(propertiesPath); + if (inputStream == null) { + //throw new NullPointerException("could not find action file " + propertiesPath); + // actually, there is nothing to load, this is not an error + } else { + log.info("load " + propertiesPath); + properties.load(inputStream); + } + } catch (IOException e) { + String message = _("jaxx.error.load.actions.file", e.getMessage()); + log.warn(message); + throw new RuntimeException(message); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + log.warn(_("jaxx.error.close.actions.file", e.getMessage())); + //throw new RuntimeException(_("jaxx.error.load.actions.file", e.getMessage())); + } + } + } + + Map<String, Class<? extends A>> cache = new TreeMap<String, Class<? extends A>>(); + int prefix = ACTION_KEY_PREFIX.length(); + for (Map.Entry<Object, Object> entry : properties.entrySet()) { + String key = entry.getKey() + ""; + String qfn = entry.getValue() + ""; + try { + Class<? extends A> implCass; + implCass = (Class<? extends A>) Class.forName(qfn); + String actionKey = key.substring(prefix); + if (actionKey.startsWith(":")) { + // this is a RuntimeActionNameProvider + Class<ActionNameProvider> klazz = (Class<ActionNameProvider>) Class.forName(actionKey.substring(1)); + for (String s : klazz.newInstance().getActionCommands()) { + log.debug("found action <" + s + " : " + implCass + ">"); + cache.put(s, implCass); + } + continue; + } + log.debug("found action <" + actionKey + " : " + implCass + ">"); + cache.put(actionKey, implCass); + } catch (Exception e) { + throw new RuntimeException(_("jaxx.error.load.actions.class", key, qfn), e); + } + } + + return cache; + } +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/MyAbstractAction.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,259 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import jaxx.runtime.JAXXObject; -import org.apache.commons.logging.LogFactory; -import static org.codelutin.i18n.I18n._; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JComponent; -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeListener; - -/** - * Action de base à utiliser pour encapsuler toutes les actions du système. - * <p/> - * Ces actions seront chargées par des {@link ActionProvider} et des {@link ActionFactory}. - * - * @author chemit - */ -public abstract class MyAbstractAction extends AbstractAction { - - protected static org.apache.commons.logging.Log log = LogFactory.getLog(MyAbstractAction.class); - - private static final long serialVersionUID = -810023044364620841L; - - protected ActionEvent e; - - protected MyAbstractAction delegate; - - protected abstract String getPrefix(); - - protected MyAbstractAction(String name) { - super(name); - } - - protected MyAbstractAction(MyAbstractAction delegate) { - super((String) delegate.getValue(Action.NAME)); - this.delegate = delegate; - } - - public void actionPerformed(java.awt.event.ActionEvent e) { - if (hasDelegate()) { - // delegate to real action - delegate.actionPerformed(e); - return; - } - log.debug("------------------------------------------------------------"); - log.debug("event : " + e); - log.debug("source : " + e.getSource()); - this.e = e; - try { - boolean accepted = beforeAction(e); - log.debug("action : " + this); - if (accepted) { - log.info(getActionName() + " (treate:" + accepted + ") : " + this); - } else { - log.debug(getActionName() + " (treate:" + accepted + ") : " + this); - } - if (accepted) { - doAction(e); - setStatus(_("jaxx.action.done", getName())); - updateUI(); - } - } catch (Exception e1) { - showError(e1); - } finally { - this.e = null; - // always clear action after use : actions are staless - clear(); - } - } - - public String getI18nToolTipText() { - if (hasDelegate()) { - return delegate.getI18nToolTipText(); - } - return getPrefix() + ".action." + getActionName() + ".tooltip"; - } - - public void updateUI() { - if (hasDelegate()) { - delegate.updateUI(); - } - // nothing by default - } - - public void disposeUI() { - if (hasDelegate()) { - delegate.disposeUI(); - } - // nothing by default - } - - public MyAbstractAction getDelegate() { - return delegate; - } - - public boolean hasDelegate() { - return delegate != null; - } - - protected String getName() { - return (String) getValue(NAME); - } - - protected String getActionName() { - return (String) getValue(ACTION_COMMAND_KEY); - } - - protected void setStatus(String status) { - // do nothing from here - if (log.isDebugEnabled()) { - log.debug(status); - } - } - - protected boolean beforeAction(ActionEvent evt) throws Exception { - boolean enabled = isEnabled(); - if (enabled && hasDelegate()) { - return delegate.beforeAction(evt); - } - return enabled; - } - - protected void doAction(ActionEvent evt) throws Exception { - if (hasDelegate()) { - delegate.doAction(evt); - } - // nothing by default - } - - protected JComponent getUIObject(String name, JAXXObject container) { - if (container == null) { - return null; - } - return (JComponent) container.getObjectById(name); - } - - protected void clear() { - if (hasDelegate()) { - delegate.clear(); - } - // nothing by default - } - - protected void showError(Exception e) { - log.error(e); - } - - // ----------------------------------------------------------------------------- - // --- super class delegate methods ------------------------------------------- - // ----------------------------------------------------------------------------- - - @Override - public Object getValue(String key) { - if (hasDelegate()) { - return delegate.getValue(key); - } - return super.getValue(key); - } - - @Override - public void putValue(String key, Object newValue) { - if (hasDelegate()) { - delegate.putValue(key, newValue); - } - super.putValue(key, newValue); - } - - @Override - public boolean isEnabled() { - if (hasDelegate()) { - return delegate.isEnabled(); - } - return super.isEnabled(); - } - - @Override - public void setEnabled(boolean newValue) { - if (hasDelegate()) { - delegate.setEnabled(newValue); - } - super.setEnabled(newValue); - } - - @Override - public Object[] getKeys() { - if (hasDelegate()) { - return getKeys(); - } - return super.getKeys(); - } - - @Override - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - if (hasDelegate()) { - delegate.firePropertyChange(propertyName, oldValue, newValue); - } - super.firePropertyChange(propertyName, oldValue, newValue); - } - - @Override - public synchronized void addPropertyChangeListener(PropertyChangeListener listener) { - if (hasDelegate()) { - delegate.addPropertyChangeListener(listener); - } - super.addPropertyChangeListener(listener); - } - - @Override - public synchronized void removePropertyChangeListener(PropertyChangeListener listener) { - if (hasDelegate()) { - delegate.removePropertyChangeListener(listener); - } - super.removePropertyChangeListener(listener); - } - - @Override - public synchronized PropertyChangeListener[] getPropertyChangeListeners() { - if (hasDelegate()) { - return delegate.getPropertyChangeListeners(); - } - return super.getPropertyChangeListeners(); - } - - @Override - protected Object clone() throws CloneNotSupportedException { - if (hasDelegate()) { - return clone(); - } - return super.clone(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(super.toString()); - if (hasDelegate()) { - sb.append("[delegate: ").append(delegate.toString()).append("]"); - } else { - sb.append("<key:").append(getActionName()).append(">"); - } - return sb.toString(); - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/MyAbstractAction.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/MyAbstractAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,260 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import jaxx.runtime.JAXXObject; +import org.apache.commons.logging.LogFactory; +import static org.nuiton.i18n.I18n._; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JComponent; +import java.awt.event.ActionEvent; +import java.beans.PropertyChangeListener; + +/** + * Action de base à utiliser pour encapsuler toutes les actions du système. + * <p/> + * Ces actions seront chargées par des {@link ActionProvider} et des {@link ActionFactory}. + * + * @author chemit + */ +public abstract class MyAbstractAction extends AbstractAction { + + protected static org.apache.commons.logging.Log log = LogFactory.getLog(MyAbstractAction.class); + + private static final long serialVersionUID = -810023044364620841L; + + protected ActionEvent e; + + protected MyAbstractAction delegate; + + protected abstract String getPrefix(); + + protected MyAbstractAction(String name) { + super(name); + } + + protected MyAbstractAction(MyAbstractAction delegate) { + super((String) delegate.getValue(Action.NAME)); + this.delegate = delegate; + } + + @Override + public void actionPerformed(java.awt.event.ActionEvent e) { + if (hasDelegate()) { + // delegate to real action + delegate.actionPerformed(e); + return; + } + log.debug("------------------------------------------------------------"); + log.debug("event : " + e); + log.debug("source : " + e.getSource()); + this.e = e; + try { + boolean accepted = beforeAction(e); + log.debug("action : " + this); + if (accepted) { + log.info(getActionName() + " (treate:" + accepted + ") : " + this); + } else { + log.debug(getActionName() + " (treate:" + accepted + ") : " + this); + } + if (accepted) { + doAction(e); + setStatus(_("jaxx.action.done", getName())); + updateUI(); + } + } catch (Exception e1) { + showError(e1); + } finally { + this.e = null; + // always clear action after use : actions are staless + clear(); + } + } + + public String getI18nToolTipText() { + if (hasDelegate()) { + return delegate.getI18nToolTipText(); + } + return getPrefix() + ".action." + getActionName() + ".tooltip"; + } + + public void updateUI() { + if (hasDelegate()) { + delegate.updateUI(); + } + // nothing by default + } + + public void disposeUI() { + if (hasDelegate()) { + delegate.disposeUI(); + } + // nothing by default + } + + public MyAbstractAction getDelegate() { + return delegate; + } + + public boolean hasDelegate() { + return delegate != null; + } + + protected String getName() { + return (String) getValue(NAME); + } + + protected String getActionName() { + return (String) getValue(ACTION_COMMAND_KEY); + } + + protected void setStatus(String status) { + // do nothing from here + if (log.isDebugEnabled()) { + log.debug(status); + } + } + + protected boolean beforeAction(ActionEvent evt) throws Exception { + boolean canContinue = isEnabled(); + if (canContinue && hasDelegate()) { + return delegate.beforeAction(evt); + } + return canContinue; + } + + protected void doAction(ActionEvent evt) throws Exception { + if (hasDelegate()) { + delegate.doAction(evt); + } + // nothing by default + } + + protected JComponent getUIObject(String name, JAXXObject container) { + if (container == null) { + return null; + } + return (JComponent) container.getObjectById(name); + } + + protected void clear() { + if (hasDelegate()) { + delegate.clear(); + } + // nothing by default + } + + protected void showError(Exception e) { + log.error(e); + } + + // ----------------------------------------------------------------------------- + // --- super class delegate methods ------------------------------------------- + // ----------------------------------------------------------------------------- + + @Override + public Object getValue(String key) { + if (hasDelegate()) { + return delegate.getValue(key); + } + return super.getValue(key); + } + + @Override + public void putValue(String key, Object newValue) { + if (hasDelegate()) { + delegate.putValue(key, newValue); + } + super.putValue(key, newValue); + } + + @Override + public boolean isEnabled() { + if (hasDelegate()) { + return delegate.isEnabled(); + } + return super.isEnabled(); + } + + @Override + public void setEnabled(boolean newValue) { + if (hasDelegate()) { + delegate.setEnabled(newValue); + } + super.setEnabled(newValue); + } + + @Override + public Object[] getKeys() { + if (hasDelegate()) { + return getKeys(); + } + return super.getKeys(); + } + + @Override + protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (hasDelegate()) { + delegate.firePropertyChange(propertyName, oldValue, newValue); + } + super.firePropertyChange(propertyName, oldValue, newValue); + } + + @Override + public synchronized void addPropertyChangeListener(PropertyChangeListener listener) { + if (hasDelegate()) { + delegate.addPropertyChangeListener(listener); + } + super.addPropertyChangeListener(listener); + } + + @Override + public synchronized void removePropertyChangeListener(PropertyChangeListener listener) { + if (hasDelegate()) { + delegate.removePropertyChangeListener(listener); + } + super.removePropertyChangeListener(listener); + } + + @Override + public synchronized PropertyChangeListener[] getPropertyChangeListeners() { + if (hasDelegate()) { + return delegate.getPropertyChangeListeners(); + } + return super.getPropertyChangeListeners(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + if (hasDelegate()) { + return clone(); + } + return super.clone(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()); + if (hasDelegate()) { + sb.append("[delegate: ").append(delegate.toString()).append("]"); + } else { + sb.append("<key:").append(getActionName()).append(">"); + } + return sb.toString(); + } +} Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfig.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/SelectActionConfig.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfig.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -16,7 +16,7 @@ * 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.jaxx.action; +package org.nuiton.jaxx.action; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -51,10 +51,10 @@ /** * @return the class to obtain at runtime the array of names to be used in actions mapping. * <p/> - * <b>Note : the special value {@link org.codelutin.jaxx.action.ActionNameProvider} is used to says not to used + * <b>Note : the special value {@link org.nuiton.jaxx.action.ActionNameProvider} is used to says not to used * œthis mecanism since we can not set a null value in a annotation</b> */ - Class<? extends ActionNameProvider> actionCommandProvider() default org.codelutin.jaxx.action.ActionNameProvider.class; + Class<? extends ActionNameProvider> actionCommandProvider() default org.nuiton.jaxx.action.ActionNameProvider.class; /** * @return la clef i18n du texte de l'action, si vide ignoré Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/SelectActionConfigConfigurationResolver.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,53 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import static org.codelutin.i18n.I18n._; - -import javax.swing.Action; -import javax.swing.JComboBox; - -/** - * Implementation of configuration's resolver for annotation {@link SelectActionConfig} - * - * @author chemit - */ -public class SelectActionConfigConfigurationResolver extends AbstractActionConfigurationResolver<SelectActionConfig, JComboBox> { - - public SelectActionConfigConfigurationResolver() { - super(SelectActionConfig.class, JComboBox.class); - } - - protected SelectActionConfig applyConfiguration0(JComboBox component, MyAbstractAction action) { - SelectActionConfig anno = resolveConfiguration(action); - if (anno == null) { - return null; - } - // inject les données - if (!anno.name().isEmpty()) { - action.putValue(Action.NAME, _(anno.name())); - } - if (!anno.shortDescription().isEmpty()) { - action.putValue(Action.SHORT_DESCRIPTION, _(anno.shortDescription())); - } else { - action.putValue(Action.SHORT_DESCRIPTION, _(component.getToolTipText())); - } - action.putValue("selectedIndex", anno.selectedIndex()); - //TODO Convert it from String action.putValue(Action.ACCELERATOR_KEY, anno.accelerator()); - action.setEnabled(anno.enabled()); - - return anno; - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/SelectActionConfigConfigurationResolver.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/SelectActionConfigConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,54 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import static org.nuiton.i18n.I18n._; + +import javax.swing.Action; +import javax.swing.JComboBox; + +/** + * Implementation of configuration's resolver for annotation {@link SelectActionConfig} + * + * @author chemit + */ +public class SelectActionConfigConfigurationResolver extends AbstractActionConfigurationResolver<SelectActionConfig, JComboBox> { + + public SelectActionConfigConfigurationResolver() { + super(SelectActionConfig.class, JComboBox.class); + } + + @Override + protected SelectActionConfig applyConfiguration0(JComboBox component, MyAbstractAction action) { + SelectActionConfig anno = resolveConfiguration(action); + if (anno == null) { + return null; + } + // inject les données + if (!anno.name().isEmpty()) { + action.putValue(Action.NAME, _(anno.name())); + } + if (!anno.shortDescription().isEmpty()) { + action.putValue(Action.SHORT_DESCRIPTION, _(anno.shortDescription())); + } else { + action.putValue(Action.SHORT_DESCRIPTION, _(component.getToolTipText())); + } + action.putValue("selectedIndex", anno.selectedIndex()); + //TODO Convert it from String action.putValue(Action.ACCELERATOR_KEY, anno.accelerator()); + action.setEnabled(anno.enabled()); + + return anno; + } +} \ No newline at end of file Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfig.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ToggleActionConfig.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfig.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -16,7 +16,7 @@ * 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.jaxx.action; +package org.nuiton.jaxx.action; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -49,10 +49,10 @@ /** * @return the class to obtain at runtime the array of names to be used in actions mapping. * <p/> - * <b>Note : the special value {@link org.codelutin.jaxx.action.ActionNameProvider} is used to says not to used + * <b>Note : the special value {@link org.nuiton.jaxx.action.ActionNameProvider} is used to says not to used * œthis mecanism since we can not set a null value in a annotation</b> */ - Class<? extends ActionNameProvider> actionCommandProvider() default org.codelutin.jaxx.action.ActionNameProvider.class; + Class<? extends ActionNameProvider> actionCommandProvider() default org.nuiton.jaxx.action.ActionNameProvider.class; /** * @return la clef i18n du texte de l'action, si vide ignoré Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ToggleActionConfigConfigurationResolver.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,79 +0,0 @@ -/** - * ##% 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.jaxx.action; - -import static org.codelutin.i18n.I18n._; - -import javax.swing.AbstractButton; -import javax.swing.Action; - -/** - * Implementation of configuration's resolver for annotation {@link ToggleActionConfig} - * - * @author chemit - */ -public class ToggleActionConfigConfigurationResolver extends AbstractActionConfigurationResolver<ToggleActionConfig, AbstractButton> { - - public ToggleActionConfigConfigurationResolver() { - super(ToggleActionConfig.class, AbstractButton.class); - } - - protected ToggleActionConfig applyConfiguration0(AbstractButton component, MyAbstractAction action) { - ToggleActionConfig anno = resolveConfiguration(action); - if (anno == null) { - return null; - } - // inject les données - if (!anno.name().isEmpty()) { - //System.out.println("found action with name : " + anno.name()); - action.putValue(Action.NAME, _(anno.name())); - } - if (!anno.name2().isEmpty()) { - //System.out.println("found action with name2 : " + anno.name2()); - action.putValue(Action.NAME + "2", _(anno.name2())); - } - - if (!anno.shortDescription().isEmpty()) { - action.putValue(Action.SHORT_DESCRIPTION, _(anno.shortDescription())); - } - if (!anno.shortDescription2().isEmpty()) { - action.putValue(Action.SHORT_DESCRIPTION + "2", _(anno.shortDescription2())); - } - - if (!anno.smallIcon().isEmpty()) { - action.putValue(Action.SMALL_ICON, org.codelutin.jaxx.util.UIHelper.createImageIcon(anno.smallIcon())); - } - if (!anno.smallIcon2().isEmpty()) { - action.putValue(Action.SMALL_ICON + "2", org.codelutin.jaxx.util.UIHelper.createImageIcon(anno.smallIcon2())); - } - - if (anno.mnemonic() != '\0') { - action.putValue(Action.MNEMONIC_KEY, anno.mnemonic()); - } else if (component != null) { - action.putValue(Action.MNEMONIC_KEY, component.getMnemonic()); - } - if (anno.mnemonic2() != '\0') { - action.putValue(Action.MNEMONIC_KEY + "2", anno.mnemonic2()); - } - //TODO Convert it from String action.putValue(Action.ACCELERATOR_KEY, anno.accelerator()); - - - action.putValue("hideActionText", anno.hideActionText()); - action.putValue(Action.SELECTED_KEY, anno.selected()); - action.setEnabled(anno.enabled()); - - return anno; - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/action/ToggleActionConfigConfigurationResolver.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/action/ToggleActionConfigConfigurationResolver.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,79 @@ +/** + * ##% 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.nuiton.jaxx.action; + +import static org.nuiton.i18n.I18n._; + +import javax.swing.AbstractButton; +import javax.swing.Action; + +/** + * Implementation of configuration's resolver for annotation {@link ToggleActionConfig} + * + * @author chemit + */ +public class ToggleActionConfigConfigurationResolver extends AbstractActionConfigurationResolver<ToggleActionConfig, AbstractButton> { + + public ToggleActionConfigConfigurationResolver() { + super(ToggleActionConfig.class, AbstractButton.class); + } + + protected ToggleActionConfig applyConfiguration0(AbstractButton component, MyAbstractAction action) { + ToggleActionConfig anno = resolveConfiguration(action); + if (anno == null) { + return null; + } + // inject les données + if (!anno.name().isEmpty()) { + //System.out.println("found action with name : " + anno.name()); + action.putValue(Action.NAME, _(anno.name())); + } + if (!anno.name2().isEmpty()) { + //System.out.println("found action with name2 : " + anno.name2()); + action.putValue(Action.NAME + "2", _(anno.name2())); + } + + if (!anno.shortDescription().isEmpty()) { + action.putValue(Action.SHORT_DESCRIPTION, _(anno.shortDescription())); + } + if (!anno.shortDescription2().isEmpty()) { + action.putValue(Action.SHORT_DESCRIPTION + "2", _(anno.shortDescription2())); + } + + if (!anno.smallIcon().isEmpty()) { + action.putValue(Action.SMALL_ICON, org.nuiton.jaxx.util.UIHelper.createImageIcon(anno.smallIcon())); + } + if (!anno.smallIcon2().isEmpty()) { + action.putValue(Action.SMALL_ICON + "2", org.nuiton.jaxx.util.UIHelper.createImageIcon(anno.smallIcon2())); + } + + if (anno.mnemonic() != '\0') { + action.putValue(Action.MNEMONIC_KEY, anno.mnemonic()); + } else if (component != null) { + action.putValue(Action.MNEMONIC_KEY, component.getMnemonic()); + } + if (anno.mnemonic2() != '\0') { + action.putValue(Action.MNEMONIC_KEY + "2", anno.mnemonic2()); + } + //TODO Convert it from String action.putValue(Action.ACCELERATOR_KEY, anno.accelerator()); + + + action.putValue("hideActionText", anno.hideActionText()); + action.putValue(Action.SELECTED_KEY, anno.selected()); + action.setEnabled(anno.enabled()); + + return anno; + } +} \ No newline at end of file Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabContentConfig.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/tab/TabContentConfig.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabContentConfig.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -16,7 +16,7 @@ * 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.jaxx.tab; +package org.nuiton.jaxx.tab; import jaxx.runtime.swing.JAXXTab; Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabFactory.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/tab/TabFactory.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabFactory.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -16,7 +16,7 @@ * 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.jaxx.tab; +package org.nuiton.jaxx.tab; import jaxx.runtime.JAXXObject; import jaxx.runtime.swing.JAXXTab; Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabModel.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/tab/TabModel.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/tab/TabModel.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -16,7 +16,7 @@ * 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.jaxx.tab; +package org.nuiton.jaxx.tab; import java.io.Serializable; Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/AbstractUIAction.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,53 +0,0 @@ -/** - * ##% 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.jaxx.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** @author chemit */ -public abstract class AbstractUIAction<H extends DialogUIHandler<?, ?>> extends javax.swing.AbstractAction { - - protected static Log log = LogFactory.getLog(AbstractUIAction.class); - - protected transient DialogUI<? extends H> ui; - - private static final long serialVersionUID = 1L; - - protected AbstractUIAction(String name, javax.swing.Icon icon, DialogUI<? extends H> ui) { - super(name, icon); - this.ui = ui; - } - - protected H getHandler() { - checkInit(); - return ui.getHandler(); - } - - protected void setUi(DialogUI<? extends H> ui) { - this.ui = ui; - } - - public DialogUI<? extends H> getUi() { - return ui; - } - - protected void checkInit() throws IllegalStateException { - /*if (ui == null) { - throw new IllegalStateException("no handler, nor ui referenced in " + this); - } */ - } - -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/AbstractUIAction.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/AbstractUIAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,55 @@ +/** + * ##% 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.nuiton.jaxx.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * @param <H> type of handler + * @author chemit */ +public abstract class AbstractUIAction<H extends DialogUIHandler<?, ?>> extends javax.swing.AbstractAction { + + protected static Log log = LogFactory.getLog(AbstractUIAction.class); + + protected transient DialogUI<? extends H> ui; + + private static final long serialVersionUID = 1L; + + protected AbstractUIAction(String name, javax.swing.Icon icon, DialogUI<? extends H> ui) { + super(name, icon); + this.ui = ui; + } + + protected H getHandler() { + checkInit(); + return ui.getHandler(); + } + + protected void setUi(DialogUI<? extends H> ui) { + this.ui = ui; + } + + public DialogUI<? extends H> getUi() { + return ui; + } + + protected void checkInit() throws IllegalStateException { + /*if (ui == null) { + throw new IllegalStateException("no handler, nor ui referenced in " + this); + } */ + } + +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUI.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,129 +0,0 @@ -/** - * ##% 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.jaxx.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.ImageIcon; -import javax.swing.JDialog; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.lang.reflect.Constructor; - -/** - * A abstract dialog contract to be realised by a dialogUI (WindowEvent adapter) - * <p/> - * TODO : make jaxx authorized implementing interface for root tag :) - * - * @author chemit - */ -public abstract class DialogUI<H extends DialogUIHandler> extends JDialog implements WindowListener { - - protected static Log log = LogFactory.getLog(DialogUI.class); - - public javax.swing.AbstractAction newAction(Class<?> actionClass, Object... params) { - Constructor<?> constructor = null; - for (Constructor<?> cons : actionClass.getConstructors()) { - Class<?>[] prototype = cons.getParameterTypes(); - if (prototype.length > 0 && DialogUI.class.isAssignableFrom(prototype[0])) { - // use this constructor - constructor = cons; - break; - } - } - if (constructor == null) { - throw new IllegalStateException("could not find a matching constructor for " + actionClass); - } - - // wrap params - Object[] parameters = new Object[1 + params.length]; - parameters[0] = this; - System.arraycopy(params, 0, parameters, 1, params.length); - try { - AbstractAction action = (AbstractAction) constructor.newInstance(parameters); - if (log.isInfoEnabled()) { - log.info(action); - } - return action; - } catch (Exception e) { - throw new IllegalStateException("could not init the action " + actionClass + " for reason : " + e.getMessage()); - } - } - - private H handler; - - public abstract AbstractButton getHelp(); - - public abstract Object getObjectById(java.lang.String s); - - protected DialogUI() { - UIHelper.setQuitAction(this); - addWindowListener(this); - //TODO will be handled by jaxx with javax.help... - //getHelp().setAction(newAction(HelpAction.class)); - } - - public H getHandler() { - return handler; - } - - public void setHandler(H handler) { - this.handler = handler; - } - - protected ImageIcon createActionIcon(String name) { - return UIHelper.createActionIcon(name); - } - - public void windowOpened(WindowEvent e) { - } - - public void windowClosed(WindowEvent e) { - } - - public void windowClosing(WindowEvent e) { - } - - public void windowIconified(WindowEvent e) { - } - - public void windowDeiconified(WindowEvent e) { - } - - public void windowActivated(WindowEvent e) { - } - - public void windowDeactivated(WindowEvent e) { - } - - @Override - public synchronized void addWindowListener(WindowListener l) { - super.addWindowListener(l); - if (log.isDebugEnabled()) { - log.debug("after added (" + getWindowListeners().length + ") : " + l); - } - } - - @Override - public synchronized void removeWindowListener(WindowListener l) { - super.removeWindowListener(l); - if (log.isDebugEnabled()) { - log.debug("after removed (" + getWindowListeners().length + ") : " + l); - } - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUI.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUI.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,137 @@ +/** + * ##% 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.nuiton.jaxx.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import javax.swing.AbstractButton; +import javax.swing.ImageIcon; +import javax.swing.JDialog; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.lang.reflect.Constructor; + +/** + * A abstract dialog contract to be realised by a dialogUI (WindowEvent adapter) + * <p/> + * TODO : make jaxx authorized implementing interface for root tag :) + * + * @param <H> type of handler + * @author chemit + */ +public abstract class DialogUI<H extends DialogUIHandler<?,?>> extends JDialog implements WindowListener { + + protected static Log log = LogFactory.getLog(DialogUI.class); + + public javax.swing.AbstractAction newAction(Class<?> actionClass, Object... params) { + Constructor<?> constructor = null; + for (Constructor<?> cons : actionClass.getConstructors()) { + Class<?>[] prototype = cons.getParameterTypes(); + if (prototype.length > 0 && DialogUI.class.isAssignableFrom(prototype[0])) { + // use this constructor + constructor = cons; + break; + } + } + if (constructor == null) { + throw new IllegalStateException("could not find a matching constructor for " + actionClass); + } + + // wrap params + Object[] parameters = new Object[1 + params.length]; + parameters[0] = this; + System.arraycopy(params, 0, parameters, 1, params.length); + try { + AbstractAction action = (AbstractAction) constructor.newInstance(parameters); + if (log.isInfoEnabled()) { + log.info(action); + } + return action; + } catch (Exception e) { + throw new IllegalStateException("could not init the action " + actionClass + " for reason : " + e.getMessage()); + } + } + + private H handler; + + public abstract AbstractButton getHelp(); + + public abstract Object getObjectById(java.lang.String s); + + protected DialogUI() { + UIHelper.setQuitAction(this); + addWindowListener(this); + //TODO will be handled by jaxx with javax.help... + //getHelp().setAction(newAction(HelpAction.class)); + } + + public H getHandler() { + return handler; + } + + public void setHandler(H handler) { + this.handler = handler; + } + + protected ImageIcon createActionIcon(String name) { + return UIHelper.createActionIcon(name); + } + + @Override + public void windowOpened(WindowEvent e) { + } + + @Override + public void windowClosed(WindowEvent e) { + } + + @Override + public void windowClosing(WindowEvent e) { + } + + @Override + public void windowIconified(WindowEvent e) { + } + + @Override + public void windowDeiconified(WindowEvent e) { + } + + @Override + public void windowActivated(WindowEvent e) { + } + + @Override + public void windowDeactivated(WindowEvent e) { + } + + @Override + public synchronized void addWindowListener(WindowListener l) { + super.addWindowListener(l); + if (log.isDebugEnabled()) { + log.debug("after added (" + getWindowListeners().length + ") : " + l); + } + } + + @Override + public synchronized void removeWindowListener(WindowListener l) { + super.removeWindowListener(l); + if (log.isDebugEnabled()) { + log.debug("after removed (" + getWindowListeners().length + ") : " + l); + } + } +} \ No newline at end of file Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUIDef.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,235 +0,0 @@ -/** - * ##% 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.jaxx.util; - -import static org.codelutin.i18n.I18n._; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.ImageIcon; -import java.lang.reflect.Constructor; - -/** - * Definition of an ui, with his model, handler and ui class definitions. - * <p/> - * The class contains also a shared instace of concrete ui. - * - * @author chemit - */ -public class DialogUIDef<M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> implements java.io.Serializable { - - static protected final Log log = LogFactory.getLog(DialogUIDef.class); - - public static <M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> DialogUIDef<M, U, H> newDef(Class<H> handlerClass, Class<U> uiClass, Class<M> modelClass, String showActionLibelle, String showActionTip, String uiTitle) { - DialogUIDef<M, U, H> result; - result = new DialogUIDef<M, U, H>(handlerClass, uiClass, modelClass, showActionLibelle, showActionTip, uiTitle); - return result; - } - - /** - * model class - */ - private final Class<M> modelClass; - - /** - * handler class - */ - private final Class<H> handlerClass; - - /** - * abstract ui class - */ - private final Class<U> uiClass; - - /** - * concrete lookup ui class - */ - private Class<? extends U> uiImplClass; - - /** - * shared instance of ui - */ - protected U uiInstance; - - /** - * unique name of ui def - */ - protected final String name; - - protected final String uiTitle; - protected final String showActionLibelle; - protected final String showActionTip; - - protected ImageIcon showUIActionIcon; - - - private static final long serialVersionUID = 1L; - - private DialogUIDef(Class<H> handlerClass, Class<U> uiClass, Class<M> modelClass, - String showActionLibelle, String showActionTip, String uiTitle) { - this.handlerClass = handlerClass; - this.uiClass = uiClass; - this.modelClass = modelClass; - this.showActionLibelle = showActionLibelle; - this.name = uiClass.getSimpleName().toLowerCase(); - this.showActionTip = showActionTip; - this.uiTitle = uiTitle; - } - - public Class<U> getUiClass() { - return uiClass; - } - - public Class<H> getHandlerClass() { - return handlerClass; - } - - public Class<M> getModelClass() { - return modelClass; - } - - public Class<? extends U> getUiImplClass() { - return uiImplClass; - } - - public String getUiTitle() { - return _(uiTitle); - } - - public String getShowActionLibelle() { - return _(showActionLibelle); - } - - public String getShowActionTip() { - return _(showActionTip); - } - - public ImageIcon getShowUIActionIcon() { - if (showUIActionIcon == null) { - showUIActionIcon = UIHelper.createActionIcon("show-" + name); - } - return showUIActionIcon; - } - - @SuppressWarnings({"unchecked"}) - public void setUiImplClass(Class<?> uiImplClass) { - this.uiImplClass = (Class<? extends U>) uiImplClass; - } - - @Override - public boolean equals(Object o) { - return this == o || o instanceof DialogUIDef && uiClass.equals(((DialogUIDef) o).uiClass); - } - - @Override - public int hashCode() { - return uiClass.hashCode(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(super.toString()).append('<'); - sb.append(printClass("handler", handlerClass, true)); - sb.append(printClass("model", modelClass, true)); - sb.append(printClass("ui", uiClass, true)); - sb.append(printClass("uiImpl", uiImplClass, false)); - return sb.toString(); - } - - protected U getUiInstance() { - // no lazy instanciation, to control ui instanciation... - /*if (uiInstance == null) { - if (uiImplClass == null) { - throw new IllegalStateException("no concrete ui impl found in " + this); - } - synchronized (this) { - try { - uiInstance = uiImplClass.newInstance(); - } catch (Exception e) { - throw new IllegalStateException("could not instanciate ui " + this,e); - } - } - }*/ - return uiInstance; - } - - protected void setUiInstance(U uiInstance) { - this.uiInstance = uiInstance; - } - - protected U newUI() { - if (uiImplClass == null) { - throw new IllegalStateException("no concrete ui impl found in " + this); - } - try { - U result = uiImplClass.newInstance(); - log.info(result); - return result; - } catch (Exception e) { - throw new IllegalStateException("could not instanciate ui " + this, e); - } - } - - protected M newModel() { - if (modelClass == null) { - throw new IllegalStateException("no model impl found in " + this); - } - try { - M model = modelClass.newInstance(); - log.info(model); - return model; - } catch (Exception e) { - throw new IllegalStateException("could not instanciate ui " + this, e); - } - } - - protected H newHandler(U ui, M model, Object... params) { - if (handlerClass == null) { - throw new IllegalStateException("no handler impl found in " + this); - } - try { - Class[] prototype = getHandlerPrototype(params); - Object[] parameters = getHandlerParameters(ui, model, params); - H result = handlerClass.getConstructor(prototype).newInstance(parameters); - log.info(result); - return result; - } catch (Exception e) { - throw new IllegalStateException("could not instanciate ui " + this, e); - } - } - - protected Object[] getHandlerParameters(U ui, M model, Object[] params) { - Object[] result = new Object[2 + params.length]; - result[0] = ui; - result[1] = model; - System.arraycopy(params, 0, result, 2, params.length); - return result; - } - - protected Class[] getHandlerPrototype(Object[] params) { - int length = params.length; - for (Constructor<?> constructor : handlerClass.getConstructors()) { - Class<?>[] prototype = constructor.getParameterTypes(); - if (prototype.length == 2 + length && prototype[0] == uiClass && prototype[1] == modelClass) { - return prototype; - } - } - throw new IllegalStateException("could not find a matching constructor in " + handlerClass); - } - - protected String printClass(String s, Class<?> aClass, boolean notLast) { - return s + ':' + (aClass == null ? null : aClass.getSimpleName()) + (notLast ? ", " : ">"); - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUIDef.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIDef.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,238 @@ +/** + * ##% 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.nuiton.jaxx.util; + +import static org.nuiton.i18n.I18n._; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.ImageIcon; +import java.lang.reflect.Constructor; + +/** + * Definition of an ui, with his model, handler and ui class definitions. + * <p/> + * The class contains also a shared instace of concrete ui. + * + * @param <M> type of model + * @param <U> type of ui + * @param <H> type of handler + * @author chemit + */ +public class DialogUIDef<M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> implements java.io.Serializable { + + static protected final Log log = LogFactory.getLog(DialogUIDef.class); + + public static <M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> DialogUIDef<M, U, H> newDef(Class<H> handlerClass, Class<U> uiClass, Class<M> modelClass, String showActionLibelle, String showActionTip, String uiTitle) { + DialogUIDef<M, U, H> result; + result = new DialogUIDef<M, U, H>(handlerClass, uiClass, modelClass, showActionLibelle, showActionTip, uiTitle); + return result; + } + + /** + * model class + */ + private final Class<M> modelClass; + + /** + * handler class + */ + private final Class<H> handlerClass; + + /** + * abstract ui class + */ + private final Class<U> uiClass; + + /** + * concrete lookup ui class + */ + private Class<? extends U> uiImplClass; + + /** + * shared instance of ui + */ + protected U uiInstance; + + /** + * unique name of ui def + */ + protected final String name; + + protected final String uiTitle; + protected final String showActionLibelle; + protected final String showActionTip; + + protected ImageIcon showUIActionIcon; + + + private static final long serialVersionUID = 1L; + + private DialogUIDef(Class<H> handlerClass, Class<U> uiClass, Class<M> modelClass, + String showActionLibelle, String showActionTip, String uiTitle) { + this.handlerClass = handlerClass; + this.uiClass = uiClass; + this.modelClass = modelClass; + this.showActionLibelle = showActionLibelle; + this.name = uiClass.getSimpleName().toLowerCase(); + this.showActionTip = showActionTip; + this.uiTitle = uiTitle; + } + + public Class<U> getUiClass() { + return uiClass; + } + + public Class<H> getHandlerClass() { + return handlerClass; + } + + public Class<M> getModelClass() { + return modelClass; + } + + public Class<? extends U> getUiImplClass() { + return uiImplClass; + } + + public String getUiTitle() { + return _(uiTitle); + } + + public String getShowActionLibelle() { + return _(showActionLibelle); + } + + public String getShowActionTip() { + return _(showActionTip); + } + + public ImageIcon getShowUIActionIcon() { + if (showUIActionIcon == null) { + showUIActionIcon = UIHelper.createActionIcon("show-" + name); + } + return showUIActionIcon; + } + + @SuppressWarnings({"unchecked"}) + public void setUiImplClass(Class<?> uiImplClass) { + this.uiImplClass = (Class<? extends U>) uiImplClass; + } + + @Override + public boolean equals(Object o) { + return this == o || o instanceof DialogUIDef<?,?,?> && uiClass.equals(((DialogUIDef<?,?,?>) o).uiClass); + } + + @Override + public int hashCode() { + return uiClass.hashCode(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(super.toString()).append('<'); + sb.append(printClass("handler", handlerClass, true)); + sb.append(printClass("model", modelClass, true)); + sb.append(printClass("ui", uiClass, true)); + sb.append(printClass("uiImpl", uiImplClass, false)); + return sb.toString(); + } + + protected U getUiInstance() { + // no lazy instanciation, to control ui instanciation... + /*if (uiInstance == null) { + if (uiImplClass == null) { + throw new IllegalStateException("no concrete ui impl found in " + this); + } + synchronized (this) { + try { + uiInstance = uiImplClass.newInstance(); + } catch (Exception e) { + throw new IllegalStateException("could not instanciate ui " + this,e); + } + } + }*/ + return uiInstance; + } + + protected void setUiInstance(U uiInstance) { + this.uiInstance = uiInstance; + } + + protected U newUI() { + if (uiImplClass == null) { + throw new IllegalStateException("no concrete ui impl found in " + this); + } + try { + U result = uiImplClass.newInstance(); + log.info(result); + return result; + } catch (Exception e) { + throw new IllegalStateException("could not instanciate ui " + this, e); + } + } + + protected M newModel() { + if (modelClass == null) { + throw new IllegalStateException("no model impl found in " + this); + } + try { + M model = modelClass.newInstance(); + log.info(model); + return model; + } catch (Exception e) { + throw new IllegalStateException("could not instanciate ui " + this, e); + } + } + + protected H newHandler(U ui, M model, Object... params) { + if (handlerClass == null) { + throw new IllegalStateException("no handler impl found in " + this); + } + try { + Class<?>[] prototype = getHandlerPrototype(params); + Object[] parameters = getHandlerParameters(ui, model, params); + H result = handlerClass.getConstructor(prototype).newInstance(parameters); + log.info(result); + return result; + } catch (Exception e) { + throw new IllegalStateException("could not instanciate ui " + this, e); + } + } + + protected Object[] getHandlerParameters(U ui, M model, Object[] params) { + Object[] result = new Object[2 + params.length]; + result[0] = ui; + result[1] = model; + System.arraycopy(params, 0, result, 2, params.length); + return result; + } + + protected Class<?>[] getHandlerPrototype(Object[] params) { + int length = params.length; + for (Constructor<?> constructor : handlerClass.getConstructors()) { + Class<?>[] prototype = constructor.getParameterTypes(); + if (prototype.length == 2 + length && prototype[0] == uiClass && prototype[1] == modelClass) { + return prototype; + } + } + throw new IllegalStateException("could not find a matching constructor in " + handlerClass); + } + + protected String printClass(String s, Class<?> aClass, boolean notLast) { + return s + ':' + (aClass == null ? null : aClass.getSimpleName()) + (notLast ? ", " : ">"); + } +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUIHandler.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,70 +0,0 @@ -/** - * ##% 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.jaxx.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.event.WindowListener; -import java.beans.PropertyChangeListener; - -/** - * DialogUI handler - * - * @author chemit - */ -public abstract class DialogUIHandler<M extends DialogUIModel, U extends DialogUI<? extends DialogUIHandler>> implements PropertyChangeListener { - - protected static Log log = LogFactory.getLog(DialogUIHandler.class); - - /** ui handled */ - private U ui; - - /** model handled */ - private M model; - - protected DialogUIHandler(U ui, M model) { - this.ui = ui; - this.model = model; - } - - public U getUi() { - return ui; - } - - public M getModel() { - return model; - } - - public void init() { - if (model == null) { - throw new IllegalStateException("no model was defined for " + this); - } - model.addPropertyChangeListener(this); - } - - public void dispose() { - model.dispose(); - for (WindowListener windowListener : getUi().getWindowListeners()) { - getUi().removeWindowListener(windowListener); - } - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - dispose(); - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUIHandler.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIHandler.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,72 @@ +/** + * ##% 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.nuiton.jaxx.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.event.WindowListener; +import java.beans.PropertyChangeListener; + +/** + * DialogUI handler + * + * @param <M> type of model + * @param <U> type of ui + * @author chemit + */ +public abstract class DialogUIHandler<M extends DialogUIModel, U extends DialogUI<? extends DialogUIHandler<?,?>>> implements PropertyChangeListener { + + protected static Log log = LogFactory.getLog(DialogUIHandler.class); + + /** ui handled */ + private U ui; + + /** model handled */ + private M model; + + protected DialogUIHandler(U ui, M model) { + this.ui = ui; + this.model = model; + } + + public U getUi() { + return ui; + } + + public M getModel() { + return model; + } + + public void init() { + if (model == null) { + throw new IllegalStateException("no model was defined for " + this); + } + model.addPropertyChangeListener(this); + } + + public void dispose() { + model.dispose(); + for (WindowListener windowListener : getUi().getWindowListeners()) { + getUi().removeWindowListener(windowListener); + } + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + dispose(); + } +} \ No newline at end of file Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIModel.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/DialogUIModel.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/DialogUIModel.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -12,7 +12,7 @@ * - Suite 330, Boston, MA 02111-1307, USA. * ##% */ -package org.codelutin.jaxx.util; +package org.nuiton.jaxx.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/FactoryWindowListener.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,84 +0,0 @@ -/** - * ##% 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.jaxx.util; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -/** - * A windowListenr for ui managed by {@link org.codelutin.jaxx.util.UIFactory}. - * <p/> - * To be used when all ui from factory are closed, via {@link #allWindowsClosed(java.awt.event.WindowEvent)} method. - * - * @author chemit - */ -public abstract class FactoryWindowListener extends WindowAdapter { - - /** - * method to be invoked when all ui registred in factory are really disposed. - * - * @param e event - */ - public abstract void allWindowsClosed(WindowEvent e); - - /** underlying factory of ui */ - private UIFactory factory; - - /** flag to make sure {@link #allWindowsClosed(java.awt.event.WindowEvent)} is called only once. */ - private boolean wasClosed; - - @Override - public void windowClosed(WindowEvent e) { - if (UIFactory.log.isDebugEnabled()) { - UIFactory.log.debug(this + " : " + e); - } - if (e.getWindow().isVisible()) { - // only deal with real closed and none visible windows... - return; - } - for (DialogUIDef def : factory.getDefs()) { - DialogUI ui = def.uiInstance; - if (ui != null && ui.isVisible()) { - // at least one ui visible, do not close all - return; - } - } - - if (wasClosed) { - // make sure to process only once - return; - } - if (UIFactory.log.isInfoEnabled()) { - UIFactory.log.info("closing factory listener " + this); - } - - synchronized (this) { - try { - allWindowsClosed(e); - } finally { - wasClosed = true; - factory.removeFactoryWindowListener(this); - } - } - } - - protected UIFactory getFactory() { - return factory; - } - - protected void setFactory(UIFactory factory) { - this.factory = factory; - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/FactoryWindowListener.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FactoryWindowListener.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,84 @@ +/** + * ##% 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.nuiton.jaxx.util; + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +/** + * A windowListenr for ui managed by {@link org.nuiton.jaxx.util.UIFactory}. + * <p/> + * To be used when all ui from factory are closed, via {@link #allWindowsClosed(java.awt.event.WindowEvent)} method. + * + * @author chemit + */ +public abstract class FactoryWindowListener extends WindowAdapter { + + /** + * method to be invoked when all ui registred in factory are really disposed. + * + * @param e event + */ + public abstract void allWindowsClosed(WindowEvent e); + + /** underlying factory of ui */ + private UIFactory factory; + + /** flag to make sure {@link #allWindowsClosed(java.awt.event.WindowEvent)} is called only once. */ + private boolean wasClosed; + + @Override + public void windowClosed(WindowEvent e) { + if (UIFactory.log.isDebugEnabled()) { + UIFactory.log.debug(this + " : " + e); + } + if (e.getWindow().isVisible()) { + // only deal with real closed and none visible windows... + return; + } + for (DialogUIDef<?,?,?> def : factory.getDefs()) { + DialogUI<?> ui = def.uiInstance; + if (ui != null && ui.isVisible()) { + // at least one ui visible, do not close all + return; + } + } + + if (wasClosed) { + // make sure to process only once + return; + } + if (UIFactory.log.isInfoEnabled()) { + UIFactory.log.info("closing factory listener " + this); + } + + synchronized (this) { + try { + allWindowsClosed(e); + } finally { + wasClosed = true; + factory.removeFactoryWindowListener(this); + } + } + } + + protected UIFactory getFactory() { + return factory; + } + + protected void setFactory(UIFactory factory) { + this.factory = factory; + } +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/FormElement.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,29 +0,0 @@ -/** - * ##% 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.jaxx.util; - -/** @author chemit */ -public interface FormElement<U extends DialogUI> { - - String name(); - - int ordinal(); - - Object getValue(U ui); - - void setValue(U ui, String value); - - javax.swing.JLabel getLabel(U ui); -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/FormElement.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/FormElement.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,31 @@ +/** + * ##% 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.nuiton.jaxx.util; + +/** + * @param <U> type of dialog + * @author chemit */ +public interface FormElement<U extends DialogUI<?>> { + + String name(); + + int ordinal(); + + Object getValue(U ui); + + void setValue(U ui, String value); + + javax.swing.JLabel getLabel(U ui); +} Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/ShowUIAction.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,135 +0,0 @@ -/** - * ##% 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.jaxx.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.ActionEvent; - -/** @author chemit */ -public abstract class ShowUIAction<M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> extends javax.swing.AbstractAction { - - protected static Log log = LogFactory.getLog(AbstractUIAction.class); - - protected transient DialogUI<?> ui; - - private static final long serialVersionUID = 1L; - - protected DialogUIDef<M, U, H> uiDef; - - protected transient UIFactory factory; - - protected String position; - - protected boolean undecorated = true; - - protected U initUI(ActionEvent e) { - return getFactory().getUI(uiDef); - } - - public ShowUIAction(DialogUI<?> ui, DialogUIDef<M, U, H> uiDef, UIFactory factory, boolean showText) { - super(uiDef.getShowActionLibelle(), uiDef.getShowUIActionIcon()); - this.ui = ui; - this.uiDef = uiDef; - String name = (String) getValue(NAME); - putValue(DISPLAYED_MNEMONIC_INDEX_KEY, name.length() - 1); - putValue(ACCELERATOR_KEY, (int) name.charAt(name.length() - 1)); - if (!showText) { - putValue(NAME, null); - } - putValue(SHORT_DESCRIPTION, uiDef.getShowActionTip()); - this.factory = factory; - } - - public DialogUI<?> getUi() { - return ui; - } - - public DialogUIDef<M, U, H> getUiDef() { - return uiDef; - } - - public UIFactory getFactory() { - return factory; - } - - public void setUiDef(DialogUIDef<M, U, H> uiDef) { - this.uiDef = uiDef; - } - - public void setPosition(String position) { - this.position = position; - } - - public void setUndecorated(boolean undecorated) { - this.undecorated = undecorated; - } - - public void actionPerformed(java.awt.event.ActionEvent e) { - checkInit(); - U ui = initUI(e); - ui.setTitle(uiDef.getUiTitle()); - log.info(ui.getTitle()); - //TODO ui.setUndecorated(undecorated); - setPosition(this.getUi(), ui, position); - - ui.setVisible(true); - } - - protected void setPosition(javax.swing.JDialog parentUI, javax.swing.JDialog ui, String position) { - if (position == null || parentUI == null) { - return; - } - Point parentLocation = parentUI.getLocationOnScreen(); - Dimension parentSize = parentUI.getSize(); - - if (position.equals("bottom-left")) { - int top = (int) (parentLocation.getY() + parentSize.getHeight()); - int left = (int) (parentLocation.getX()); - Point newLocation = new Point(left, top); - newLocation.setLocation(left, top); - ui.setLocation(newLocation); - return; - } - if (position.equals("top-left")) { - int top = (int) (parentLocation.getY()); - int left = (int) (parentLocation.getX()); - Point newLocation = new Point(left, top); - newLocation.setLocation(left, top); - ui.setLocation(newLocation); - return; - } - if (position.equals("top-right")) { - int top = (int) (parentLocation.getY()); - int left = (int) (parentLocation.getX() + parentSize.getWidth()); - Point newLocation = new Point(left, top); - newLocation.setLocation(left, top); - ui.setLocation(newLocation); - return; - } - if (position.equals(("center"))) { - //TODO - } - } - - protected void checkInit() throws IllegalStateException { - if (factory == null) { - throw new IllegalStateException("no factory found in " + this); - } - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/ShowUIAction.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/ShowUIAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,140 @@ +/** + * ##% 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.nuiton.jaxx.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.Dimension; +import java.awt.Point; +import java.awt.event.ActionEvent; + +/** + * @param <M> type of model + * @param <U> type of ui + * @param <H> type of handler + * @author chemit */ +public abstract class ShowUIAction<M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> extends javax.swing.AbstractAction { + + protected static Log log = LogFactory.getLog(AbstractUIAction.class); + + protected transient DialogUI<?> ui; + + private static final long serialVersionUID = 1L; + + protected DialogUIDef<M, U, H> uiDef; + + protected transient UIFactory factory; + + protected String position; + + protected boolean undecorated = true; + + protected U initUI(ActionEvent e) { + return getFactory().getUI(uiDef); + } + + public ShowUIAction(DialogUI<?> ui, DialogUIDef<M, U, H> uiDef, UIFactory factory, boolean showText) { + super(uiDef.getShowActionLibelle(), uiDef.getShowUIActionIcon()); + this.ui = ui; + this.uiDef = uiDef; + String name = (String) getValue(NAME); + putValue(DISPLAYED_MNEMONIC_INDEX_KEY, name.length() - 1); + putValue(ACCELERATOR_KEY, (int) name.charAt(name.length() - 1)); + if (!showText) { + putValue(NAME, null); + } + putValue(SHORT_DESCRIPTION, uiDef.getShowActionTip()); + this.factory = factory; + } + + public DialogUI<?> getUi() { + return ui; + } + + public DialogUIDef<M, U, H> getUiDef() { + return uiDef; + } + + public UIFactory getFactory() { + return factory; + } + + public void setUiDef(DialogUIDef<M, U, H> uiDef) { + this.uiDef = uiDef; + } + + public void setPosition(String position) { + this.position = position; + } + + public void setUndecorated(boolean undecorated) { + this.undecorated = undecorated; + } + + @Override + public void actionPerformed(java.awt.event.ActionEvent e) { + checkInit(); + U gui = initUI(e); + gui.setTitle(uiDef.getUiTitle()); + log.info(gui.getTitle()); + //TODO ui.setUndecorated(undecorated); + setPosition(this.getUi(), gui, position); + + gui.setVisible(true); + } + + protected void setPosition(javax.swing.JDialog parentUI, javax.swing.JDialog ui, String position) { + if (position == null || parentUI == null) { + return; + } + Point parentLocation = parentUI.getLocationOnScreen(); + Dimension parentSize = parentUI.getSize(); + + if (position.equals("bottom-left")) { + int top = (int) (parentLocation.getY() + parentSize.getHeight()); + int left = (int) (parentLocation.getX()); + Point newLocation = new Point(left, top); + newLocation.setLocation(left, top); + ui.setLocation(newLocation); + return; + } + if (position.equals("top-left")) { + int top = (int) (parentLocation.getY()); + int left = (int) (parentLocation.getX()); + Point newLocation = new Point(left, top); + newLocation.setLocation(left, top); + ui.setLocation(newLocation); + return; + } + if (position.equals("top-right")) { + int top = (int) (parentLocation.getY()); + int left = (int) (parentLocation.getX() + parentSize.getWidth()); + Point newLocation = new Point(left, top); + newLocation.setLocation(left, top); + ui.setLocation(newLocation); + return; + } + if (position.equals(("center"))) { + //TODO + } + } + + protected void checkInit() throws IllegalStateException { + if (factory == null) { + throw new IllegalStateException("no factory found in " + this); + } + } +} \ No newline at end of file Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/UIFactory.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,184 +0,0 @@ -/** -/** - * ##% 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.jaxx.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codelutin.util.StringUtil; - -import javax.swing.event.EventListenerList; -import java.util.ArrayList; -import java.util.List; -import java.util.ServiceLoader; - -/** - * Factory for UI, using a cache and a provider to find ui implementations. - * - * @author chemit - */ -public class UIFactory { - - static protected final Log log = LogFactory.getLog(UIFactory.class); - - private final String applicationName; - - private final DialogUIDef[] defs; - - private final EventListenerList listeners; - - public UIFactory(String applicationName, DialogUIDef[] defs, FactoryWindowListener... listeners) { - this.applicationName = applicationName; - this.listeners = new EventListenerList(); - for (FactoryWindowListener listener : listeners) { - listener.setFactory(this); - addFactoryWindowListener(listener); - } - this.defs = defs; - long t0 = System.nanoTime(); - if (log.isDebugEnabled()) { - log.debug("start at " + new java.util.Date()); - } - try { - init(); - } catch (Exception e) { - log.error(e); - throw new RuntimeException(e); - } finally { - if (log.isDebugEnabled()) { - log.info("end in " + StringUtil.convertTime(t0, System.nanoTime())); - } - } - } - - public void addFactoryWindowListener(FactoryWindowListener l) { - listeners.add(FactoryWindowListener.class, l); - if (log.isDebugEnabled()) { - log.debug("after added (" + listeners.getListenerCount() + ") : " + l); - } - } - - public void removeFactoryWindowListener(FactoryWindowListener l) { - listeners.remove(FactoryWindowListener.class, l); - for (DialogUIDef def : getDefs()) { - if (def.uiInstance != null) { - def.uiInstance.removeWindowListener(l); - } - } - if (log.isDebugEnabled()) { - log.debug(" after removed (" + listeners.getListenerCount() + ") : " + l); - } - if (listeners.getListenerCount(FactoryWindowListener.class) == 0) { - // close for real factory - close(); - } - } - - public void close() { - log.info(this + " at " + new java.util.Date()); - for (DialogUIDef<?, ?, ?> def : defs) { - DialogUI<?> ui = def.uiInstance; - if (ui != null) { - ui.getHandler().dispose(); - def.uiInstance = null; - } - } - if (listeners.getListenerCount(FactoryWindowListener.class) > 0) { - log.warn("some listeners where not properly removed, force deletion..."); - for (FactoryWindowListener listener : listeners.getListeners(FactoryWindowListener.class)) { - removeFactoryWindowListener(listener); - } - } - - } - - protected void init() { - - UIProvider[] providers = detectProviders(); - - for (DialogUIDef<?, ?, ?> def : defs) { - initDef(providers, def); - if (def.getUiImplClass() == null) { - throw new IllegalStateException("could not find implementation for ui def " + def); - } - } - } - - protected void initDef(UIProvider[] providers, DialogUIDef<?, ?, ?> def) { - for (UIProvider provider : providers) { - Class<?> uiImplClass = provider.findUIImplementation(def); - if (uiImplClass != null) { - if (log.isDebugEnabled()) { - log.debug("init done for " + def); - } - // ui implementation was found - break; - } - } - } - - protected UIProvider[] detectProviders() { - long t0 = System.nanoTime(); - List<UIProvider> providers = new ArrayList<UIProvider>(); - for (UIProvider provider : ServiceLoader.load(UIProvider.class)) { - if (applicationName.equals(provider.getApplicationName())) { - if (log.isDebugEnabled()) { - log.debug("provider detected [" + provider + ']'); - } - providers.add(provider); - } - } - log.info("found " + providers.size() + " ui provider(s) in " + StringUtil.convertTime(t0, System.nanoTime()) + " : " + providers); - return providers.toArray(new UIProvider[providers.size()]); - } - - protected DialogUIDef[] getDefs() { - return defs; - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - close(); - } - - public <M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> U getUI(DialogUIDef<M, U, H> uiType, Object... params) { - U ui = uiType.uiInstance; - if (ui == null) { - try { - ui = uiType.newUI(); - M model = uiType.newModel(); - H handler = uiType.newHandler(ui, model, params); - registerUI(uiType, ui, handler); - } catch (Exception e) { - throw new IllegalStateException("could not instanciate ui handler " + uiType + " for reason : " + e.getMessage(), e); - } - } - return ui; - } - - protected <M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> void registerUI(DialogUIDef<M, U, H> uiType, U ui, H handler) { - ui.setHandler(handler); - handler.init(); - uiType.setUiInstance(ui); - for (FactoryWindowListener listener : listeners.getListeners(FactoryWindowListener.class)) { - if (log.isDebugEnabled()) { - log.debug("----- addFactoryWindowListener " + listener + " to " + ui); - } - ui.addWindowListener(listener); - } - } - -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/UIFactory.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIFactory.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,184 @@ +/** +/** + * ##% 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.nuiton.jaxx.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.StringUtil; + +import javax.swing.event.EventListenerList; +import java.util.ArrayList; +import java.util.List; +import java.util.ServiceLoader; + +/** + * Factory for UI, using a cache and a provider to find ui implementations. + * + * @author chemit + */ +public class UIFactory { + + static protected final Log log = LogFactory.getLog(UIFactory.class); + + private final String applicationName; + + private final DialogUIDef<?,?,?>[] defs; + + private final EventListenerList listeners; + + public UIFactory(String applicationName, DialogUIDef<?,?,?>[] defs, FactoryWindowListener... listeners) { + this.applicationName = applicationName; + this.listeners = new EventListenerList(); + for (FactoryWindowListener listener : listeners) { + listener.setFactory(this); + addFactoryWindowListener(listener); + } + this.defs = defs; + long t0 = System.nanoTime(); + if (log.isDebugEnabled()) { + log.debug("start at " + new java.util.Date()); + } + try { + init(); + } catch (Exception e) { + log.error(e); + throw new RuntimeException(e); + } finally { + if (log.isDebugEnabled()) { + log.info("end in " + StringUtil.convertTime(t0, System.nanoTime())); + } + } + } + + public void addFactoryWindowListener(FactoryWindowListener l) { + listeners.add(FactoryWindowListener.class, l); + if (log.isDebugEnabled()) { + log.debug("after added (" + listeners.getListenerCount() + ") : " + l); + } + } + + public void removeFactoryWindowListener(FactoryWindowListener l) { + listeners.remove(FactoryWindowListener.class, l); + for (DialogUIDef<?,?,?> def : getDefs()) { + if (def.uiInstance != null) { + def.uiInstance.removeWindowListener(l); + } + } + if (log.isDebugEnabled()) { + log.debug(" after removed (" + listeners.getListenerCount() + ") : " + l); + } + if (listeners.getListenerCount(FactoryWindowListener.class) == 0) { + // close for real factory + close(); + } + } + + public void close() { + log.info(this + " at " + new java.util.Date()); + for (DialogUIDef<?, ?, ?> def : defs) { + DialogUI<?> ui = def.uiInstance; + if (ui != null) { + ui.getHandler().dispose(); + def.uiInstance = null; + } + } + if (listeners.getListenerCount(FactoryWindowListener.class) > 0) { + log.warn("some listeners where not properly removed, force deletion..."); + for (FactoryWindowListener listener : listeners.getListeners(FactoryWindowListener.class)) { + removeFactoryWindowListener(listener); + } + } + + } + + protected void init() { + + UIProvider[] providers = detectProviders(); + + for (DialogUIDef<?, ?, ?> def : defs) { + initDef(providers, def); + if (def.getUiImplClass() == null) { + throw new IllegalStateException("could not find implementation for ui def " + def); + } + } + } + + protected void initDef(UIProvider[] providers, DialogUIDef<?, ?, ?> def) { + for (UIProvider provider : providers) { + Class<?> uiImplClass = provider.findUIImplementation(def); + if (uiImplClass != null) { + if (log.isDebugEnabled()) { + log.debug("init done for " + def); + } + // ui implementation was found + break; + } + } + } + + protected UIProvider[] detectProviders() { + long t0 = System.nanoTime(); + List<UIProvider> providers = new ArrayList<UIProvider>(); + for (UIProvider provider : ServiceLoader.load(UIProvider.class)) { + if (applicationName.equals(provider.getApplicationName())) { + if (log.isDebugEnabled()) { + log.debug("provider detected [" + provider + ']'); + } + providers.add(provider); + } + } + log.info("found " + providers.size() + " ui provider(s) in " + StringUtil.convertTime(t0, System.nanoTime()) + " : " + providers); + return providers.toArray(new UIProvider[providers.size()]); + } + + protected DialogUIDef<?,?,?>[] getDefs() { + return defs; + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + close(); + } + + public <M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> U getUI(DialogUIDef<M, U, H> uiType, Object... params) { + U ui = uiType.uiInstance; + if (ui == null) { + try { + ui = uiType.newUI(); + M model = uiType.newModel(); + H handler = uiType.newHandler(ui, model, params); + registerUI(uiType, ui, handler); + } catch (Exception e) { + throw new IllegalStateException("could not instanciate ui handler " + uiType + " for reason : " + e.getMessage(), e); + } + } + return ui; + } + + protected <M extends DialogUIModel, U extends DialogUI<H>, H extends DialogUIHandler<M, U>> void registerUI(DialogUIDef<M, U, H> uiType, U ui, H handler) { + ui.setHandler(handler); + handler.init(); + uiType.setUiInstance(ui); + for (FactoryWindowListener listener : listeners.getListeners(FactoryWindowListener.class)) { + if (log.isDebugEnabled()) { + log.debug("----- addFactoryWindowListener " + listener + " to " + ui); + } + ui.addWindowListener(listener); + } + } + +} \ No newline at end of file Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/UIHelper.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,70 +0,0 @@ -/* -* ##% Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 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.jaxx.util; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JRootPane; -import javax.swing.KeyStroke; -import java.awt.event.ActionEvent; - -/** - * Ui helper class. - * - * @author tony - */ -public class UIHelper { - - public static ImageIcon createImageIcon(String path) { - java.net.URL imgURL = UIHelper.class.getResource("/icons/" + path); - if (imgURL != null) { - return new ImageIcon(imgURL); - } else { - throw new IllegalArgumentException("could not find icon " + path); - } - } - - /** - * Attach to <code>ui</code> an abort action,accessible by <code>ESC</code> key. - * - * @param ui ui - */ - public static void setQuitAction(final JDialog ui) { - JRootPane rootPane = ui.getRootPane(); - - Action quitAction = new AbstractAction("quit") { - private static final long serialVersionUID = -869095664995763057L; - - public void actionPerformed(ActionEvent e) { - ui.dispose(); - } - }; - rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "quit"); - rootPane.getActionMap().put("quit", quitAction); - ui.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - } - - public static ImageIcon createActionIcon(String name) { - return createImageIcon("action-" + name + ".png"); - } - -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/UIHelper.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIHelper.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,71 @@ +/* +* ##% Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 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.nuiton.jaxx.util; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JRootPane; +import javax.swing.KeyStroke; +import java.awt.event.ActionEvent; + +/** + * Ui helper class. + * + * @author tony + */ +public class UIHelper { + + public static ImageIcon createImageIcon(String path) { + java.net.URL imgURL = UIHelper.class.getResource("/icons/" + path); + if (imgURL != null) { + return new ImageIcon(imgURL); + } else { + throw new IllegalArgumentException("could not find icon " + path); + } + } + + /** + * Attach to <code>ui</code> an abort action,accessible by <code>ESC</code> key. + * + * @param ui ui + */ + public static void setQuitAction(final JDialog ui) { + JRootPane rootPane = ui.getRootPane(); + + Action quitAction = new AbstractAction("quit") { + private static final long serialVersionUID = -869095664995763057L; + + @Override + public void actionPerformed(ActionEvent e) { + ui.dispose(); + } + }; + rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "quit"); + rootPane.getActionMap().put("quit", quitAction); + ui.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + } + + public static ImageIcon createActionIcon(String name) { + return createImageIcon("action-" + name + ".png"); + } + +} Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIProvider.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/UIProvider.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/UIProvider.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -12,7 +12,7 @@ * - Suite 330, Boston, MA 02111-1307, USA. * ##% */ -package org.codelutin.jaxx.util; +package org.nuiton.jaxx.util; /** @author chemit */ public abstract class UIProvider { Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/CancelAction.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,43 +0,0 @@ -/** - * ##% 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.jaxx.util.config; - -import org.codelutin.jaxx.util.AbstractUIAction; -import org.codelutin.jaxx.util.DialogUI; -import org.codelutin.jaxx.util.UIHelper; - -import java.awt.event.ActionEvent; - -/** @author chemit */ -public class CancelAction<E extends Enum<E>, H extends DialogConfigUIHandler<E, ?, ?>> extends AbstractUIAction<H> { - private static final long serialVersionUID = 1L; - - public CancelAction(DialogUI<? extends H> dialogUI, boolean showLabel) { - super(null, UIHelper.createActionIcon("cancel-config"), dialogUI); - if (showLabel) { - String text = org.codelutin.i18n.I18n._("lutinui.config.cancel"); - putValue(NAME, text); - putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 0); - putValue(MNEMONIC_KEY, (int) text.charAt(0)); - } - String libelle = org.codelutin.i18n.I18n._("lutinui.config.cancel.tooltip"); - putValue(SHORT_DESCRIPTION, libelle); - - } - - public void actionPerformed(ActionEvent e) { - getUi().dispose(); - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/CancelAction.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/CancelAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,43 @@ +/** + * ##% 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.nuiton.jaxx.util.config; + +import org.nuiton.jaxx.util.AbstractUIAction; +import org.nuiton.jaxx.util.DialogUI; +import org.nuiton.jaxx.util.UIHelper; + +import java.awt.event.ActionEvent; + +/** @author chemit */ +public class CancelAction<E extends Enum<E>, H extends DialogConfigUIHandler<E, ?, ?>> extends AbstractUIAction<H> { + private static final long serialVersionUID = 1L; + + public CancelAction(DialogUI<? extends H> dialogUI, boolean showLabel) { + super(null, UIHelper.createActionIcon("cancel-config"), dialogUI); + if (showLabel) { + String text = org.nuiton.i18n.I18n._("lutinui.config.cancel"); + putValue(NAME, text); + putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 0); + putValue(MNEMONIC_KEY, (int) text.charAt(0)); + } + String libelle = org.nuiton.i18n.I18n._("lutinui.config.cancel.tooltip"); + putValue(SHORT_DESCRIPTION, libelle); + + } + + public void actionPerformed(ActionEvent e) { + getUi().dispose(); + } +} \ No newline at end of file Modified: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUI.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/DialogConfigUI.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUI.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -12,9 +12,9 @@ * - Suite 330, Boston, MA 02111-1307, USA. * ##% */ -package org.codelutin.jaxx.util.config; +package org.nuiton.jaxx.util.config; -import org.codelutin.jaxx.util.DialogUI; +import org.nuiton.jaxx.util.DialogUI; import javax.swing.AbstractButton; import javax.swing.JCheckBox; Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/DialogConfigUIHandler.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,156 +0,0 @@ -/** - * ##% 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.jaxx.util.config; - -import org.codelutin.jaxx.util.DialogUIHandler; -import org.codelutin.util.ConverterUtil; -import org.codelutin.util.config.Config; -import org.codelutin.util.config.Property; - -import javax.swing.JComponent; -import java.awt.Color; -import java.beans.PropertyChangeEvent; -import java.util.EnumMap; -import java.util.EnumSet; - -/** - * DialogUI handler - * - * @author chemit - */ -public abstract class DialogConfigUIHandler<E extends Enum<E>, M extends DialogConfigUIModel<E, ?>, U extends DialogConfigUI<E, ?>> extends DialogUIHandler<M, U> { - - protected DialogConfigUIHandler(U ui, M model) { - super(ui, model); - } - - public void propertyChange(PropertyChangeEvent evt) { - if (log.isDebugEnabled()) { - log.debug(evt.getPropertyName() + " old:" + evt.getOldValue() + ", new:" + evt.getNewValue()); - } - String action = evt.getPropertyName(); - - if (DialogConfigUIModel.CONFIG_PROPERTY_CHANGED.equals(action)) { - // update ui with model values, - populateUI(); - // revalidate form - doCheckAll(); - return; - } - - if (DialogConfigUIModel.MODIFIED_PROPERTY_CHANGED.equals(action)) { - Boolean newValue = (Boolean) evt.getNewValue(); - boolean modified = newValue != null && newValue; - getUi().getReset().setEnabled(modified); - getUi().getOk().setEnabled(modified && getModel().isConfigValid()); - return; - } - - if (DialogConfigUIModel.UNVALID_PROPERTY_CHANGED.equals(action)) { - updateUI(); - return; - } - - throw new IllegalStateException("unimplemented property changed : " + evt + " for " + this); - } - - public void doCheck(E key) { - Object uiValue = getUi().getElementValue(key); - DialogConfigUIModel<E, ?> model = getModel(); - Object currentValue = model.getCurrent().getProperty(key); - if (currentValue == null) { - currentValue = ""; - } else { - currentValue = String.valueOf(currentValue); - } - - model.validateProperty(key, uiValue); - model.changeModifiedState(key, uiValue, currentValue); - } - - public void doCheckAll() { - DialogConfigUIModel<E, ?> model = getModel(); - EnumSet<E> unvalids = EnumSet.noneOf(model.klass); - for (E e : model.getCheckedKeysSet()) { - Object uiValue = getUi().getElementValue(e); - if (!model.isValid(e, uiValue)) { - unvalids.add(e); - } - } - model.setUnvalids(unvalids); - unvalids.clear(); - } - - protected boolean prepareSave() { - DialogConfigUI<E, ?> ui = getUi(); - DialogConfigUIModel<E, ?> model = getModel(); - - Config<E> current = model.getCurrent(); - - if (!model.isConfigValid()) { - log.warn("do not save a unvalid config : " + model.getUnvalids()); - return false; - } - - if (!model.isModified()) { - log.warn("nothing to save"); - return false; - } - EnumSet<E> toTreate = model.getCheckedKeysSet(); - // transfert checkable values from ui to model - for (E key : model.getModifieds()) { - if (!toTreate.contains(key)) { - continue; - } - Object value = ui.getElementValue(key); - Class<?> type = ((Property) key).getType(); - Object newValue = ConverterUtil.convert(type, value); - current.setProperty(key, newValue); - } - - return true; - } - - protected void populateUI() { - U ui = getUi(); - EnumMap<E, Object> map = getModel().getCurrent().getProperties(); - for (E e : getModel().getCheckedKeysSet()) { - Object value = map.get(e); - populateUI(ui, e, value); - } - } - - protected void populateUI(U ui, E key, Object value) { - ui.setElementValue(key, value); - } - - protected void updateUI() { - EnumSet<E> unvalids = getModel().getUnvalids(); - for (E key : unvalids) { - setLabelColor(key, false); - } - for (E key : EnumSet.complementOf(unvalids)) { - setLabelColor(key, true); - } - } - - protected void setLabelColor(E key, boolean valid) { - JComponent component = getUi().getElementLabel(key); - if (component != null && component.isVisible()) { - component.setForeground(valid ? Color.black : Color.red); - } - } - -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/DialogConfigUIHandler.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIHandler.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,156 @@ +/** + * ##% 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.nuiton.jaxx.util.config; + +import org.nuiton.jaxx.util.DialogUIHandler; +import org.nuiton.util.ConverterUtil; +import org.nuiton.util.config.Config; +import org.nuiton.util.config.Property; + +import javax.swing.JComponent; +import java.awt.Color; +import java.beans.PropertyChangeEvent; +import java.util.EnumMap; +import java.util.EnumSet; + +/** + * DialogUI handler + * + * @author chemit + */ +public abstract class DialogConfigUIHandler<E extends Enum<E>, M extends DialogConfigUIModel<E, ?>, U extends DialogConfigUI<E, ?>> extends DialogUIHandler<M, U> { + + protected DialogConfigUIHandler(U ui, M model) { + super(ui, model); + } + + public void propertyChange(PropertyChangeEvent evt) { + if (log.isDebugEnabled()) { + log.debug(evt.getPropertyName() + " old:" + evt.getOldValue() + ", new:" + evt.getNewValue()); + } + String action = evt.getPropertyName(); + + if (DialogConfigUIModel.CONFIG_PROPERTY_CHANGED.equals(action)) { + // update ui with model values, + populateUI(); + // revalidate form + doCheckAll(); + return; + } + + if (DialogConfigUIModel.MODIFIED_PROPERTY_CHANGED.equals(action)) { + Boolean newValue = (Boolean) evt.getNewValue(); + boolean modified = newValue != null && newValue; + getUi().getReset().setEnabled(modified); + getUi().getOk().setEnabled(modified && getModel().isConfigValid()); + return; + } + + if (DialogConfigUIModel.UNVALID_PROPERTY_CHANGED.equals(action)) { + updateUI(); + return; + } + + throw new IllegalStateException("unimplemented property changed : " + evt + " for " + this); + } + + public void doCheck(E key) { + Object uiValue = getUi().getElementValue(key); + DialogConfigUIModel<E, ?> model = getModel(); + Object currentValue = model.getCurrent().getProperty(key); + if (currentValue == null) { + currentValue = ""; + } else { + currentValue = String.valueOf(currentValue); + } + + model.validateProperty(key, uiValue); + model.changeModifiedState(key, uiValue, currentValue); + } + + public void doCheckAll() { + DialogConfigUIModel<E, ?> model = getModel(); + EnumSet<E> unvalids = EnumSet.noneOf(model.klass); + for (E e : model.getCheckedKeysSet()) { + Object uiValue = getUi().getElementValue(e); + if (!model.isValid(e, uiValue)) { + unvalids.add(e); + } + } + model.setUnvalids(unvalids); + unvalids.clear(); + } + + protected boolean prepareSave() { + DialogConfigUI<E, ?> ui = getUi(); + DialogConfigUIModel<E, ?> model = getModel(); + + Config<E> current = model.getCurrent(); + + if (!model.isConfigValid()) { + log.warn("do not save a unvalid config : " + model.getUnvalids()); + return false; + } + + if (!model.isModified()) { + log.warn("nothing to save"); + return false; + } + EnumSet<E> toTreate = model.getCheckedKeysSet(); + // transfert checkable values from ui to model + for (E key : model.getModifieds()) { + if (!toTreate.contains(key)) { + continue; + } + Object value = ui.getElementValue(key); + Class<?> type = ((Property) key).getType(); + Object newValue = ConverterUtil.convert(type, value); + current.setProperty(key, newValue); + } + + return true; + } + + protected void populateUI() { + U ui = getUi(); + EnumMap<E, Object> map = getModel().getCurrent().getProperties(); + for (E e : getModel().getCheckedKeysSet()) { + Object value = map.get(e); + populateUI(ui, e, value); + } + } + + protected void populateUI(U ui, E key, Object value) { + ui.setElementValue(key, value); + } + + protected void updateUI() { + EnumSet<E> unvalids = getModel().getUnvalids(); + for (E key : unvalids) { + setLabelColor(key, false); + } + for (E key : EnumSet.complementOf(unvalids)) { + setLabelColor(key, true); + } + } + + protected void setLabelColor(E key, boolean valid) { + JComponent component = getUi().getElementLabel(key); + if (component != null && component.isVisible()) { + component.setForeground(valid ? Color.black : Color.red); + } + } + +} \ No newline at end of file Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/DialogConfigUIModel.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,220 +0,0 @@ -/** - * ##% 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.jaxx.util.config; - -import org.codelutin.jaxx.util.DialogUIModel; -import org.codelutin.util.config.Config; - -import java.util.EnumSet; - -/** - * Abstract config ui model. - * - * @author chemit - */ -public abstract class DialogConfigUIModel<E extends Enum<E>, C extends Config<E>> extends DialogUIModel { - - public static final String CONFIG_PROPERTY_CHANGED = "config"; - public static final String MODIFIED_PROPERTY_CHANGED = "modify"; - public static final String UNVALID_PROPERTY_CHANGED = "unvalid"; - - /** @return a empty config */ - protected abstract C newConfig(); - - /** - * @param key property key - * @param value value to validate - * @return <code>true</code> if given value is valid for property, <code>false>/code> otherwise - */ - protected abstract boolean isValid(E key, Object value); - - /** - * object used to init model and save model, this is an external object. - * <p/> - * The object must have bean read-write properties for each value of E - */ - protected Object src; - - /** current config used in model */ - protected C current; - - /** set of modified properties */ - protected EnumSet<E> modifieds; - - /** set of unvalid properties */ - protected EnumSet<E> unvalids; - - /** enum class */ - protected Class<E> klass; - - /** set of key not to check */ - protected EnumSet<E> uncheckedKeys; - - /** set of all keys checkable */ - protected EnumSet<E> checkedKeysSet; - - protected DialogConfigUIModel(Class<E> klass) { - this.klass = klass; - this.current = newConfig(); - this.modifieds = EnumSet.noneOf(klass); - this.unvalids = EnumSet.noneOf(klass); - } - - public EnumSet<E> getCheckedKeysSet() { - if (checkedKeysSet == null) { - if (uncheckedKeys != null) { - checkedKeysSet = EnumSet.complementOf(uncheckedKeys); - } else { - checkedKeysSet = EnumSet.allOf(klass); - } - } - return checkedKeysSet; - } - - public Object getSrc() { - return src; - } - - public C getCurrent() { - return current; - } - - public EnumSet<E> getUnivserse() { - return getCurrent().getUniverse(); - } - - public EnumSet<E> getModifieds() { - return modifieds; - } - - public EnumSet<E> getUnvalids() { - return unvalids; - } - - public boolean isModified() { - return !modifieds.isEmpty(); - } - - public boolean isConfigValid() { - return unvalids.isEmpty(); - } - - public void populate(Object src) { - this.src = src; - this.current = newConfig(); - if (src != null) { - this.current.copyFrom(src); - } - this.modifieds.clear(); - this.unvalids.clear(); - setModified(false); - firePropertyChange(CONFIG_PROPERTY_CHANGED, null, this); - } - - public void reset() { - populate(src); - } - - public void setModified(boolean modified) { - firePropertyChange(MODIFIED_PROPERTY_CHANGED, null, modified); - } - - public void setUnvalid(boolean unvalid) { - firePropertyChange(UNVALID_PROPERTY_CHANGED, null, unvalid); - } - - public void addModified(E key) { - if (!modifieds.contains(key)) { - modifieds.add(key); - log.debug(key); - } - setModified(!modifieds.isEmpty()); - } - - public void removeModified(E key) { - - if (modifieds.contains(key)) { - modifieds.remove(key); - } - setModified(!modifieds.isEmpty()); - } - - public void removeModified(EnumSet<E> keys) { - for (E key : keys) { - if (modifieds.contains(key)) { - modifieds.remove(key); - } - } - setModified(!modifieds.isEmpty()); - } - - public void setUnvalids(EnumSet<E> keys) { - for (E key : keys) { - if (!unvalids.contains(key)) { - unvalids.add(key); - } - } - for (E key : EnumSet.complementOf(keys)) { - if (unvalids.contains(key)) { - unvalids.remove(key); - } - } - setUnvalid(!unvalids.isEmpty()); - } - - - public void addUnvalid(E key) { - if (!unvalids.contains(key)) { - unvalids.add(key); - } - setUnvalid(!unvalids.isEmpty()); - } - - public void removeUnvalid(E key) { - if (unvalids.contains(key)) { - unvalids.remove(key); - } - setUnvalid(!unvalids.isEmpty()); - } - - public void save() { - current.copyTo(src, modifieds); - modifieds.clear(); - // redisplay config - firePropertyChange(CONFIG_PROPERTY_CHANGED, null, this); - } - - public void changeModifiedState(E key, Object uiValue, Object currentValue) { - if (uiValue!=null && uiValue.equals(currentValue)) { - removeModified(key); - } else { - addModified(key); - } - } - - public void clear(E key) { - log.info(key); - modifieds.remove(key); - unvalids.remove(key); - } - - protected void validateProperty(E key, Object uiValue) { - if (isValid(key, uiValue)) { - removeUnvalid(key); - } else { - addUnvalid(key); - } - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/DialogConfigUIModel.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/DialogConfigUIModel.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,220 @@ +/** + * ##% 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.nuiton.jaxx.util.config; + +import org.nuiton.jaxx.util.DialogUIModel; +import org.nuiton.util.config.Config; + +import java.util.EnumSet; + +/** + * Abstract config ui model. + * + * @author chemit + */ +public abstract class DialogConfigUIModel<E extends Enum<E>, C extends Config<E>> extends DialogUIModel { + + public static final String CONFIG_PROPERTY_CHANGED = "config"; + public static final String MODIFIED_PROPERTY_CHANGED = "modify"; + public static final String UNVALID_PROPERTY_CHANGED = "unvalid"; + + /** @return a empty config */ + protected abstract C newConfig(); + + /** + * @param key property key + * @param value value to validate + * @return <code>true</code> if given value is valid for property, <code>false>/code> otherwise + */ + protected abstract boolean isValid(E key, Object value); + + /** + * object used to init model and save model, this is an external object. + * <p/> + * The object must have bean read-write properties for each value of E + */ + protected Object src; + + /** current config used in model */ + protected C current; + + /** set of modified properties */ + protected EnumSet<E> modifieds; + + /** set of unvalid properties */ + protected EnumSet<E> unvalids; + + /** enum class */ + protected Class<E> klass; + + /** set of key not to check */ + protected EnumSet<E> uncheckedKeys; + + /** set of all keys checkable */ + protected EnumSet<E> checkedKeysSet; + + protected DialogConfigUIModel(Class<E> klass) { + this.klass = klass; + this.current = newConfig(); + this.modifieds = EnumSet.noneOf(klass); + this.unvalids = EnumSet.noneOf(klass); + } + + public EnumSet<E> getCheckedKeysSet() { + if (checkedKeysSet == null) { + if (uncheckedKeys != null) { + checkedKeysSet = EnumSet.complementOf(uncheckedKeys); + } else { + checkedKeysSet = EnumSet.allOf(klass); + } + } + return checkedKeysSet; + } + + public Object getSrc() { + return src; + } + + public C getCurrent() { + return current; + } + + public EnumSet<E> getUnivserse() { + return getCurrent().getUniverse(); + } + + public EnumSet<E> getModifieds() { + return modifieds; + } + + public EnumSet<E> getUnvalids() { + return unvalids; + } + + public boolean isModified() { + return !modifieds.isEmpty(); + } + + public boolean isConfigValid() { + return unvalids.isEmpty(); + } + + public void populate(Object src) { + this.src = src; + this.current = newConfig(); + if (src != null) { + this.current.copyFrom(src); + } + this.modifieds.clear(); + this.unvalids.clear(); + setModified(false); + firePropertyChange(CONFIG_PROPERTY_CHANGED, null, this); + } + + public void reset() { + populate(src); + } + + public void setModified(boolean modified) { + firePropertyChange(MODIFIED_PROPERTY_CHANGED, null, modified); + } + + public void setUnvalid(boolean unvalid) { + firePropertyChange(UNVALID_PROPERTY_CHANGED, null, unvalid); + } + + public void addModified(E key) { + if (!modifieds.contains(key)) { + modifieds.add(key); + log.debug(key); + } + setModified(!modifieds.isEmpty()); + } + + public void removeModified(E key) { + + if (modifieds.contains(key)) { + modifieds.remove(key); + } + setModified(!modifieds.isEmpty()); + } + + public void removeModified(EnumSet<E> keys) { + for (E key : keys) { + if (modifieds.contains(key)) { + modifieds.remove(key); + } + } + setModified(!modifieds.isEmpty()); + } + + public void setUnvalids(EnumSet<E> keys) { + for (E key : keys) { + if (!unvalids.contains(key)) { + unvalids.add(key); + } + } + for (E key : EnumSet.complementOf(keys)) { + if (unvalids.contains(key)) { + unvalids.remove(key); + } + } + setUnvalid(!unvalids.isEmpty()); + } + + + public void addUnvalid(E key) { + if (!unvalids.contains(key)) { + unvalids.add(key); + } + setUnvalid(!unvalids.isEmpty()); + } + + public void removeUnvalid(E key) { + if (unvalids.contains(key)) { + unvalids.remove(key); + } + setUnvalid(!unvalids.isEmpty()); + } + + public void save() { + current.copyTo(src, modifieds); + modifieds.clear(); + // redisplay config + firePropertyChange(CONFIG_PROPERTY_CHANGED, null, this); + } + + public void changeModifiedState(E key, Object uiValue, Object currentValue) { + if (uiValue!=null && uiValue.equals(currentValue)) { + removeModified(key); + } else { + addModified(key); + } + } + + public void clear(E key) { + log.info(key); + modifieds.remove(key); + unvalids.remove(key); + } + + protected void validateProperty(E key, Object uiValue) { + if (isValid(key, uiValue)) { + removeUnvalid(key); + } else { + addUnvalid(key); + } + } +} \ No newline at end of file Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/ResetAction.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,43 +0,0 @@ -/** - * ##% 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.jaxx.util.config; - -import org.codelutin.jaxx.util.AbstractUIAction; -import org.codelutin.jaxx.util.DialogUI; -import org.codelutin.jaxx.util.UIHelper; - -import java.awt.event.ActionEvent; - -/** @author chemit */ -public class ResetAction<E extends Enum<E>, H extends DialogConfigUIHandler<E, ?, ?>> extends AbstractUIAction<H> { - private static final long serialVersionUID = 1L; - - public ResetAction(DialogUI<? extends H> dialogUI, boolean showLabel) { - super(null, UIHelper.createActionIcon("reset-config"), dialogUI); - if (showLabel) { - String text = org.codelutin.i18n.I18n._("lutinui.config.reset"); - putValue(NAME, text); - putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 0); - putValue(MNEMONIC_KEY, (int) text.charAt(0)); - } - String libelle = org.codelutin.i18n.I18n._("lutinui.config.reset.tooltip"); - putValue(SHORT_DESCRIPTION, libelle); - - } - - public void actionPerformed(ActionEvent e) { - getHandler().getModel().reset(); - } -} \ No newline at end of file Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/ResetAction.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/ResetAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,43 @@ +/** + * ##% 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.nuiton.jaxx.util.config; + +import org.nuiton.jaxx.util.AbstractUIAction; +import org.nuiton.jaxx.util.DialogUI; +import org.nuiton.jaxx.util.UIHelper; + +import java.awt.event.ActionEvent; + +/** @author chemit */ +public class ResetAction<E extends Enum<E>, H extends DialogConfigUIHandler<E, ?, ?>> extends AbstractUIAction<H> { + private static final long serialVersionUID = 1L; + + public ResetAction(DialogUI<? extends H> dialogUI, boolean showLabel) { + super(null, UIHelper.createActionIcon("reset-config"), dialogUI); + if (showLabel) { + String text = org.nuiton.i18n.I18n._("lutinui.config.reset"); + putValue(NAME, text); + putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 0); + putValue(MNEMONIC_KEY, (int) text.charAt(0)); + } + String libelle = org.nuiton.i18n.I18n._("lutinui.config.reset.tooltip"); + putValue(SHORT_DESCRIPTION, libelle); + + } + + public void actionPerformed(ActionEvent e) { + getHandler().getModel().reset(); + } +} \ No newline at end of file Deleted: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/SaveAction.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,50 +0,0 @@ -/** - * ##% 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.jaxx.util.config; - -import org.codelutin.jaxx.util.AbstractUIAction; -import org.codelutin.jaxx.util.DialogUI; -import org.codelutin.jaxx.util.UIHelper; - -import java.awt.event.ActionEvent; - -/** @author chemit */ -public class SaveAction<E extends Enum<E>, H extends DialogConfigUIHandler<E, ?, ?>> extends AbstractUIAction<H> { - private static final long serialVersionUID = 1L; - - public SaveAction(DialogUI<? extends H> dialogUI, boolean showLabel) { - super(null, UIHelper.createActionIcon("save-config"), dialogUI); - if (showLabel) { - String text = org.codelutin.i18n.I18n._("lutinui.config.save"); - putValue(NAME, text); - putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 0); - putValue(MNEMONIC_KEY, (int) text.charAt(0)); - } - String libelle = org.codelutin.i18n.I18n._("lutinui.config.save.tooltip"); - putValue(SHORT_DESCRIPTION, libelle); - } - - public void actionPerformed(ActionEvent e) { - - if (getHandler().prepareSave()) { - - // save model to src - getHandler().getModel().save(); - - // close ui - getUi().dispose(); - } - } -} Copied: jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java (from rev 1406, jaxx/trunk/jaxx-swing-action/src/main/java/org/codelutin/jaxx/util/config/SaveAction.java) =================================================================== --- jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java (rev 0) +++ jaxx/trunk/jaxx-swing-action/src/main/java/org/nuiton/jaxx/util/config/SaveAction.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,50 @@ +/** + * ##% 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.nuiton.jaxx.util.config; + +import org.nuiton.jaxx.util.AbstractUIAction; +import org.nuiton.jaxx.util.DialogUI; +import org.nuiton.jaxx.util.UIHelper; + +import java.awt.event.ActionEvent; + +/** @author chemit */ +public class SaveAction<E extends Enum<E>, H extends DialogConfigUIHandler<E, ?, ?>> extends AbstractUIAction<H> { + private static final long serialVersionUID = 1L; + + public SaveAction(DialogUI<? extends H> dialogUI, boolean showLabel) { + super(null, UIHelper.createActionIcon("save-config"), dialogUI); + if (showLabel) { + String text = org.nuiton.i18n.I18n._("lutinui.config.save"); + putValue(NAME, text); + putValue(DISPLAYED_MNEMONIC_INDEX_KEY, 0); + putValue(MNEMONIC_KEY, (int) text.charAt(0)); + } + String libelle = org.nuiton.i18n.I18n._("lutinui.config.save.tooltip"); + putValue(SHORT_DESCRIPTION, libelle); + } + + public void actionPerformed(ActionEvent e) { + + if (getHandler().prepareSave()) { + + // save model to src + getHandler().getModel().save(); + + // close ui + getUi().dispose(); + } + } +} Copied: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton (from rev 1405, jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin) Property changes on: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton ___________________________________________________________________ Name: svn:mergeinfo + Deleted: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/AbstractJaxxMojo.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,170 +0,0 @@ -/* *##% - * Copyright (C) 2007 - * JaxxPlugin, Code Lutin - * - * 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.jaxx; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.project.MavenProject; - -import java.io.File; - -/** - * Abract Jaxx Mojo. - * - * @author chemit - * - * @since 1.3 - */ -public abstract class AbstractJaxxMojo extends AbstractMojo { - - /** - * Dépendance du projet. - * - * @parameter default-value="${project}" - * @required - * @readonly - */ - protected MavenProject project; - /** - * Repertoire de destination des fichiers java a generer. - * - * @parameter expression="${jaxx.outJava}" default-value="${basedir}/target/generated-sources/java" - */ - protected File outJava; - /** - * verbose flag - * - * @parameter expression="${jaxx.verbose}" default-value="false" - * - * @since 1.3 - */ - protected boolean verbose; - /** - * to make compiler i18nable, says add the {@link org.codelutin.i18n.I18n#_(String, Object[])} method - * invocation on {@link jaxx.compiler.I18nHelper#I18N_ATTRIBUTES} attributes. - * - * @parameter expression="${jaxx.i18nable}" default-value="true" - * @see jaxx.compiler.I18nHelper - */ - protected boolean i18nable; - /** - * The store of helpIds generated by {@link JaxxGeneratorMojo}. - * <p/> - * - * @parameter expression="${jaxx.helpIdStore}" default-value="target/helpIds.properties" - * @required - * - * @since 1.3 - */ - protected File helpIdStore; - /** - * The name of the helpset to generate. - * - * @parameter expression="${jaxx.helpSetName}" default-value="${project.artifactId}" - * @required - * - * @since 1.3 - */ - protected String helpSetName; - /** - * The prefix to add to i18n key for any help i18n key. - * - * @parameter expression="${jaxx.helpsetI18nPrefix}" default-value="${jaxx.helpSetName}.help." - * @required - * - * @since 1.3 - */ - protected String helpsetI18nPrefix; - /** - * The suffix to add to i18n key for an help Id. - * - * @parameter expression="${jaxx.helpsetTitleI18nSuffix}" default-value=".title" - * @required - * - * @since 1.3 - */ - protected String helpsetTitleI18nSuffix; - /** - * The suffix to add to i18n key for an toc Id. - * - * @parameter expression="${jaxx.helpsetTocI18nSuffix}" default-value=".toc" - * @required - * - * @since 1.3 - */ - protected String helpsetTocI18nSuffix; - /** - * The suffix to add to i18n key for an toc Id. - * - * @parameter expression="${jaxx.helpsetIndexI18nSuffix}" default-value=".index" - * @required - * - * @since 1.3 - */ - protected String helpsetIndexI18nSuffix; - protected boolean skip = true; - protected ClassLoader cl; - - public abstract void init() throws Exception; - - public abstract void doAction() throws Exception; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - try { - init(); - } catch (Exception e) { - if (e instanceof MojoFailureException) { - throw (MojoFailureException) e; - } - if (e instanceof MojoExecutionException) { - throw (MojoExecutionException) e; - } - throw new MojoExecutionException("error in init : " + e.getMessage(), e); - } - - if (skip) { - if (verbose) { - getLog().info("jaxx - skip!"); - } - return; - } - - try { - - doAction(); - - } catch (Exception e) { - //getLog().error(e); - Throwable e2 = e; - while (e2.getCause() != null) { - e2 = e.getCause(); - } - getLog().error(e2); - - throw new MojoExecutionException(e2.getMessage(), e2); - } finally { - System.gc(); - } - - } - -} \ No newline at end of file Copied: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java (from rev 1406, jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/AbstractJaxxMojo.java) =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java (rev 0) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/AbstractJaxxMojo.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,170 @@ +/* *##% + * Copyright (C) 2007 + * JaxxPlugin, Code Lutin + * + * 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.nuiton.jaxx; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.project.MavenProject; + +import java.io.File; + +/** + * Abract Jaxx Mojo. + * + * @author chemit + * + * @since 1.3 + */ +public abstract class AbstractJaxxMojo extends AbstractMojo { + + /** + * Dépendance du projet. + * + * @parameter default-value="${project}" + * @required + * @readonly + */ + protected MavenProject project; + /** + * Repertoire de destination des fichiers java a generer. + * + * @parameter expression="${jaxx.outJava}" default-value="${basedir}/target/generated-sources/java" + */ + protected File outJava; + /** + * verbose flag + * + * @parameter expression="${jaxx.verbose}" default-value="false" + * + * @since 1.3 + */ + protected boolean verbose; + /** + * to make compiler i18nable, says add the {@link org.nuiton.i18n.I18n#_(String, Object[])} method + * invocation on {@link jaxx.compiler.I18nHelper#I18N_ATTRIBUTES} attributes. + * + * @parameter expression="${jaxx.i18nable}" default-value="true" + * @see jaxx.compiler.I18nHelper + */ + protected boolean i18nable; + /** + * The store of helpIds generated by {@link JaxxGeneratorMojo}. + * <p/> + * + * @parameter expression="${jaxx.helpIdStore}" default-value="target/helpIds.properties" + * @required + * + * @since 1.3 + */ + protected File helpIdStore; + /** + * The name of the helpset to generate. + * + * @parameter expression="${jaxx.helpSetName}" default-value="${project.artifactId}" + * @required + * + * @since 1.3 + */ + protected String helpSetName; + /** + * The prefix to add to i18n key for any help i18n key. + * + * @parameter expression="${jaxx.helpsetI18nPrefix}" default-value="${jaxx.helpSetName}.help." + * @required + * + * @since 1.3 + */ + protected String helpsetI18nPrefix; + /** + * The suffix to add to i18n key for an help Id. + * + * @parameter expression="${jaxx.helpsetTitleI18nSuffix}" default-value=".title" + * @required + * + * @since 1.3 + */ + protected String helpsetTitleI18nSuffix; + /** + * The suffix to add to i18n key for an toc Id. + * + * @parameter expression="${jaxx.helpsetTocI18nSuffix}" default-value=".toc" + * @required + * + * @since 1.3 + */ + protected String helpsetTocI18nSuffix; + /** + * The suffix to add to i18n key for an toc Id. + * + * @parameter expression="${jaxx.helpsetIndexI18nSuffix}" default-value=".index" + * @required + * + * @since 1.3 + */ + protected String helpsetIndexI18nSuffix; + protected boolean skip = true; + protected ClassLoader cl; + + public abstract void init() throws Exception; + + public abstract void doAction() throws Exception; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + + try { + init(); + } catch (Exception e) { + if (e instanceof MojoFailureException) { + throw (MojoFailureException) e; + } + if (e instanceof MojoExecutionException) { + throw (MojoExecutionException) e; + } + throw new MojoExecutionException("error in init : " + e.getMessage(), e); + } + + if (skip) { + if (verbose) { + getLog().info("jaxx - skip!"); + } + return; + } + + try { + + doAction(); + + } catch (Exception e) { + //getLog().error(e); + Throwable e2 = e; + while (e2.getCause() != null) { + e2 = e.getCause(); + } + getLog().error(e2); + + throw new MojoExecutionException(e2.getMessage(), e2); + } finally { + System.gc(); + } + + } + +} \ No newline at end of file Deleted: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/JaxxGeneratorMojo.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,585 +0,0 @@ -/* *##% - * Copyright (C) 2007 - * JaxxPlugin, Code Lutin - * - * 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.jaxx; - -import jaxx.beaninfos.BeanInfoUtil; -import jaxx.compiler.CompilerOptions; -import jaxx.compiler.JAXXCompiler; -import jaxx.compiler.JAXXCompilerLaunchor; -import jaxx.runtime.JAXXContext; -import jaxx.tags.TagManager; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.codehaus.plexus.util.DirectoryScanner; -import org.codelutin.util.FileUpdaterHelper; -import org.codelutin.util.MirroredFileUpdater; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.reflect.Modifier; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import jaxx.compiler.CompiledObjectDecorator; -import jaxx.compiler.HelpRootCompiledObjectDecorator; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.project.MavenProject; - -/** - * Classe permettant de transformer des sources jaxx vers du source java. - * - * @author chemit - * @goal generate - * @phase process-sources - * @requiresDependencyResolution compile - * @requiresProject - */ -public class JaxxGeneratorMojo extends AbstractJaxxMojo { - - /** - * Le compilateur à utiliser (par défaut celui de Swing) - * - * @parameter expression="${jaxx.compilerFQN}" default-value="jaxx.compiler.SwingCompiler" - */ - protected String compilerFQN; - /** - * Le compilateur à utiliser (par défaut celui de Swing) - * - * @parameter expression="${jaxx.validatorFQN}" default-value="jaxx.runtime.validator.swing.SwingValidator" - */ - protected String validatorFQN; - /** - * chemin du repertoire de generation des resources. - * - * @parameter expression="${jaxx.outResource}" default-value="${basedir}/target/generated-sources/resources" - */ - protected File outResource; - /** - * chemin du repertoire de compilation des resources. - * - * @parameter expression="${jaxx.outClass}" default-value="${basedir}/target/classes" - */ - protected File outClass; - /** - * Repertoire sources des fichiers jaxx a generer. - * - * @parameter expression="${jaxx.src}" default-value="${maven.src.dir}/main/java" - */ - protected File src; - /** - * pour optimizer le code compile ou genere ? - * - * @parameter expression="${jaxx.optimize}" default-value="false" - */ - protected boolean optimize; - /** - * les options de la compilation - * - * @parameter expression="${jaxx.javaOpts}" - */ - protected String javaOpts = null; - /** - * pour filter les fichiers a traiter - * - * @parameter expression="${jaxx.includes}" - */ - protected String[] includes; - /** - * pour filter les fichiers a ne pas traiter - * - * @parameter expression="${jaxx.excludes}" - */ - protected String[] excludes; - /** - * flag to include in compiler classpath the java sources directories (src and outJava). - * <p/> - * By default, false. - * - * @parameter expression="${jaxx.addSourcesToClassPath}" default-value="false" - */ - protected boolean addSourcesToClassPath; - /** - * flag to include in compiler classpath the project compile classpath. - * <p/> - * By default, false. - * - * @parameter expression="${jaxx.addProjectClassPath}" default-value="false" - */ - protected boolean addProjectClassPath; - /** - * to force generation of java source for any jaxx files with no timestamp checking. - * <p/> - * By default, never force generation. - * - * @parameter expression="${jaxx.force}" default-value="false" - */ - protected boolean force; - /** - * flag to add logger to each generated jaxx file. - * <p/> - * By default, always add it. - * - * @parameter expression="${jaxx.addLogger}" default-value="true" - */ - protected boolean addLogger; - /** - * flag to keep compilers after the generate operation (usefull for tests. - * <p/> - * By default, always reset. - * - * @parameter expression="${jaxx.resetAfterCompile}" default-value="true" - */ - protected boolean resetAfterCompile; - /** - * the name of implementation of {@link jaxx.runtime.JAXXContext} - * to be used on {@link jaxx.runtime.JAXXObject}. - * <p/> - * Must not be abstract. - * - * @parameter expression="${jaxx.jaxxContextImplementorClass}" default-value="jaxx.runtime.DefaultJAXXContext" - * @required - */ - protected String jaxxContextImplementorClass; - /** - * extra path to be added in {@link java.beans.Introspector#setBeanInfoSearchPath(String[])}. - * <p/> - * add beanInfoSearchPath to be registred by {@link BeanInfoUtil#addJaxxBeanInfoPath(String[])} - * <p/> - * and then will be use by {@link jaxx.tags.swing.SwingInitializer#initialize()}. - * <p/> - * <p/> - * This permit to use real beanInfo of imported graphic libraries. - * - * @parameter expression="${jaxx.beanInfoSearchPath}" - */ - protected String[] beanInfoSearchPath; - /** - * list of fqn of class toimport for all generated jaxx files - * - * @parameter expression="${jaxx.extraImports}" - * - * @deprecated Prefer use of extraImportList as a string, so - * could be use in properties section. - */ - protected String[] extraImports; - /** - * list of fqn of class toimport for all generated jaxx files - * - * @parameter expression="${jaxx.extraImportList}" - */ - protected String extraImportList; - /** - * the FQN of the ui to use for error notification. - * <p/> - * If not given, will use the one defined in validator - * - * @parameter expression="${jaxx.defaultErrorUIFQN}" - * @see jaxx.runtime.validator.swing.SwingValidator#DEFAULT_UI_CLASS - */ - protected String defaultErrorUIFQN; - /** - * the FQN of the ui to use for error notification. - * <p/> - * If not given, will use the one defined in validator - * - * @parameter expression="${jaxx.defaultDecorator}" default-value="jaxx.compiler.DefaultCompiledObjectDecorator" - * - * @see jaxx.compiler.CompiledObjectDecorator - */ - protected String defaultDecoratorFQN; - /** - * a flag to use UIManager to retreave icons. - * - * @parameter expression="${jaxx.useUIManagerForIcon}" default-value="false" - */ - protected boolean useUIManagerForIcon; - /** - * flag to activate profile mode. - * <p/> - * By default, not active. - * - * @parameter expression="${jaxx.profile}" default-value="false" - */ - protected boolean profile; - /** - * flag to activate help generation process. - * <p/> - * By default, not active. - * - * @parameter expression="${jaxx.generateHelp}" default-value="false" - * - * @since 1.3 - */ - private boolean generateHelp; - /** - * the FQN of help broker - * <p/> - * By default, none. - * - * @parameter expression="${jaxx.helpBrokerFQN}" - * - * @since 1.3 - */ - private String helpBrokerFQN; - protected String[] files; - private static final String[] INCLUDES = {"**\\/*.jaxx"}; - protected CompilerOptions options; - protected MirroredFileUpdater updater; - private Class<?> defaultErrorUIClass; - private Class<? extends CompiledObjectDecorator> defaultDecoratorClass; - private Class<? extends JAXXCompiler> compilerClass; - - @SuppressWarnings("unchecked") - @Override - public void init() throws Exception { - - if (project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging()))) { - // nothing to be done for this type of packaging - skip = true; - getLog().info("skip generate goal for packaging " + project.getPackaging()); - return; - } - - if (generateHelp) { - // check there is some bundle - if (helpIdStore == null) { - throw new MojoFailureException("you must set the helpIdStore property."); - } - } - - compilerClass = (Class<? extends JAXXCompiler>) Class.forName(compilerFQN); - defaultDecoratorClass = (Class<? extends CompiledObjectDecorator>) Class.forName(defaultDecoratorFQN); - - // check the validator class is correct - Class.forName(validatorFQN); - - if (defaultErrorUIFQN != null && !defaultErrorUIFQN.trim().isEmpty()) { - defaultErrorUIClass = Class.forName(defaultErrorUIFQN); - } - skip = false; - - checkJaxxContextImplementorClass(); - - if (beanInfoSearchPath != null && beanInfoSearchPath.length > 0) { - // regisre extra path - BeanInfoUtil.addJaxxBeanInfoPath(beanInfoSearchPath); - } - if (!outResource.exists()) { - outResource.mkdirs(); - } - - if (!outJava.exists()) { - outJava.mkdirs(); - } - - fixCompileSourceRoots(); - - if (addSourcesToClassPath || addProjectClassPath) { - cl = initClassLoader(project, getLog()); - Thread.currentThread().setContextClassLoader(cl); - } - DirectoryScanner ds; - ds = new DirectoryScanner(); - ds.setBasedir(src); - boolean noIncludes = includes == null || includes.length == 0; - ds.setIncludes(noIncludes ? INCLUDES : includes); - - if (excludes != null && excludes.length > 0) { - ds.setExcludes(excludes); - } - - ds.scan(); - String[] filesFind = ds.getIncludedFiles(); - if (verbose) { - getLog().info("jaxx - discover " + filesFind.length + " jaxx file(s). "); - } - - updater = (MirroredFileUpdater) FileUpdaterHelper.newJaxxFileUpdater(src, outJava); - - if (force) { - // we will regenerate all files - this.files = filesFind; - } else { - // filter files - List<String> listFiles = new ArrayList<String>(); - - for (String file : filesFind) { - if (updater.isFileUpToDate(new File(src, file))) { - if (verbose) { - getLog().info("jaxx - skip file [" + file + "]."); - } - } else { - if (verbose) { - getLog().info("jaxx - detect modify file [" + file + "]."); - } - listFiles.add(file); - } - } - this.files = listFiles.toArray(new String[listFiles.size()]); - } - - if (extraImportList != null && !extraImportList.isEmpty()) { - String[] imports = extraImportList.split(","); - int i = 0; - for (String importS : imports) { - imports[i++] = importS.trim(); - } - if (verbose) { - getLog().info("extra imports " + java.util.Arrays.toString(imports)); - } - extraImports = imports; - - } - options = toCompilerOptions(); - - if (verbose) { - printInit(); - } - - } - - @Override - public void doAction() throws MojoExecutionException { - getLog().info("jaxx - detects " + this.files.length + " modify jaxx file(s). "); - - try { - - // force compiler init from here, not in a static block - TagManager.reset(verbose); - - JAXXCompilerLaunchor launchor = JAXXCompilerLaunchor.newLaunchor(src, files, options); - boolean success = launchor.compile(); - getLog().info("jaxx - generate " + launchor.getCompilerCount() + " file(s). "); - - if (!success) { - throw new MojoExecutionException("Aborting due to errors reported by jaxxc"); - } - - if (generateHelp) { - // generate help - generateHelp(); - } - - } catch (MojoExecutionException e) { - getLog().error(e); - throw e; - } catch (Exception e) { - //getLog().error(e); - Throwable e2 = e; - while (e2.getCause() != null) { - e2 = e.getCause(); - } - getLog().error(e2); - - throw new MojoExecutionException(e2.getMessage(), e2); - } - } - - public CompilerOptions toCompilerOptions() { - CompilerOptions result = new CompilerOptions(); - result.setClassPath(src.getPath()); - if (javaOpts != null && !"".equals(javaOpts)) { - result.setJavacOpts(javaOpts); - } - result.setCompilerClass(compilerClass); - result.setValidatorFQN(validatorFQN); - result.setKeepJavaFiles(true); - result.setOptimize(optimize); - result.setJavacTargetDirectory(outClass); - result.setTargetDirectory(outJava); - result.setVerbose(verbose); - result.setI18nable(i18nable); - result.setAddLogger(addLogger); - result.setProfile(profile); - result.setResetAfterCompile(resetAfterCompile); - result.setJaxxContextImplementorClass(jaxxContextImplementorClass); - result.setExtraImports(extraImports); - result.setDefaultErrorUI(defaultErrorUIClass); - result.setUseUIManagerForIcon(useUIManagerForIcon); - result.setDefaultDecoratorClass(defaultDecoratorClass); - result.setGenerateHelp(generateHelp); - result.setHelpBrokerFQN(helpBrokerFQN); - result.setHelpsetTitleI18nSuffix(helpsetTitleI18nSuffix); - result.setHelpsetIndexI18nSuffix(helpsetIndexI18nSuffix); - result.setHelpsetTocI18nSuffix(helpsetTocI18nSuffix); - result.setHelpSetName(helpSetName); - result.setHelpsetI18nPrefix(helpsetI18nPrefix); - - if (cl != null) { - result.setClassLoader(cl); - } - return result; - } - - protected void fixCompileSourceRoots() { - //fixme should remove this silly test when we will make real maven plugin tests :) - if (project != null) { - if (!project.getCompileSourceRoots().contains(outJava.getPath())) { - project.addCompileSourceRoot(outJava.getPath()); - } - } - } - - protected void printInit() { - getLog().info(options.toString()); - getLog().info("includes : " + Arrays.toString(includes)); - for (String file : files) { - getLog().info("will generate " + file); - } - - ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); - getLog().info(threadLoader.toString()); - if (threadLoader.getClass().getSimpleName().equals("RealmClassLoader")) { - try { - java.lang.reflect.Method m = threadLoader.getClass().getDeclaredMethod("getURLs"); - m.setAccessible(true); - URL[] urls = (URL[]) m.invoke(threadLoader); - - for (URL url : urls) { - getLog().info("url in class loader " + url); - } - } catch (Exception e) { - getLog().warn("??? : " + e.getMessage(), e); - } - } - - //fixme should remove this silly test when we will make real maven plugin tests :) - if (getPluginContext() != null) { - for (Object e : getPluginContext().keySet()) { - getLog().info("pluginContext " + e + " : " + getPluginContext().get(e)); - } - } - } - - protected void checkJaxxContextImplementorClass() { - if (jaxxContextImplementorClass == null) { - throw new IllegalArgumentException("jaxxContextImplementor can not be null"); - } - try { - Class jaxxContextImplementor = Class.forName(jaxxContextImplementorClass); - if (!JAXXContext.class.isAssignableFrom(jaxxContextImplementor)) { - throw new IllegalArgumentException("jaxxContextImplementor '" + jaxxContextImplementor + "' does not implements " + JAXXContext.class); - } - if (Modifier.isAbstract(jaxxContextImplementor.getModifiers())) { - throw new IllegalArgumentException("jaxxContextImplementor '" + jaxxContextImplementor + "' can not be abstract."); - - } - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("could not find jaxxContextImplementor class : " + jaxxContextImplementorClass); - } - } - - protected void generateHelp() throws IOException { - Set<String> helpIds = HelpRootCompiledObjectDecorator.getHelpIds(); - if (helpIds.isEmpty()) { - if (verbose) { - // no ids detected in this compilation round - getLog().info("no helpIds detected."); - } - return; - } - - if (!helpIdStore.getParentFile().exists()) { - helpIdStore.getParentFile().mkdirs(); - } - - Properties p = new Properties(); - - for (String helpId : helpIds) { - String path = helpId.replaceAll("\\.", File.separator); - path = removeQuote(path) + ".html"; - p.put(removeQuote(helpId), path); - } - - FileOutputStream w = new FileOutputStream(helpIdStore); - - try { - p.store(w, null); - } finally { - w.close(); - } - - getLog().info("helpIdStore generated in " + helpIdStore); - - helpIds.clear(); - } - - @SuppressWarnings({"unchecked"}) - protected URLClassLoader initClassLoader(MavenProject project, org.apache.maven.plugin.logging.Log log) throws MalformedURLException { - URLClassLoader loader = null; - if (project != null) { - - URLClassLoader result; - try { - - List<URL> lUrls = new ArrayList<URL>(); - List<String> sources = project.getCompileSourceRoots(); - - if (addSourcesToClassPath) { - for (String source : sources) { - lUrls.add(new File(source).toURI().toURL()); - } - } - if (addProjectClassPath) { - getLog().info("use project compile scope class-path"); - // add also all dependencies of the project in compile scope - Set artifacts = project.getArtifacts(); - for (Object o : artifacts) { - Artifact a = (Artifact) o; - lUrls.add(a.getFile().toURI().toURL()); - } - } - - result = new URLClassLoader(lUrls.toArray(new URL[lUrls.size()]), getClass().getClassLoader()); - - } catch (IOException e) { - throw new RuntimeException("Can't create ClassLoader for reason " + e.getMessage(), e); - } - loader = result; - } else { - List<URL> lUrls = new ArrayList<URL>(); - if (addSourcesToClassPath) { - lUrls.add(src.toURI().toURL()); - } - loader = new URLClassLoader(lUrls.toArray(new URL[lUrls.size()]), getClass().getClassLoader()); - } - if (verbose) { - for (URL entry : loader.getURLs()) { - log.info("classpath : " + entry); - } - } - return loader; - } - - protected String removeQuote(String txt) { - if (txt.startsWith("\"")) { - txt = txt.substring(1); - } - if (txt.endsWith("\"")) { - txt = txt.substring(0, txt.length() - 1); - } - return txt; - } -} \ No newline at end of file Copied: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java (from rev 1406, jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/JaxxGeneratorMojo.java) =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java (rev 0) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxGeneratorMojo.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,585 @@ +/* *##% + * Copyright (C) 2007 + * JaxxPlugin, Code Lutin + * + * 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.nuiton.jaxx; + +import jaxx.beaninfos.BeanInfoUtil; +import jaxx.compiler.CompilerOptions; +import jaxx.compiler.JAXXCompiler; +import jaxx.compiler.JAXXCompilerLaunchor; +import jaxx.runtime.JAXXContext; +import jaxx.tags.TagManager; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.codehaus.plexus.util.DirectoryScanner; +import org.nuiton.util.FileUpdaterHelper; +import org.nuiton.util.MirroredFileUpdater; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.Modifier; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import jaxx.compiler.CompiledObjectDecorator; +import jaxx.compiler.HelpRootCompiledObjectDecorator; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.project.MavenProject; + +/** + * Classe permettant de transformer des sources jaxx vers du source java. + * + * @author chemit + * @goal generate + * @phase process-sources + * @requiresDependencyResolution compile + * @requiresProject + */ +public class JaxxGeneratorMojo extends AbstractJaxxMojo { + + /** + * Le compilateur à utiliser (par défaut celui de Swing) + * + * @parameter expression="${jaxx.compilerFQN}" default-value="jaxx.compiler.SwingCompiler" + */ + protected String compilerFQN; + /** + * Le compilateur à utiliser (par défaut celui de Swing) + * + * @parameter expression="${jaxx.validatorFQN}" default-value="jaxx.runtime.validator.swing.SwingValidator" + */ + protected String validatorFQN; + /** + * chemin du repertoire de generation des resources. + * + * @parameter expression="${jaxx.outResource}" default-value="${basedir}/target/generated-sources/resources" + */ + protected File outResource; + /** + * chemin du repertoire de compilation des resources. + * + * @parameter expression="${jaxx.outClass}" default-value="${basedir}/target/classes" + */ + protected File outClass; + /** + * Repertoire sources des fichiers jaxx a generer. + * + * @parameter expression="${jaxx.src}" default-value="${maven.src.dir}/main/java" + */ + protected File src; + /** + * pour optimizer le code compile ou genere ? + * + * @parameter expression="${jaxx.optimize}" default-value="false" + */ + protected boolean optimize; + /** + * les options de la compilation + * + * @parameter expression="${jaxx.javaOpts}" + */ + protected String javaOpts = null; + /** + * pour filter les fichiers a traiter + * + * @parameter expression="${jaxx.includes}" + */ + protected String[] includes; + /** + * pour filter les fichiers a ne pas traiter + * + * @parameter expression="${jaxx.excludes}" + */ + protected String[] excludes; + /** + * flag to include in compiler classpath the java sources directories (src and outJava). + * <p/> + * By default, false. + * + * @parameter expression="${jaxx.addSourcesToClassPath}" default-value="false" + */ + protected boolean addSourcesToClassPath; + /** + * flag to include in compiler classpath the project compile classpath. + * <p/> + * By default, false. + * + * @parameter expression="${jaxx.addProjectClassPath}" default-value="false" + */ + protected boolean addProjectClassPath; + /** + * to force generation of java source for any jaxx files with no timestamp checking. + * <p/> + * By default, never force generation. + * + * @parameter expression="${jaxx.force}" default-value="false" + */ + protected boolean force; + /** + * flag to add logger to each generated jaxx file. + * <p/> + * By default, always add it. + * + * @parameter expression="${jaxx.addLogger}" default-value="true" + */ + protected boolean addLogger; + /** + * flag to keep compilers after the generate operation (usefull for tests. + * <p/> + * By default, always reset. + * + * @parameter expression="${jaxx.resetAfterCompile}" default-value="true" + */ + protected boolean resetAfterCompile; + /** + * the name of implementation of {@link jaxx.runtime.JAXXContext} + * to be used on {@link jaxx.runtime.JAXXObject}. + * <p/> + * Must not be abstract. + * + * @parameter expression="${jaxx.jaxxContextImplementorClass}" default-value="jaxx.runtime.DefaultJAXXContext" + * @required + */ + protected String jaxxContextImplementorClass; + /** + * extra path to be added in {@link java.beans.Introspector#setBeanInfoSearchPath(String[])}. + * <p/> + * add beanInfoSearchPath to be registred by {@link BeanInfoUtil#addJaxxBeanInfoPath(String[])} + * <p/> + * and then will be use by {@link jaxx.tags.swing.SwingInitializer#initialize()}. + * <p/> + * <p/> + * This permit to use real beanInfo of imported graphic libraries. + * + * @parameter expression="${jaxx.beanInfoSearchPath}" + */ + protected String[] beanInfoSearchPath; + /** + * list of fqn of class toimport for all generated jaxx files + * + * @parameter expression="${jaxx.extraImports}" + * + * @deprecated Prefer use of extraImportList as a string, so + * could be use in properties section. + */ + protected String[] extraImports; + /** + * list of fqn of class toimport for all generated jaxx files + * + * @parameter expression="${jaxx.extraImportList}" + */ + protected String extraImportList; + /** + * the FQN of the ui to use for error notification. + * <p/> + * If not given, will use the one defined in validator + * + * @parameter expression="${jaxx.defaultErrorUIFQN}" + * @see jaxx.runtime.validator.swing.SwingValidator#DEFAULT_UI_CLASS + */ + protected String defaultErrorUIFQN; + /** + * the FQN of the ui to use for error notification. + * <p/> + * If not given, will use the one defined in validator + * + * @parameter expression="${jaxx.defaultDecorator}" default-value="jaxx.compiler.DefaultCompiledObjectDecorator" + * + * @see jaxx.compiler.CompiledObjectDecorator + */ + protected String defaultDecoratorFQN; + /** + * a flag to use UIManager to retreave icons. + * + * @parameter expression="${jaxx.useUIManagerForIcon}" default-value="false" + */ + protected boolean useUIManagerForIcon; + /** + * flag to activate profile mode. + * <p/> + * By default, not active. + * + * @parameter expression="${jaxx.profile}" default-value="false" + */ + protected boolean profile; + /** + * flag to activate help generation process. + * <p/> + * By default, not active. + * + * @parameter expression="${jaxx.generateHelp}" default-value="false" + * + * @since 1.3 + */ + private boolean generateHelp; + /** + * the FQN of help broker + * <p/> + * By default, none. + * + * @parameter expression="${jaxx.helpBrokerFQN}" + * + * @since 1.3 + */ + private String helpBrokerFQN; + protected String[] files; + private static final String[] INCLUDES = {"**\\/*.jaxx"}; + protected CompilerOptions options; + protected MirroredFileUpdater updater; + private Class<?> defaultErrorUIClass; + private Class<? extends CompiledObjectDecorator> defaultDecoratorClass; + private Class<? extends JAXXCompiler> compilerClass; + + @SuppressWarnings("unchecked") + @Override + public void init() throws Exception { + + if (project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging()))) { + // nothing to be done for this type of packaging + skip = true; + getLog().info("skip generate goal for packaging " + project.getPackaging()); + return; + } + + if (generateHelp) { + // check there is some bundle + if (helpIdStore == null) { + throw new MojoFailureException("you must set the helpIdStore property."); + } + } + + compilerClass = (Class<? extends JAXXCompiler>) Class.forName(compilerFQN); + defaultDecoratorClass = (Class<? extends CompiledObjectDecorator>) Class.forName(defaultDecoratorFQN); + + // check the validator class is correct + Class.forName(validatorFQN); + + if (defaultErrorUIFQN != null && !defaultErrorUIFQN.trim().isEmpty()) { + defaultErrorUIClass = Class.forName(defaultErrorUIFQN); + } + skip = false; + + checkJaxxContextImplementorClass(); + + if (beanInfoSearchPath != null && beanInfoSearchPath.length > 0) { + // regisre extra path + BeanInfoUtil.addJaxxBeanInfoPath(beanInfoSearchPath); + } + if (!outResource.exists()) { + outResource.mkdirs(); + } + + if (!outJava.exists()) { + outJava.mkdirs(); + } + + fixCompileSourceRoots(); + + if (addSourcesToClassPath || addProjectClassPath) { + cl = initClassLoader(project, getLog()); + Thread.currentThread().setContextClassLoader(cl); + } + DirectoryScanner ds; + ds = new DirectoryScanner(); + ds.setBasedir(src); + boolean noIncludes = includes == null || includes.length == 0; + ds.setIncludes(noIncludes ? INCLUDES : includes); + + if (excludes != null && excludes.length > 0) { + ds.setExcludes(excludes); + } + + ds.scan(); + String[] filesFind = ds.getIncludedFiles(); + if (verbose) { + getLog().info("jaxx - discover " + filesFind.length + " jaxx file(s). "); + } + + updater = (MirroredFileUpdater) FileUpdaterHelper.newJaxxFileUpdater(src, outJava); + + if (force) { + // we will regenerate all files + this.files = filesFind; + } else { + // filter files + List<String> listFiles = new ArrayList<String>(); + + for (String file : filesFind) { + if (updater.isFileUpToDate(new File(src, file))) { + if (verbose) { + getLog().info("jaxx - skip file [" + file + "]."); + } + } else { + if (verbose) { + getLog().info("jaxx - detect modify file [" + file + "]."); + } + listFiles.add(file); + } + } + this.files = listFiles.toArray(new String[listFiles.size()]); + } + + if (extraImportList != null && !extraImportList.isEmpty()) { + String[] imports = extraImportList.split(","); + int i = 0; + for (String importS : imports) { + imports[i++] = importS.trim(); + } + if (verbose) { + getLog().info("extra imports " + java.util.Arrays.toString(imports)); + } + extraImports = imports; + + } + options = toCompilerOptions(); + + if (verbose) { + printInit(); + } + + } + + @Override + public void doAction() throws MojoExecutionException { + getLog().info("jaxx - detects " + this.files.length + " modify jaxx file(s). "); + + try { + + // force compiler init from here, not in a static block + TagManager.reset(verbose); + + JAXXCompilerLaunchor launchor = JAXXCompilerLaunchor.newLaunchor(src, files, options); + boolean success = launchor.compile(); + getLog().info("jaxx - generate " + launchor.getCompilerCount() + " file(s). "); + + if (!success) { + throw new MojoExecutionException("Aborting due to errors reported by jaxxc"); + } + + if (generateHelp) { + // generate help + generateHelp(); + } + + } catch (MojoExecutionException e) { + getLog().error(e); + throw e; + } catch (Exception e) { + //getLog().error(e); + Throwable e2 = e; + while (e2.getCause() != null) { + e2 = e.getCause(); + } + getLog().error(e2); + + throw new MojoExecutionException(e2.getMessage(), e2); + } + } + + public CompilerOptions toCompilerOptions() { + CompilerOptions result = new CompilerOptions(); + result.setClassPath(src.getPath()); + if (javaOpts != null && !"".equals(javaOpts)) { + result.setJavacOpts(javaOpts); + } + result.setCompilerClass(compilerClass); + result.setValidatorFQN(validatorFQN); + result.setKeepJavaFiles(true); + result.setOptimize(optimize); + result.setJavacTargetDirectory(outClass); + result.setTargetDirectory(outJava); + result.setVerbose(verbose); + result.setI18nable(i18nable); + result.setAddLogger(addLogger); + result.setProfile(profile); + result.setResetAfterCompile(resetAfterCompile); + result.setJaxxContextImplementorClass(jaxxContextImplementorClass); + result.setExtraImports(extraImports); + result.setDefaultErrorUI(defaultErrorUIClass); + result.setUseUIManagerForIcon(useUIManagerForIcon); + result.setDefaultDecoratorClass(defaultDecoratorClass); + result.setGenerateHelp(generateHelp); + result.setHelpBrokerFQN(helpBrokerFQN); + result.setHelpsetTitleI18nSuffix(helpsetTitleI18nSuffix); + result.setHelpsetIndexI18nSuffix(helpsetIndexI18nSuffix); + result.setHelpsetTocI18nSuffix(helpsetTocI18nSuffix); + result.setHelpSetName(helpSetName); + result.setHelpsetI18nPrefix(helpsetI18nPrefix); + + if (cl != null) { + result.setClassLoader(cl); + } + return result; + } + + protected void fixCompileSourceRoots() { + //fixme should remove this silly test when we will make real maven plugin tests :) + if (project != null) { + if (!project.getCompileSourceRoots().contains(outJava.getPath())) { + project.addCompileSourceRoot(outJava.getPath()); + } + } + } + + protected void printInit() { + getLog().info(options.toString()); + getLog().info("includes : " + Arrays.toString(includes)); + for (String file : files) { + getLog().info("will generate " + file); + } + + ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); + getLog().info(threadLoader.toString()); + if (threadLoader.getClass().getSimpleName().equals("RealmClassLoader")) { + try { + java.lang.reflect.Method m = threadLoader.getClass().getDeclaredMethod("getURLs"); + m.setAccessible(true); + URL[] urls = (URL[]) m.invoke(threadLoader); + + for (URL url : urls) { + getLog().info("url in class loader " + url); + } + } catch (Exception e) { + getLog().warn("??? : " + e.getMessage(), e); + } + } + + //fixme should remove this silly test when we will make real maven plugin tests :) + if (getPluginContext() != null) { + for (Object e : getPluginContext().keySet()) { + getLog().info("pluginContext " + e + " : " + getPluginContext().get(e)); + } + } + } + + protected void checkJaxxContextImplementorClass() { + if (jaxxContextImplementorClass == null) { + throw new IllegalArgumentException("jaxxContextImplementor can not be null"); + } + try { + Class jaxxContextImplementor = Class.forName(jaxxContextImplementorClass); + if (!JAXXContext.class.isAssignableFrom(jaxxContextImplementor)) { + throw new IllegalArgumentException("jaxxContextImplementor '" + jaxxContextImplementor + "' does not implements " + JAXXContext.class); + } + if (Modifier.isAbstract(jaxxContextImplementor.getModifiers())) { + throw new IllegalArgumentException("jaxxContextImplementor '" + jaxxContextImplementor + "' can not be abstract."); + + } + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException("could not find jaxxContextImplementor class : " + jaxxContextImplementorClass); + } + } + + protected void generateHelp() throws IOException { + Set<String> helpIds = HelpRootCompiledObjectDecorator.getHelpIds(); + if (helpIds.isEmpty()) { + if (verbose) { + // no ids detected in this compilation round + getLog().info("no helpIds detected."); + } + return; + } + + if (!helpIdStore.getParentFile().exists()) { + helpIdStore.getParentFile().mkdirs(); + } + + Properties p = new Properties(); + + for (String helpId : helpIds) { + String path = helpId.replaceAll("\\.", File.separator); + path = removeQuote(path) + ".html"; + p.put(removeQuote(helpId), path); + } + + FileOutputStream w = new FileOutputStream(helpIdStore); + + try { + p.store(w, null); + } finally { + w.close(); + } + + getLog().info("helpIdStore generated in " + helpIdStore); + + helpIds.clear(); + } + + @SuppressWarnings({"unchecked"}) + protected URLClassLoader initClassLoader(MavenProject project, org.apache.maven.plugin.logging.Log log) throws MalformedURLException { + URLClassLoader loader = null; + if (project != null) { + + URLClassLoader result; + try { + + List<URL> lUrls = new ArrayList<URL>(); + List<String> sources = project.getCompileSourceRoots(); + + if (addSourcesToClassPath) { + for (String source : sources) { + lUrls.add(new File(source).toURI().toURL()); + } + } + if (addProjectClassPath) { + getLog().info("use project compile scope class-path"); + // add also all dependencies of the project in compile scope + Set artifacts = project.getArtifacts(); + for (Object o : artifacts) { + Artifact a = (Artifact) o; + lUrls.add(a.getFile().toURI().toURL()); + } + } + + result = new URLClassLoader(lUrls.toArray(new URL[lUrls.size()]), getClass().getClassLoader()); + + } catch (IOException e) { + throw new RuntimeException("Can't create ClassLoader for reason " + e.getMessage(), e); + } + loader = result; + } else { + List<URL> lUrls = new ArrayList<URL>(); + if (addSourcesToClassPath) { + lUrls.add(src.toURI().toURL()); + } + loader = new URLClassLoader(lUrls.toArray(new URL[lUrls.size()]), getClass().getClassLoader()); + } + if (verbose) { + for (URL entry : loader.getURLs()) { + log.info("classpath : " + entry); + } + } + return loader; + } + + protected String removeQuote(String txt) { + if (txt.startsWith("\"")) { + txt = txt.substring(1); + } + if (txt.endsWith("\"")) { + txt = txt.substring(0, txt.length() - 1); + } + return txt; + } +} \ No newline at end of file Deleted: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/JaxxHelpGeneratorMojo.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,792 +0,0 @@ -/* *##% - * Copyright (C) 2007 - * JaxxPlugin, Code Lutin - * - * 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.jaxx; - -import org.apache.maven.plugin.MojoFailureException; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Enumeration; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.Stack; -import org.apache.maven.model.Resource; -import org.codelutin.i18n.I18n; -import org.codelutin.util.FileUtil; -import org.codelutin.util.SortedProperties; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; -import static org.codelutin.i18n.I18n._; - -/** - * Mojo to generate javax help stuff for your project. - * - * HelpIds should have been discovered by the JaxxMojo. - * - * @author chemit - * @goal generate-help - * @phase process-sources - * - * @requiresProject - * @requiresDependencyResolution compile - * @since 1.3 - */ -public class JaxxHelpGeneratorMojo extends AbstractJaxxMojo { - - /** - * The directory where to generate javaHelp skeleton files. - * <p/> - * Is required if generateHelp is on. - * - * @parameter expression="${jaxx.helpTarget}" alias="target" default-value="${maven.src.dir}/main/help" - * @required - * - * @since 1.3 - */ - protected File target; - /** - * The locale to generate for help. - * - * By default, stay in France. - * - * @parameter expression="${jaxx.locale}" default-value="fr" - * @required - * - * @since 1.3 - */ - protected String locale; - /** - * The package where to generate i18n java file. - * - * @parameter expression="${jaxx.packageName}" default-value="${project.groupId}" - * @required - * - * @since 1.3 - */ - protected String packageName; - /** - * The file name of the helpset to generate. - * - * @parameter expression="${jaxx.helpSetFileName}" default-value="${jaxx.helpSetName}.hs" - * @required - * - * @since 1.3 - */ - protected String helpsetFileName; - /** - * The file name of the helpset map to generate. - * - * @parameter expression="${jaxx.mapFileName}" default-value="${jaxx.helpSetName}Map.jhm" - * @required - * - * @since 1.3 - */ - protected String mapFileName; - /** - * The file name of the helpset index to generate. - * - * @parameter expression="${jaxx.indexFileName}" default-value="${jaxx.helpSetName}Index.xml" - * @required - * - * @since 1.3 - */ - protected String indexFileName; - /** - * The file name of the helpset toc to generate. - * - * @parameter expression="${jaxx.tocFileName}" default-value="${jaxx.helpSetName}TOC.xml" - * @required - * - * @since 1.3 - */ - protected String tocFileName; - /** - * The file name of the i18n java file to generate. - * - * @parameter expression="${jaxx.i8nFileName}" default-value="${jaxx.helpSetName}I18n.java" - * @required - * - * @since 1.3 - */ - protected String i8nFileName; - /** - * The template used to generate helpset file. - * - * Must be an existing file or a ressource in classp-ath - * - * @parameter expression="${jaxx.helpSetTemplate}" default-value="/defaultHelpSet.hs.vm" - * @required - * - * @since 1.3 - */ - protected File helpSetTemplate; - /** - * The template used to generate helpset map file. - * - * Must be an existing file or a ressource in classp-ath - * - * @parameter expression="${jaxx.mapTemplate}" default-value="/defaultMap.jhm.vm" - * @required - * - * @since 1.3 - */ - protected File mapTemplate; - /** - * The template used to generate helpset index file. - * - * Must be an existing file or a ressource in classp-ath - * - * @parameter expression="${jaxx.indexTemplate}" default-value="/defaultIndex.xml.vm" - * @required - * - * @since 1.3 - */ - protected File indexTemplate; - /** - * The template used to generate helpset toc file. - * - * Must be an existing file or a ressource in classp-ath - * - * @parameter expression="${jaxx.tocTemplate}" default-value="/defaultToc.xml.vm" - * @required - * - * @since 1.3 - */ - protected File tocTemplate; - /** - * The template used to generate helpset content file. - * - * Must be an existing file or a ressource in classp-ath - * - * @parameter expression="${jaxx.contentTemplate}" default-value="/defaultContent.html.vm" - * @required - * - * @since 1.3 - */ - protected File contentTemplate; - /** - * The template used to generate helpset content file. - * - * Must be an existing file or a ressource in classp-ath - * - * @parameter expression="${jaxx.i18nTemplate}" default-value="/defaultI18n.java.vm" - * @required - * - * @since 1.3 - */ - protected File i18nTemplate; - /** - * The help ids discovered by Jaxx compilation - */ - protected Properties helpIds; - private static final String AUTOREMOVE_LINE = "REMOVE THS LINE TO DISABLE AUTO-REGENERATE THE FILE"; - - @Override - public void init() throws Exception { - - if (project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging()))) { - // nothing to be done for this type of packaging - skip = true; - getLog().info("skip generate goal for packaging " + project.getPackaging()); - return; - } - - if (!helpIdStore.exists()) { - skip = true; - getLog().info("no helpIdStore to react at " + helpIdStore); - return; - } - - // check there is some bundle - if (locale == null) { - throw new MojoFailureException("you must set the bundles property."); - } - // check there is some bundle - if (target == null) { - throw new MojoFailureException("you must set the target property."); - } - // check ressources - checkResource(helpSetTemplate); - checkResource(mapTemplate); - checkResource(indexTemplate); - checkResource(tocTemplate); - checkResource(contentTemplate); - - if (!target.exists()) { - getLog().info("mkdir " + target); - target.mkdirs(); - } - - - helpIds = new SortedProperties(); - - InputStream stream = new FileInputStream(helpIdStore); - - helpIds.load(stream); - - stream.close(); - - if (helpIds.isEmpty()) { - - // no ids detected - getLog().warn("no helpIds detected, will skip."); - skip = true; - return; - } - - skip = false; - } - - @Override - public void doAction() throws Exception { - - if (i18nable) { - - List<URL> lUrls = new java.util.ArrayList<URL>(); - List resources = project.getResources(); - for (Object o : resources) { - Resource resource = (Resource) o; - lUrls.add(new File(resource.getDirectory()).toURI().toURL()); - } - I18n.setExtraURL(lUrls.toArray(new URL[lUrls.size()])); - I18n.init(locale, null); - } - - File file; - - Properties env = new Properties(); - - env.put("helpSetName", helpSetName); - env.put("helpSetFileName", helpsetFileName); - env.put("mapFileName", mapFileName); - env.put("indexFileName", indexFileName); - env.put("tocFileName", tocFileName); - env.put("separator", " "); - env.put("autoremoveLine", AUTOREMOVE_LINE); - - - int touchedFiles = 0; - - // --------------------------------------------------------------- - // --- main helpset file ----------------------------------------- - // --------------------------------------------------------------- - - - file = new File(target, helpsetFileName); - - boolean doCreate = generateHelSetFile(file, env); - - if (doCreate) { - touchedFiles++; - } - - // --------------------------------------------------------------- - // --- helpset map file ------------------------------------------ - // --------------------------------------------------------------- - - file = new File(target, mapFileName); - - Properties mergedHelpIds = generateMapFile(file, env); - touchedFiles++; - - // --------------------------------------------------------------- - // --- helpset index file ---------------------------------------- - // --------------------------------------------------------------- - - file = new File(target, indexFileName); - - NodeItem indexRootItem = generateIndexFile(file, env); - touchedFiles++; - - // --------------------------------------------------------------- - // --- helpset toc file ------------------------------------------ - // --------------------------------------------------------------- - - file = new File(target, tocFileName); - - NodeItem tocRootItem = generateTocFile(file, env); - touchedFiles++; - - // --------------------------------------------------------------- - // --- helpset content files ------------------------------------- - // --------------------------------------------------------------- - - TemplateGenerator gen = prepareGenerator(contentTemplate); - - Enumeration keys = helpIds.keys(); - - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - String url = (String) helpIds.get(key); - url = helpSetName + File.separator + url; - - File f = new File(target, url); - - boolean exist = f.exists(); - - if (exist) { - // check if there is a autoremoveLine in content - String content = FileUtil.readAsString(f); - if (!content.contains(AUTOREMOVE_LINE)) { - // no regenerate marker detected, so skip this file - if (verbose) { - getLog().debug("skip existing file " + f); - } - continue; - } - } - - f.getParentFile().mkdirs(); - - if (verbose) { - if (exist) { - getLog().info("regenerate content file " + f); - } else { - getLog().info("generate content file " + f); - } - } - - env.put("helpId", key); - String i18n = helpsetI18nPrefix + key + helpsetTitleI18nSuffix; - env.put("helpIdTitle", _(i18n)); - env.put("helpIdUrl", url); - - gen.generate(env, f); - touchedFiles++; - } - - // --------------------------------------------------------------- - // --- i18n file ------------------------------------------------- - // --------------------------------------------------------------- - - String path = packageName.replaceAll("\\.", File.separator); - path += File.separator + i8nFileName; - file = new File(outJava, path); - generateI18nFile(file, env, mergedHelpIds, indexRootItem, tocRootItem); - touchedFiles++; - - getLog().info(touchedFiles + " file(s) treated."); - } - - protected void generateI18nFile(File file, Properties env, Properties mergedHelpIds, NodeItem indexRootItem, NodeItem tocRootItem) throws Exception { - - boolean create = !file.exists(); - - if (!file.getParentFile().exists()) { - file.getParentFile().mkdirs(); - } - - Set<String> keys = new java.util.HashSet<String>(); - - for (Object k : mergedHelpIds.keySet()) { - String key = helpsetI18nPrefix + k + helpsetTitleI18nSuffix; - keys.add(key); - } - indexRootItem.extractI18n(keys, helpsetI18nPrefix, helpsetIndexI18nSuffix); - tocRootItem.extractI18n(keys, helpsetI18nPrefix, helpsetTocI18nSuffix); - - env.put("keys", keys); - env.put("packageName", packageName); - String className = file.getName(); - int index = className.lastIndexOf("."); - className = className.substring(0, index); - env.put("className", className); - - if (verbose) { - if (create) { - getLog().info("generate i18n java file " + file); - } else { - getLog().info("udpate i18n java file " + file); - } - } - - doGen(i18nTemplate, file, env); - - } - - protected boolean generateHelSetFile(File file, Properties env) throws Exception { - - if (file.exists()) { - // check the auto removeline presence - String content = FileUtil.readAsString(file); - if (!content.contains(AUTOREMOVE_LINE)) { - // no regenerate marker detected, so skip this file - if (verbose) { - getLog().info("skip existing helpset main file " + file); - } - return false; - } - } - - if (verbose) { - if (file.exists()) { - getLog().info("regenerate helpset main file " + file); - } else { - getLog().info("generate helpset main file " + file); - } - } - doGen(helpSetTemplate, file, env); - return true; - } - - protected Properties generateMapFile(File file, Properties env) throws Exception { - - boolean create; - - Properties mergedHelpIds = null; - if (file.exists()) { - - // get back the exisiting data and merge it with incoming ones - - if (verbose) { - getLog().info("loading existing helpset map file " + file); - } - - mergedHelpIds = getExistingHelpIds(file); - create = false; - - } else { - - mergedHelpIds = new SortedProperties(); - create = true; - } - - // inject new helpIds - - for (Object k : helpIds.keySet()) { - mergedHelpIds.put(k, helpSetName + "/" + helpIds.get(k)); - } - - if (!mergedHelpIds.contains("top")) { - // on ajoute une entree vers le root du helpset - - String topUrl = helpSetName + ".html"; - helpIds.put("top", topUrl); - mergedHelpIds.put("top", helpSetName + "/" + topUrl); - if (verbose) { - getLog().debug("add top entry with url " + topUrl); - } - } - - if (verbose) { - if (create) { - getLog().info("generate helpset map file " + file); - } else { - getLog().info("udpate helpset map file " + file); - } - } - - env.put("helpIds", mergedHelpIds); - doGen(mapTemplate, file, env); - env.remove("helpIds"); - return mergedHelpIds; - } - - protected NodeItem generateIndexFile(File file, Properties env) throws Exception { - NodeItem rootItem = null; - - boolean create; - - if (file.exists()) { - - create = false; - - rootItem = getExistingItems("indexitem", file); - } else { - create = true; - } - - if (rootItem == null) { - rootItem = new NodeItem("top", helpSetName); - } - - // inject new index entries - - for (Object k : helpIds.keySet()) { - NodeItem toc = rootItem.findChild(k + ""); - if (verbose) { - getLog().debug("index " + k + " : " + toc); - } - } - - //String prefix = helpsetI18nPrefix; - //String prefix = helpsetI18nPrefix + helpSetName + "."; - rootItem.applyI18n(helpsetI18nPrefix, helpsetIndexI18nSuffix); - - if (verbose) { - if (create) { - getLog().info("generate helpset index file " + file); - } else { - getLog().info("udpate helpset index file " + file); - } - } - - env.put("rootItem", rootItem); - doGen(indexTemplate, file, env); - env.remove("rootItem"); - return rootItem; - } - - protected NodeItem generateTocFile(File file, Properties env) throws Exception { - NodeItem rootItem = null; - - boolean create; - - if (file.exists()) { - - create = false; - - rootItem = getExistingItems("tocitem", file); - } else { - create = true; - } - - if (rootItem == null) { - rootItem = new NodeItem("top", helpSetName); - } - // inject new toc entries - - for (Object k : helpIds.keySet()) { - NodeItem toc = rootItem.findChild(k + ""); - if (verbose) { - getLog().debug("toc " + k + " : " + toc); - } - } - - //String prefix = helpsetI18nPrefix + helpSetName + "."; - rootItem.applyI18n(helpsetI18nPrefix, helpsetTocI18nSuffix); - - if (verbose) { - if (create) { - getLog().info("generate helpset toc file " + file); - } else { - getLog().info("udpate helpset toc file " + file); - } - } - - env.put("rootItem", rootItem); - doGen(tocTemplate, file, env); - env.remove("rootItem"); - return rootItem; - } - - protected void doGen(File template, File f, Properties env) throws Exception { - TemplateGenerator gen = prepareGenerator(template); - gen.generate(env, f); - } - - protected TemplateGenerator prepareGenerator(File template) throws Exception { - URL templateURL = getTemplate(template); - - if (verbose) { - getLog().info("using template " + templateURL); - } - TemplateGenerator gen = new TemplateGenerator(project, templateURL); - return gen; - } - - protected URL getTemplate(File f) throws IOException { - URL r = null; - InputStream s = null; - if (f.exists()) { - r = f.toURI().toURL(); - } else { - r = getClass().getResource(f.toString()); - } - return r; - } - - protected void checkResource(File f) throws MojoFailureException { - if (!f.exists()) { - // test in classPath - InputStream r = getClass().getResourceAsStream(f.toString()); - if (r == null) { - throw new MojoFailureException("could not find ressource " + f); - } - } - } - - protected Properties getExistingHelpIds(File file) throws SAXException, IOException { - - final Properties result = new SortedProperties(); - - XMLReader parser = XMLReaderFactory.createXMLReader(); - - parser.setContentHandler(new ContentHandlerAdapter() { - - String target; - String url; - - @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - if ("mapID".equals(localName)) { - target = atts.getValue("target"); - url = atts.getValue("url"); - if (verbose) { - getLog().debug("detect map entry : " + target + " : " + url); - } - result.put(target, url); - } - } - }); - - InputStream s = new FileInputStream(file); - try { - parser.parse(new InputSource(s)); - } finally { - s.close(); - } - return result; - } - - protected NodeItem getExistingItems(String tagName, File file) throws SAXException, IOException { - - XMLReader parser = XMLReaderFactory.createXMLReader(); - NodeItemHandler handler = new NodeItemHandler(tagName); - - parser.setContentHandler(handler); - - NodeItem rootItem = null; - InputStream s = new FileInputStream(file); - try { - parser.parse(new InputSource(s)); - rootItem = handler.rootItem; - } finally { - s.close(); - } - return rootItem; - } - - static class NodeItemHandler extends ContentHandlerAdapter { - - NodeItem rootItem; - NodeItem currentItem; - final Stack<NodeItem> stack; - final String tagName; - - public NodeItemHandler(String tagName) { - this.tagName = tagName; - this.stack = new Stack<NodeItem>(); - } - - @Override - public void startDocument() throws SAXException { - rootItem = new NodeItem("top", null); - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - if (tagName.equals(localName)) { - - String target = atts.getValue("target"); - String text = atts.getValue("text"); - - // debut d'un item - if (currentItem == null) { - // premier item - if (rootItem.getTarget().equals(target)) { - // le premier item est bien top - //rootItem.setText(text); - currentItem = rootItem; - } else { - // le premier noeud n'est pas top - // en l'encapsule - stack.push(rootItem); - currentItem = new NodeItem(target, text); - rootItem.addChild(currentItem); - } - } else { - NodeItem newItem = new NodeItem(target, text); - currentItem.addChild(newItem); - currentItem = newItem; - } - currentItem.adjustTarget(); - stack.push(currentItem); - - } - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - if (tagName.equals(localName)) { - // fin d'un item - stack.pop(); - if (!stack.isEmpty()) { - currentItem = stack.peek(); - } - } - } - } - - static class ContentHandlerAdapter implements ContentHandler { - - @Override - public void setDocumentLocator(Locator locator) { - } - - @Override - public void startDocument() throws SAXException { - } - - @Override - public void endDocument() throws SAXException { - } - - @Override - public void startPrefixMapping(String prefix, String uri) throws SAXException { - } - - @Override - public void endPrefixMapping(String prefix) throws SAXException { - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - } - - @Override - public void characters(char[] ch, int start, int length) throws SAXException { - } - - @Override - public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { - } - - @Override - public void processingInstruction(String target, String data) throws SAXException { - } - - @Override - public void skippedEntity(String name) throws SAXException { - } - } -} \ No newline at end of file Copied: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java (from rev 1406, jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/JaxxHelpGeneratorMojo.java) =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java (rev 0) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/JaxxHelpGeneratorMojo.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,792 @@ +/* *##% + * Copyright (C) 2007 + * JaxxPlugin, Code Lutin + * + * 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.nuiton.jaxx; + +import org.apache.maven.plugin.MojoFailureException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.Stack; +import org.apache.maven.model.Resource; +import org.nuiton.i18n.I18n; +import org.nuiton.util.FileUtil; +import org.nuiton.util.SortedProperties; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; +import static org.nuiton.i18n.I18n._; + +/** + * Mojo to generate javax help stuff for your project. + * + * HelpIds should have been discovered by the JaxxMojo. + * + * @author chemit + * @goal generate-help + * @phase process-sources + * + * @requiresProject + * @requiresDependencyResolution compile + * @since 1.3 + */ +public class JaxxHelpGeneratorMojo extends AbstractJaxxMojo { + + /** + * The directory where to generate javaHelp skeleton files. + * <p/> + * Is required if generateHelp is on. + * + * @parameter expression="${jaxx.helpTarget}" alias="target" default-value="${maven.src.dir}/main/help" + * @required + * + * @since 1.3 + */ + protected File target; + /** + * The locale to generate for help. + * + * By default, stay in France. + * + * @parameter expression="${jaxx.locale}" default-value="fr" + * @required + * + * @since 1.3 + */ + protected String locale; + /** + * The package where to generate i18n java file. + * + * @parameter expression="${jaxx.packageName}" default-value="${project.groupId}" + * @required + * + * @since 1.3 + */ + protected String packageName; + /** + * The file name of the helpset to generate. + * + * @parameter expression="${jaxx.helpSetFileName}" default-value="${jaxx.helpSetName}.hs" + * @required + * + * @since 1.3 + */ + protected String helpsetFileName; + /** + * The file name of the helpset map to generate. + * + * @parameter expression="${jaxx.mapFileName}" default-value="${jaxx.helpSetName}Map.jhm" + * @required + * + * @since 1.3 + */ + protected String mapFileName; + /** + * The file name of the helpset index to generate. + * + * @parameter expression="${jaxx.indexFileName}" default-value="${jaxx.helpSetName}Index.xml" + * @required + * + * @since 1.3 + */ + protected String indexFileName; + /** + * The file name of the helpset toc to generate. + * + * @parameter expression="${jaxx.tocFileName}" default-value="${jaxx.helpSetName}TOC.xml" + * @required + * + * @since 1.3 + */ + protected String tocFileName; + /** + * The file name of the i18n java file to generate. + * + * @parameter expression="${jaxx.i8nFileName}" default-value="${jaxx.helpSetName}I18n.java" + * @required + * + * @since 1.3 + */ + protected String i8nFileName; + /** + * The template used to generate helpset file. + * + * Must be an existing file or a ressource in classp-ath + * + * @parameter expression="${jaxx.helpSetTemplate}" default-value="/defaultHelpSet.hs.vm" + * @required + * + * @since 1.3 + */ + protected File helpSetTemplate; + /** + * The template used to generate helpset map file. + * + * Must be an existing file or a ressource in classp-ath + * + * @parameter expression="${jaxx.mapTemplate}" default-value="/defaultMap.jhm.vm" + * @required + * + * @since 1.3 + */ + protected File mapTemplate; + /** + * The template used to generate helpset index file. + * + * Must be an existing file or a ressource in classp-ath + * + * @parameter expression="${jaxx.indexTemplate}" default-value="/defaultIndex.xml.vm" + * @required + * + * @since 1.3 + */ + protected File indexTemplate; + /** + * The template used to generate helpset toc file. + * + * Must be an existing file or a ressource in classp-ath + * + * @parameter expression="${jaxx.tocTemplate}" default-value="/defaultToc.xml.vm" + * @required + * + * @since 1.3 + */ + protected File tocTemplate; + /** + * The template used to generate helpset content file. + * + * Must be an existing file or a ressource in classp-ath + * + * @parameter expression="${jaxx.contentTemplate}" default-value="/defaultContent.html.vm" + * @required + * + * @since 1.3 + */ + protected File contentTemplate; + /** + * The template used to generate helpset content file. + * + * Must be an existing file or a ressource in classp-ath + * + * @parameter expression="${jaxx.i18nTemplate}" default-value="/defaultI18n.java.vm" + * @required + * + * @since 1.3 + */ + protected File i18nTemplate; + /** + * The help ids discovered by Jaxx compilation + */ + protected Properties helpIds; + private static final String AUTOREMOVE_LINE = "REMOVE THS LINE TO DISABLE AUTO-REGENERATE THE FILE"; + + @Override + public void init() throws Exception { + + if (project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging()))) { + // nothing to be done for this type of packaging + skip = true; + getLog().info("skip generate goal for packaging " + project.getPackaging()); + return; + } + + if (!helpIdStore.exists()) { + skip = true; + getLog().info("no helpIdStore to react at " + helpIdStore); + return; + } + + // check there is some bundle + if (locale == null) { + throw new MojoFailureException("you must set the bundles property."); + } + // check there is some bundle + if (target == null) { + throw new MojoFailureException("you must set the target property."); + } + // check ressources + checkResource(helpSetTemplate); + checkResource(mapTemplate); + checkResource(indexTemplate); + checkResource(tocTemplate); + checkResource(contentTemplate); + + if (!target.exists()) { + getLog().info("mkdir " + target); + target.mkdirs(); + } + + + helpIds = new SortedProperties(); + + InputStream stream = new FileInputStream(helpIdStore); + + helpIds.load(stream); + + stream.close(); + + if (helpIds.isEmpty()) { + + // no ids detected + getLog().warn("no helpIds detected, will skip."); + skip = true; + return; + } + + skip = false; + } + + @Override + public void doAction() throws Exception { + + if (i18nable) { + + List<URL> lUrls = new java.util.ArrayList<URL>(); + List resources = project.getResources(); + for (Object o : resources) { + Resource resource = (Resource) o; + lUrls.add(new File(resource.getDirectory()).toURI().toURL()); + } + I18n.setExtraURL(lUrls.toArray(new URL[lUrls.size()])); + I18n.init(locale, null); + } + + File file; + + Properties env = new Properties(); + + env.put("helpSetName", helpSetName); + env.put("helpSetFileName", helpsetFileName); + env.put("mapFileName", mapFileName); + env.put("indexFileName", indexFileName); + env.put("tocFileName", tocFileName); + env.put("separator", " "); + env.put("autoremoveLine", AUTOREMOVE_LINE); + + + int touchedFiles = 0; + + // --------------------------------------------------------------- + // --- main helpset file ----------------------------------------- + // --------------------------------------------------------------- + + + file = new File(target, helpsetFileName); + + boolean doCreate = generateHelSetFile(file, env); + + if (doCreate) { + touchedFiles++; + } + + // --------------------------------------------------------------- + // --- helpset map file ------------------------------------------ + // --------------------------------------------------------------- + + file = new File(target, mapFileName); + + Properties mergedHelpIds = generateMapFile(file, env); + touchedFiles++; + + // --------------------------------------------------------------- + // --- helpset index file ---------------------------------------- + // --------------------------------------------------------------- + + file = new File(target, indexFileName); + + NodeItem indexRootItem = generateIndexFile(file, env); + touchedFiles++; + + // --------------------------------------------------------------- + // --- helpset toc file ------------------------------------------ + // --------------------------------------------------------------- + + file = new File(target, tocFileName); + + NodeItem tocRootItem = generateTocFile(file, env); + touchedFiles++; + + // --------------------------------------------------------------- + // --- helpset content files ------------------------------------- + // --------------------------------------------------------------- + + TemplateGenerator gen = prepareGenerator(contentTemplate); + + Enumeration keys = helpIds.keys(); + + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + String url = (String) helpIds.get(key); + url = helpSetName + File.separator + url; + + File f = new File(target, url); + + boolean exist = f.exists(); + + if (exist) { + // check if there is a autoremoveLine in content + String content = FileUtil.readAsString(f); + if (!content.contains(AUTOREMOVE_LINE)) { + // no regenerate marker detected, so skip this file + if (verbose) { + getLog().debug("skip existing file " + f); + } + continue; + } + } + + f.getParentFile().mkdirs(); + + if (verbose) { + if (exist) { + getLog().info("regenerate content file " + f); + } else { + getLog().info("generate content file " + f); + } + } + + env.put("helpId", key); + String i18n = helpsetI18nPrefix + key + helpsetTitleI18nSuffix; + env.put("helpIdTitle", _(i18n)); + env.put("helpIdUrl", url); + + gen.generate(env, f); + touchedFiles++; + } + + // --------------------------------------------------------------- + // --- i18n file ------------------------------------------------- + // --------------------------------------------------------------- + + String path = packageName.replaceAll("\\.", File.separator); + path += File.separator + i8nFileName; + file = new File(outJava, path); + generateI18nFile(file, env, mergedHelpIds, indexRootItem, tocRootItem); + touchedFiles++; + + getLog().info(touchedFiles + " file(s) treated."); + } + + protected void generateI18nFile(File file, Properties env, Properties mergedHelpIds, NodeItem indexRootItem, NodeItem tocRootItem) throws Exception { + + boolean create = !file.exists(); + + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + + Set<String> keys = new java.util.HashSet<String>(); + + for (Object k : mergedHelpIds.keySet()) { + String key = helpsetI18nPrefix + k + helpsetTitleI18nSuffix; + keys.add(key); + } + indexRootItem.extractI18n(keys, helpsetI18nPrefix, helpsetIndexI18nSuffix); + tocRootItem.extractI18n(keys, helpsetI18nPrefix, helpsetTocI18nSuffix); + + env.put("keys", keys); + env.put("packageName", packageName); + String className = file.getName(); + int index = className.lastIndexOf("."); + className = className.substring(0, index); + env.put("className", className); + + if (verbose) { + if (create) { + getLog().info("generate i18n java file " + file); + } else { + getLog().info("udpate i18n java file " + file); + } + } + + doGen(i18nTemplate, file, env); + + } + + protected boolean generateHelSetFile(File file, Properties env) throws Exception { + + if (file.exists()) { + // check the auto removeline presence + String content = FileUtil.readAsString(file); + if (!content.contains(AUTOREMOVE_LINE)) { + // no regenerate marker detected, so skip this file + if (verbose) { + getLog().info("skip existing helpset main file " + file); + } + return false; + } + } + + if (verbose) { + if (file.exists()) { + getLog().info("regenerate helpset main file " + file); + } else { + getLog().info("generate helpset main file " + file); + } + } + doGen(helpSetTemplate, file, env); + return true; + } + + protected Properties generateMapFile(File file, Properties env) throws Exception { + + boolean create; + + Properties mergedHelpIds = null; + if (file.exists()) { + + // get back the exisiting data and merge it with incoming ones + + if (verbose) { + getLog().info("loading existing helpset map file " + file); + } + + mergedHelpIds = getExistingHelpIds(file); + create = false; + + } else { + + mergedHelpIds = new SortedProperties(); + create = true; + } + + // inject new helpIds + + for (Object k : helpIds.keySet()) { + mergedHelpIds.put(k, helpSetName + "/" + helpIds.get(k)); + } + + if (!mergedHelpIds.contains("top")) { + // on ajoute une entree vers le root du helpset + + String topUrl = helpSetName + ".html"; + helpIds.put("top", topUrl); + mergedHelpIds.put("top", helpSetName + "/" + topUrl); + if (verbose) { + getLog().debug("add top entry with url " + topUrl); + } + } + + if (verbose) { + if (create) { + getLog().info("generate helpset map file " + file); + } else { + getLog().info("udpate helpset map file " + file); + } + } + + env.put("helpIds", mergedHelpIds); + doGen(mapTemplate, file, env); + env.remove("helpIds"); + return mergedHelpIds; + } + + protected NodeItem generateIndexFile(File file, Properties env) throws Exception { + NodeItem rootItem = null; + + boolean create; + + if (file.exists()) { + + create = false; + + rootItem = getExistingItems("indexitem", file); + } else { + create = true; + } + + if (rootItem == null) { + rootItem = new NodeItem("top", helpSetName); + } + + // inject new index entries + + for (Object k : helpIds.keySet()) { + NodeItem toc = rootItem.findChild(k + ""); + if (verbose) { + getLog().debug("index " + k + " : " + toc); + } + } + + //String prefix = helpsetI18nPrefix; + //String prefix = helpsetI18nPrefix + helpSetName + "."; + rootItem.applyI18n(helpsetI18nPrefix, helpsetIndexI18nSuffix); + + if (verbose) { + if (create) { + getLog().info("generate helpset index file " + file); + } else { + getLog().info("udpate helpset index file " + file); + } + } + + env.put("rootItem", rootItem); + doGen(indexTemplate, file, env); + env.remove("rootItem"); + return rootItem; + } + + protected NodeItem generateTocFile(File file, Properties env) throws Exception { + NodeItem rootItem = null; + + boolean create; + + if (file.exists()) { + + create = false; + + rootItem = getExistingItems("tocitem", file); + } else { + create = true; + } + + if (rootItem == null) { + rootItem = new NodeItem("top", helpSetName); + } + // inject new toc entries + + for (Object k : helpIds.keySet()) { + NodeItem toc = rootItem.findChild(k + ""); + if (verbose) { + getLog().debug("toc " + k + " : " + toc); + } + } + + //String prefix = helpsetI18nPrefix + helpSetName + "."; + rootItem.applyI18n(helpsetI18nPrefix, helpsetTocI18nSuffix); + + if (verbose) { + if (create) { + getLog().info("generate helpset toc file " + file); + } else { + getLog().info("udpate helpset toc file " + file); + } + } + + env.put("rootItem", rootItem); + doGen(tocTemplate, file, env); + env.remove("rootItem"); + return rootItem; + } + + protected void doGen(File template, File f, Properties env) throws Exception { + TemplateGenerator gen = prepareGenerator(template); + gen.generate(env, f); + } + + protected TemplateGenerator prepareGenerator(File template) throws Exception { + URL templateURL = getTemplate(template); + + if (verbose) { + getLog().info("using template " + templateURL); + } + TemplateGenerator gen = new TemplateGenerator(project, templateURL); + return gen; + } + + protected URL getTemplate(File f) throws IOException { + URL r = null; + InputStream s = null; + if (f.exists()) { + r = f.toURI().toURL(); + } else { + r = getClass().getResource(f.toString()); + } + return r; + } + + protected void checkResource(File f) throws MojoFailureException { + if (!f.exists()) { + // test in classPath + InputStream r = getClass().getResourceAsStream(f.toString()); + if (r == null) { + throw new MojoFailureException("could not find ressource " + f); + } + } + } + + protected Properties getExistingHelpIds(File file) throws SAXException, IOException { + + final Properties result = new SortedProperties(); + + XMLReader parser = XMLReaderFactory.createXMLReader(); + + parser.setContentHandler(new ContentHandlerAdapter() { + + String target; + String url; + + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + if ("mapID".equals(localName)) { + target = atts.getValue("target"); + url = atts.getValue("url"); + if (verbose) { + getLog().debug("detect map entry : " + target + " : " + url); + } + result.put(target, url); + } + } + }); + + InputStream s = new FileInputStream(file); + try { + parser.parse(new InputSource(s)); + } finally { + s.close(); + } + return result; + } + + protected NodeItem getExistingItems(String tagName, File file) throws SAXException, IOException { + + XMLReader parser = XMLReaderFactory.createXMLReader(); + NodeItemHandler handler = new NodeItemHandler(tagName); + + parser.setContentHandler(handler); + + NodeItem rootItem = null; + InputStream s = new FileInputStream(file); + try { + parser.parse(new InputSource(s)); + rootItem = handler.rootItem; + } finally { + s.close(); + } + return rootItem; + } + + static class NodeItemHandler extends ContentHandlerAdapter { + + NodeItem rootItem; + NodeItem currentItem; + final Stack<NodeItem> stack; + final String tagName; + + public NodeItemHandler(String tagName) { + this.tagName = tagName; + this.stack = new Stack<NodeItem>(); + } + + @Override + public void startDocument() throws SAXException { + rootItem = new NodeItem("top", null); + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + if (tagName.equals(localName)) { + + String target = atts.getValue("target"); + String text = atts.getValue("text"); + + // debut d'un item + if (currentItem == null) { + // premier item + if (rootItem.getTarget().equals(target)) { + // le premier item est bien top + //rootItem.setText(text); + currentItem = rootItem; + } else { + // le premier noeud n'est pas top + // en l'encapsule + stack.push(rootItem); + currentItem = new NodeItem(target, text); + rootItem.addChild(currentItem); + } + } else { + NodeItem newItem = new NodeItem(target, text); + currentItem.addChild(newItem); + currentItem = newItem; + } + currentItem.adjustTarget(); + stack.push(currentItem); + + } + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + if (tagName.equals(localName)) { + // fin d'un item + stack.pop(); + if (!stack.isEmpty()) { + currentItem = stack.peek(); + } + } + } + } + + static class ContentHandlerAdapter implements ContentHandler { + + @Override + public void setDocumentLocator(Locator locator) { + } + + @Override + public void startDocument() throws SAXException { + } + + @Override + public void endDocument() throws SAXException { + } + + @Override + public void startPrefixMapping(String prefix, String uri) throws SAXException { + } + + @Override + public void endPrefixMapping(String prefix) throws SAXException { + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + } + + @Override + public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { + } + + @Override + public void processingInstruction(String target, String data) throws SAXException { + } + + @Override + public void skippedEntity(String name) throws SAXException { + } + } +} \ No newline at end of file Deleted: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/NodeItem.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,137 +0,0 @@ -package org.codelutin.jaxx; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import static org.codelutin.i18n.I18n._; - -public class NodeItem { - - String absoluteTarget; - private String target; - private String text; - private List<NodeItem> childs; - - public NodeItem(String target, String text) { - this.target = target; - this.absoluteTarget = target; - - this.text = text; - } - - public String getTarget() { - return target; - } - - public String getAbsoluteTarget() { - return absoluteTarget; - } - - public String getText() { - return text; - } - - public List<NodeItem> getChilds() { - return childs; - } - - public NodeItem findChild(String path) { - NodeItem result = null; - String[] paths = path.split("\\."); - for (int i = 0, j = paths.length; i < j; i++) { - String p = paths[i]; - if (result == null) { - - // first node - if (target.equals(p)) { - result = this; - continue; - } - result = getChild(p); - if (result == null) { - result = new NodeItem(p, null); - addChild(result); - adjutsAbsoluteTarget(result); - } - continue; - } - NodeItem child = result.getChild(p); - if (child == null) { - child = new NodeItem(p, null); - result.addChild(child); - result.adjutsAbsoluteTarget(child); - result = child; - } else { - result = child; - } - } - return result; - } - - public NodeItem getChild(int index) { - return childs.get(index); - } - - public NodeItem getChild(String target) { - if (isLeaf()) { - return null; - } - for (NodeItem i : childs) { - if (i.target.equals(target)) { - return i; - } - } - return null; - } - - public void addChild(NodeItem child) { - if (childs == null) { - childs = new ArrayList<NodeItem>(); - } - - childs.add(child); - } - - public void adjutsAbsoluteTarget(NodeItem child) { - if (!"top".equals(target)) { - // on ne prefixe pas les fils direct du root - child.absoluteTarget = absoluteTarget + "." + child.target; - } - } - - public void adjustTarget() { - int index = target.lastIndexOf("."); - if (index > -1) { - target = target.substring(index + 1); - } - } - - public boolean isLeaf() { - return childs == null || childs.isEmpty(); - } - - public void applyI18n(String prefix, String suffix) { - String key = prefix + getAbsoluteTarget() + suffix; - text = _(key); - if (!isLeaf()) { - for (NodeItem i : getChilds()) { - i.applyI18n(prefix, suffix); - } - } - } - - public void extractI18n(Set<String> keys, String prefix, String suffix) { - String key = prefix + getAbsoluteTarget() + suffix; - keys.add(key); - if (!isLeaf()) { - for (NodeItem i : getChilds()) { - i.extractI18n(keys, prefix, suffix); - } - } - } - - @Override - public String toString() { - return super.toString() + "<target:" + target + ", text:" + text + ", nbChilds:" + (isLeaf() ? 0 : childs.size()) + ">"; - } -} Copied: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java (from rev 1406, jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/NodeItem.java) =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java (rev 0) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/NodeItem.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,137 @@ +package org.nuiton.jaxx; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import static org.nuiton.i18n.I18n._; + +public class NodeItem { + + String absoluteTarget; + private String target; + private String text; + private List<NodeItem> childs; + + public NodeItem(String target, String text) { + this.target = target; + this.absoluteTarget = target; + + this.text = text; + } + + public String getTarget() { + return target; + } + + public String getAbsoluteTarget() { + return absoluteTarget; + } + + public String getText() { + return text; + } + + public List<NodeItem> getChilds() { + return childs; + } + + public NodeItem findChild(String path) { + NodeItem result = null; + String[] paths = path.split("\\."); + for (int i = 0, j = paths.length; i < j; i++) { + String p = paths[i]; + if (result == null) { + + // first node + if (target.equals(p)) { + result = this; + continue; + } + result = getChild(p); + if (result == null) { + result = new NodeItem(p, null); + addChild(result); + adjutsAbsoluteTarget(result); + } + continue; + } + NodeItem child = result.getChild(p); + if (child == null) { + child = new NodeItem(p, null); + result.addChild(child); + result.adjutsAbsoluteTarget(child); + result = child; + } else { + result = child; + } + } + return result; + } + + public NodeItem getChild(int index) { + return childs.get(index); + } + + public NodeItem getChild(String target) { + if (isLeaf()) { + return null; + } + for (NodeItem i : childs) { + if (i.target.equals(target)) { + return i; + } + } + return null; + } + + public void addChild(NodeItem child) { + if (childs == null) { + childs = new ArrayList<NodeItem>(); + } + + childs.add(child); + } + + public void adjutsAbsoluteTarget(NodeItem child) { + if (!"top".equals(target)) { + // on ne prefixe pas les fils direct du root + child.absoluteTarget = absoluteTarget + "." + child.target; + } + } + + public void adjustTarget() { + int index = target.lastIndexOf("."); + if (index > -1) { + target = target.substring(index + 1); + } + } + + public boolean isLeaf() { + return childs == null || childs.isEmpty(); + } + + public void applyI18n(String prefix, String suffix) { + String key = prefix + getAbsoluteTarget() + suffix; + text = _(key); + if (!isLeaf()) { + for (NodeItem i : getChilds()) { + i.applyI18n(prefix, suffix); + } + } + } + + public void extractI18n(Set<String> keys, String prefix, String suffix) { + String key = prefix + getAbsoluteTarget() + suffix; + keys.add(key); + if (!isLeaf()) { + for (NodeItem i : getChilds()) { + i.extractI18n(keys, prefix, suffix); + } + } + } + + @Override + public String toString() { + return super.toString() + "<target:" + target + ", text:" + text + ", nbChilds:" + (isLeaf() ? 0 : childs.size()) + ">"; + } +} Modified: jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/TemplateGenerator.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/main/java/org/codelutin/jaxx/TemplateGenerator.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/main/java/org/nuiton/jaxx/TemplateGenerator.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.codelutin.jaxx; +package org.nuiton.jaxx; import java.io.File; import java.io.FileWriter; Copied: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton (from rev 1405, jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin) Property changes on: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton ___________________________________________________________________ Name: svn:mergeinfo + Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1722Test.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/Bug1722Test.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1722Test.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; /** @author chemit */ public class Bug1722Test extends JaxxBaseTest { Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1750Test.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/Bug1750Test.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1750Test.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; import jaxx.Base64Coder; import jaxx.compiler.JAXXCompiler; Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1751Test.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/Bug1751Test.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/Bug1751Test.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; /** @author chemit */ public class Bug1751Test extends JaxxBaseTest { Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/CompilerTest.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/CompilerTest.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/CompilerTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; import jaxx.compiler.JAXXCompiler; import jaxx.compiler.JAXXCompilerLaunchor; Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/CompilerValidatorTest.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/CompilerValidatorTest.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/CompilerValidatorTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; import jaxx.compiler.JAXXCompilerLaunchor; import org.apache.maven.plugin.MojoExecutionException; Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/DecoratorTest.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/DecoratorTest.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/DecoratorTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; public class DecoratorTest extends JaxxBaseTest { Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/I18nTest.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/I18nTest.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/I18nTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; public class I18nTest extends JaxxBaseTest { Deleted: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/JaxxBaseTest.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,85 +0,0 @@ -package org.codelutin.jaxx; - -import jaxx.runtime.DefaultJAXXContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.codelutin.util.FileUtil; - -import java.io.File; -import java.io.IOException; - -/** @author chemit */ -public abstract class JaxxBaseTest extends AbstractMojoTestCase { - - protected static final String DEFALUT_PREFIX = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "testcases" + File.separator; - - /** log */ - protected Log log; - - protected JaxxGeneratorMojo mojo; - - protected File pomFile; - - public String getPrefix() { - return DEFALUT_PREFIX; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - getLog().info(getName()); - pomFile = getPomFile(); - mojo = (JaxxGeneratorMojo) lookupMojo("generate", pomFile); - mojo.jaxxContextImplementorClass = DefaultJAXXContext.class.getName(); - mojo.compilerFQN = jaxx.compiler.SwingCompiler.class.getName(); - mojo.validatorFQN = jaxx.runtime.validator.swing.SwingValidator.class.getName(); - mojo.defaultDecoratorFQN = jaxx.compiler.DefaultCompiledObjectDecorator.class.getName(); - assertNotNull(mojo); - } - - protected File getPomFile() { - return new File(getBasedir(), getPrefix() + getName().substring(4) + ".xml"); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (mojo != null) { - mojo = null; - } - if (pomFile != null) { - pomFile = null; - } - } - - protected void checkPattern(JaxxGeneratorMojo mojo, String pattern, boolean required, String... files) throws IOException { - if (files.length == 0) { - files = mojo.files; - } - for (String file : files) { - // check we have a the required/forbidden pattern - File f = new File(mojo.outJava, file.substring(0, file.length() - 4) + "java"); - if (mojo.verbose) { - getLog().info("check generated file " + f); - } - - assertTrue("generated file " + f + " was not found...", f.exists()); - String content = FileUtil.readAsString(f); - - String errorMessage = required ? "could not find the pattern : " : "should not have found pattern :"; - assertEquals(errorMessage + pattern + " in file " + f, required, content.contains(pattern)); - } - } - - protected Log getLog() { - if (log == null) { - log = LogFactory.getLog(getClass()); - } - return log; - } - - protected void assertNumberJaxxFiles(int expectedNbFiles) { - assertEquals(expectedNbFiles, mojo.files.length); - } -} Copied: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java (from rev 1406, jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/JaxxBaseTest.java) =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java (rev 0) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/JaxxBaseTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -0,0 +1,85 @@ +package org.nuiton.jaxx; + +import jaxx.runtime.DefaultJAXXContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.nuiton.util.FileUtil; + +import java.io.File; +import java.io.IOException; + +/** @author chemit */ +public abstract class JaxxBaseTest extends AbstractMojoTestCase { + + protected static final String DEFALUT_PREFIX = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "testcases" + File.separator; + + /** log */ + protected Log log; + + protected JaxxGeneratorMojo mojo; + + protected File pomFile; + + public String getPrefix() { + return DEFALUT_PREFIX; + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + getLog().info(getName()); + pomFile = getPomFile(); + mojo = (JaxxGeneratorMojo) lookupMojo("generate", pomFile); + mojo.jaxxContextImplementorClass = DefaultJAXXContext.class.getName(); + mojo.compilerFQN = jaxx.compiler.SwingCompiler.class.getName(); + mojo.validatorFQN = jaxx.runtime.validator.swing.SwingValidator.class.getName(); + mojo.defaultDecoratorFQN = jaxx.compiler.DefaultCompiledObjectDecorator.class.getName(); + assertNotNull(mojo); + } + + protected File getPomFile() { + return new File(getBasedir(), getPrefix() + getName().substring(4) + ".xml"); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (mojo != null) { + mojo = null; + } + if (pomFile != null) { + pomFile = null; + } + } + + protected void checkPattern(JaxxGeneratorMojo mojo, String pattern, boolean required, String... files) throws IOException { + if (files.length == 0) { + files = mojo.files; + } + for (String file : files) { + // check we have a the required/forbidden pattern + File f = new File(mojo.outJava, file.substring(0, file.length() - 4) + "java"); + if (mojo.verbose) { + getLog().info("check generated file " + f); + } + + assertTrue("generated file " + f + " was not found...", f.exists()); + String content = FileUtil.readAsString(f); + + String errorMessage = required ? "could not find the pattern : " : "should not have found pattern :"; + assertEquals(errorMessage + pattern + " in file " + f, required, content.contains(pattern)); + } + } + + protected Log getLog() { + if (log == null) { + log = LogFactory.getLog(getClass()); + } + return log; + } + + protected void assertNumberJaxxFiles(int expectedNbFiles) { + assertEquals(expectedNbFiles, mojo.files.length); + } +} Modified: jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/NodeItemTest.java =================================================================== --- jaxx/trunk/maven-jaxx-plugin/src/test/java/org/codelutin/jaxx/NodeItemTest.java 2009-05-15 14:01:35 UTC (rev 1405) +++ jaxx/trunk/maven-jaxx-plugin/src/test/java/org/nuiton/jaxx/NodeItemTest.java 2009-05-16 02:03:26 UTC (rev 1408) @@ -1,4 +1,4 @@ -package org.codelutin.jaxx; +package org.nuiton.jaxx; import org.junit.Assert; import org.junit.Test;
participants (1)
-
tchemit@users.labs.libre-entreprise.org