r765 - in trunk/maven-eugene-plugin: . src/main/java/org/nuiton/eugene/plugin src/main/java/org/nuiton/eugene/plugin/writer src/main/resources
Author: tchemit Date: 2009-12-18 11:26:52 +0100 (Fri, 18 Dec 2009) New Revision: 765 Added: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/SmartGenerateMojo.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseChainedFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToChainedFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ModelChainedFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelChainedFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelChainedFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoChainedFileWriter.java trunk/maven-eugene-plugin/src/main/resources/META-INF/ Removed: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/AbstractEugeneMojo.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GeneratateModelFilesMojo.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GenerateFromModelsMojo.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseModelFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToModelFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelFileWriter.java trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoModelFileWriter.java Modified: trunk/maven-eugene-plugin/pom.xml trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/EugenePlugin.java Log: - introduce SmartGenerateMojo to remplace all new goals : one goal for everything (even the coffee :)) - add it tests Modified: trunk/maven-eugene-plugin/pom.xml =================================================================== --- trunk/maven-eugene-plugin/pom.xml 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/pom.xml 2009-12-18 10:26:52 UTC (rev 765) @@ -71,6 +71,7 @@ <defaultGoal>install</defaultGoal> <plugins> + <!-- plugin plugin --> <plugin> <artifactId>maven-plugin-plugin</artifactId> @@ -91,7 +92,13 @@ <execution> <goals> <goal>generate-metadata</goal> + <!--<goal>merge-metadata</goal>--> </goals> + <!--configuration> + <descriptors> + <descriptor>${maven.src.dir}/main/plexus/components.xml</descriptor> + </descriptors> + </configuration--> </execution> </executions> </plugin> @@ -116,6 +123,12 @@ <plugin> <artifactId>maven-plugin-plugin</artifactId> </plugin> + + <plugin> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-maven-plugin</artifactId> + <version>1.3.8</version> + </plugin> </plugins> </reporting> @@ -134,9 +147,10 @@ <artifactId>maven-invoker-plugin</artifactId> <configuration> <pomIncludes> - <pomInclude>generate-model-files/testIncludeWithNoProtocol/pom.xml</pomInclude> - <pomInclude>generate-model-files/testIncludeWithOnlyProtocol/pom.xml</pomInclude> - <pomInclude>generate/generators/pom.xml</pomInclude> + <pomInclude>smart-generate/only-zargo/pom.xml</pomInclude> + <pomInclude>smart-generate/only-zargo-xmi/pom.xml</pomInclude> + <pomInclude>smart-generate/all/pom.xml</pomInclude> + <pomInclude>smart-generate/generators/pom.xml</pomInclude> <!--<pomInclude>**/pom.xml</pomInclude>--> </pomIncludes> <postBuildHookScript>verify</postBuildHookScript> Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/AbstractEugeneMojo.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/AbstractEugeneMojo.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/AbstractEugeneMojo.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,240 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; -import org.nuiton.eugene.models.Model; -import org.nuiton.plugin.AbstractPlugin; -import org.nuiton.plugin.PluginIOContext; - -import java.io.File; -import java.util.Arrays; -import java.util.Map; - -/** - * User: chemit - * Date: 23 nov. 2009 - * Time: 20:19:35 - */ -public abstract class AbstractEugeneMojo extends AbstractPlugin { - - /** - * Maven project. - * - * @parameter default-value="${project}" - * @readonly - * @since 2.0.0 - */ - protected MavenProject project; - /** - * Le settings (pour obtenir le mode offline). - * - * @parameter default-value="${settings}" - * @readonly - * @since 2.0.0 - */ - protected Settings settings; - /** - * Ecrase les fichiers générés. - * - * @parameter expression="${eugene.overwrite}" default-value="false" - * @since 2.0.0 - */ - protected boolean overwrite; - /** - * Pour activer le mode verbeux. - * - * @parameter expression="${eugene.verbose}" default-value="${maven.verbose}" - * @since 2.0.0 - */ - protected boolean verbose; - /** - * Encoding to be used for generation of files. - * - * @parameter expression="${eugene.encoding}" default-value="${project.build.sourceEncoding}" - * @since 2.0.0 - */ - protected String encoding; - /** - * A flag to mark the mojo to be used in a test phase. This will permits to add generated sources in test compile roots. - * - * @parameter expression="${eugene.testPhase}" default-value="false" - * @since 2.0.0 - */ - protected boolean testPhase; - /** - * The type of model to be used. - * <p/> - * By default, use an {@code objectmodel}. - * - * @parameter expression="${eugene.modelType}" default-value="objectmodel" - * @required - * @since 2.0.0 - */ - protected String modelType; - /** - * An extra directory to be added to the classpath. - * - * @parameter expression="${eugene.extraClassPathDirectory}" - * @since 2.0.0 - */ - private File extraClassPathDirectory; - /** - * class instance of the given {@link #modelType} - */ - protected Class<? extends Model> modelClass; - - /** - * All available models (obtain by plexus, keys are plexus roles, values are a - * instance of corresponding model). - * - * @component role="org.nuiton.eugene.models.Model" - */ - protected Map<String, Model> _models; - - @Override - protected boolean init() throws Exception { - - // on recupere le fqn du model à traiter via le container plexus (plus pratique dans ce cas où on veut - // pouvoir associé un nom à un type de service). - Model model = _models.get(modelType.trim().toLowerCase()); - if (model == null) { - throw new MojoExecutionException("No modelType named '" + modelType + "', use one of " + _models.keySet()); - } - modelClass = model.getClass(); - return true; - } - - /** - * Build the resources data to use for a goal. - * - * @param resources incoming resources data (form the goal - * @param defaultIn the default input directory - * @param defaultOut the default output directory - * @param defaultTestIn the default test input directory - * @param defaultTestOut the default test output directory - * @return the new {@link org.nuiton.plugin.PluginIOContext} to use in the goal - */ - protected PluginIOContext initResources(PluginIOContext resources, File defaultIn, File defaultOut, File defaultTestIn, File defaultTestOut) { - - if (resources == null) { - resources = new PluginIOContext(); - } - - // adding default inputs only if not consumed - if (resources.getInputs() == null) { - if (testPhase) { - resources.setInput(defaultTestIn); - } else { - resources.setInput(defaultIn); - } - getLog().info(" using default in : " + Arrays.asList(resources.getInputs())); - } else { - getLog().info(" in : " + Arrays.asList(resources.getInputs())); - } - - if (resources.getOutput() == null) { - if (testPhase) { - resources.setOutput(defaultTestOut); - } else { - resources.setOutput(defaultOut); - } - getLog().info(" using default out : " + resources.getOutput()); - } else { - getLog().info(" out : " + resources.getOutput()); - } - - return resources; - } - - - @Override - public MavenProject getProject() { - return project; - } - - public void setProject(MavenProject project) { - this.project = project; - } - - @Override - public boolean isVerbose() { - return verbose; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - public String getEncoding() { - return encoding; - } - - public void setEncoding(String encoding) { - this.encoding = encoding; - } - - public boolean isOverwrite() { - return overwrite; - } - - public void setOverwrite(boolean overwrite) { - this.overwrite = overwrite; - } - - public Settings getSettings() { - return settings; - } - - public void setSettings(Settings settings) { - this.settings = settings; - } - - public boolean isOffline() { - return settings.isOffline(); - } - - public boolean isTestPhase() { - return testPhase; - } - - public void setTestPhase(boolean testPhase) { - this.testPhase = testPhase; - } - - public Class<? extends Model> getModelClass() { - return modelClass; - } - - public void setModelClass(Class<? extends Model> modelClass) { - this.modelClass = modelClass; - } - - public File getExtraClassPathDirectory() { - return extraClassPathDirectory; - } - - public void setExtraClassPathDirectory(File extraClassPathDirectory) { - this.extraClassPathDirectory = extraClassPathDirectory; - } -} Modified: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/EugenePlugin.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/EugenePlugin.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/EugenePlugin.java 2009-12-18 10:26:52 UTC (rev 765) @@ -55,7 +55,7 @@ * by : $Author$ * @goal generate * @requiresProject true - * @deprecated since 2.0.0, use now the {@link GenerateFromModelsMojo}. + * @deprecated since 2.0.0, use now the {@link SmartGenerateMojo}. */ @Deprecated public class EugenePlugin extends EugeneAbstractMojo { Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GeneratateModelFilesMojo.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GeneratateModelFilesMojo.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GeneratateModelFilesMojo.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,330 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.nuiton.eugene.ModelFileWriter; -import org.nuiton.eugene.ModelFileWriterConfiguration; -import org.nuiton.eugene.ModelFileWriterUtil; -import org.nuiton.eugene.plugin.writer.BaseModelFileWriter; -import org.nuiton.eugene.plugin.writer.BaseXmiToModelFileWriter; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.*; - -/** - * User: chemit - * Date: 24 nov. 2009 - * Time: 00:22:37 - * - * @goal generate-model-files - * @requiresProject true - * @requiresDependencyResolution compile - */ -public class GeneratateModelFilesMojo extends AbstractEugeneMojo implements ModelFileWriterConfiguration { - - /** - * Inputs files to used to generate the required model files. - * </p> - * An include has the following pattern : - * <pre> - * writer: - * </pre> - * when you want to use a specific writer with his default io values. - * <p/> - * Can also write : - * <pre> - * [writer:]directory:includes - * </pre> - * where {@code includes} is the pattern to find files from the directory given and must be terminated by the extension - * of files. - * <p/> - * Specifying the {@code writer} can be usefull when you want to use a writer for an unknown extension - * by any writer. - * <p/> - * Example : - * <pre> - * <inputFiles> - * <inputFile>zargo:<inputFile> - * <inputFile>src/main/xmi2:**\/*.zargo<inputFile> - * <inputFile>zargo:src/main/xmi:**\/*.zargo2<inputFile> - * </inputFiles> - * </pre> - * - * @parameter expression="${eugene.inputFiles}" - * @required - * @since 2.0.0 - */ - protected String[] inputFiles; - /** - * Where to generate files. - * - * @parameter expression="${eugene.outputDirectory}" default-value="target/generated-sources" - * @required - * @since 2.0.0 - */ - protected File outputDirectory; - /** - * Properties to pass to writer. - * - * @parameter - * @since 2.0.0 - */ - protected Map<String, Object> properties; - /** - * Ne génère rien, analyse juste la configuration. - * - * @parameter expression="${eugene.dryRun}" default-value="false" - * @since 2.0.0 - */ - protected boolean dryRun; - /** - * Nom du paquetage pour les fichiers générés - * - * @parameter expression="${generator.fullPackagePath}" default-value="${project.groupId}.${project.artifactId}" - * @since 2.0.0 - */ - protected String fullPackagePath; -// /** -// * Nom du paquetage à générer -// * -// * @parameter expression="${generator.extractedPackages}" default-value="${project.groupId}.${project.artifactId}" -// * @since 2.0.0 -// */ -// protected String extractedPackages; - /** - * Nom du resolver a utiliser - * - * @parameter expression="${generator.resolver}" default-value="org.nuiton.util.ResourceResolver" - * @since 2.0.0 - */ - protected String resolver; - /** - * All available writers - * - * @component role="org.nuiton.eugene.ModelFileWriter" - */ - protected Map<String, ModelFileWriter> writers; - /** - * All available writers for the given {@link #getModelClass()} - */ - protected Set<ModelFileWriter> availableWriters; - /** - * Writers to process - */ - protected List<ModelFileWriter> plan; - - @Override - protected boolean init() throws Exception { - boolean b = super.init(); - if (!b) { - return false; - } - if (inputFiles.length == 0) { - throw new MojoExecutionException("Must specify something to include using the includes property"); - } - - availableWriters = ModelFileWriterUtil.filterWriterForModelType(writers, getModelClass()); - - if (availableWriters.isEmpty()) { - throw new MojoExecutionException("Could not find any writer in class-path."); - } - - for (ModelFileWriter writer : availableWriters) { - if (writer instanceof BaseModelFileWriter) { - // add log support - ((BaseModelFileWriter) writer).setLog(getLog()); - } - } - - plan = new ArrayList<ModelFileWriter>(); - - // first pass to detect top level writers - for (String include : inputFiles) { - - getLog().info("Register include : " + include); - ModelFileWriterUtil.registerInclude(this, include, plan); - } - - if (properties == null) { - properties = new TreeMap<String, Object>(); - } - return true; - } - - @Override - protected void doAction() throws Exception { - if (dryRun) { - getLog().warn("dryRun property is set, no file will be generated."); - } - try { - // transfert to properties - - ClassLoader loader = fixClassLoader(); - - properties.put(BaseModelFileWriter.PROP_CLASS_LOADER, loader); - properties.put(BaseXmiToModelFileWriter.PROP_FULL_PACKAGE_PATH, fullPackagePath); - //properties.put("extractedPackages", extractedPackages); - properties.put(BaseXmiToModelFileWriter.PROP_RESOLVER, resolver); - - // launch writers in incoming order of dicovering of them - for (ModelFileWriter writer : plan) { - int size = writer.getEntries().size(); - if (size == 1) { - getLog().info("Process phase [" + writer.getInputProtocol() + "] for one entry."); - } else { - getLog().info("Process phase [" + writer.getInputProtocol() + "] for " + size + " entries."); - } - if (dryRun || isVerbose()) { - for (ModelFileWriterUtil.ModelFileWriterEntry entry : writer.getEntries()) { - getLog().info(" entry : " + entry.getInputDirectory() + " - " + entry.getIncludePattern()); - } - if (dryRun) { - continue; - } - } - if (getLog().isDebugEnabled()) { - getLog().debug("Generating files and copying resources..."); - } - - writer.generate(this); - - } - } finally { - // always clear everything to avoid side-effects in goal is invoked more than once - properties.clear(); - for (ModelFileWriter writer : plan) { - writer.clear(); - } - plan.clear(); - } - } - - @Override - public File getOutputDirectory() { - return outputDirectory; - } - - @Override - public Map<String, Object> getProperties() { - return properties; - } - - @Override - public Set<ModelFileWriter> getAvailableWriters() { - return availableWriters; - } - - @Override - public File getBasedir() { - return getProject().getBasedir(); - } - - /** - * Prepare le classLoader a utiliser dans le generateur. - * <p/> - * Si un {@link #extraClassPathDirectory} a été renseigné, il est rajouté. - * <p/> - * Si des références à des sibling modules, ils seront rajoutés aussi. - * - * @return le class loader modifie - * @throws MojoExecutionException if any pb - */ - protected ClassLoader fixClassLoader() throws MojoExecutionException { - Set<String> urlsAsString = new HashSet<String>(); - List<URL> urls = new ArrayList<URL>(); - try { - ClassLoader loader; - File extraClassPathDirectory = getExtraClassPathDirectory(); - if (extraClassPathDirectory != null) { - if (verbose) { - getLog().info("Add extra directory in generator's classLoader : " + extraClassPathDirectory); - } - addDirectoryToUrlsList(extraClassPathDirectory, urls, urlsAsString); - } - if (project.getProjectReferences() != null) { - // this case is for multi-module when calling from a parent module - for (Object o : project.getProjectReferences().entrySet()) { - Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; - MavenProject relatedProject = (MavenProject) entry.getValue(); - if (verbose) { - getLog().info("Add project reference in generator's classLoader : '" + relatedProject.getArtifact() + "'"); - } - //TODO il faudrait peut-etre aussi ajouter les dependances ? - addDirectoryToUrlsList(relatedProject.getArtifact().getFile(), urls, urlsAsString); - } - } - if (!project.getArtifacts().isEmpty()) { - // this is a special case when artifacts were resolved (for example in site phase) - if (verbose) { - getLog().info("Use resolved artifacts to build class-path"); - } - for (Object o : project.getArtifacts()) { - Artifact a = (Artifact) o; - if (!a.getScope().equals("provided")) { - addDirectoryToUrlsList(a.getFile(), urls, urlsAsString); - } - } - } - // we ask to add the directory in classloader - loader = getClass().getClassLoader(); - if (getLog().isDebugEnabled()) { - getLog().info("original classloader " + loader); - } - if (loader instanceof URLClassLoader) { - // on reinjecte les urls de loader de base - // car sinon on risque de ne pas retrouver les resources... - for (URL u : ((URLClassLoader) loader).getURLs()) { - addUrlToUrlsList(u, urls, urlsAsString); - if (getLog().isDebugEnabled()) { - getLog().debug("original cp entry: " + u); - } - } - // et on force l'utilisation du classloader parent - // s'il existe - if (loader.getParent() != null) { - loader = loader.getParent(); - } - } - if (!urls.isEmpty()) { - loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), - loader); - } - if (getLog().isDebugEnabled()) { - for (URL u : urls) { - getLog().debug("cp entry: " + u); - } - } - return loader; - } catch (MalformedURLException e) { - throw new MojoExecutionException(e.getMessage()); - } finally { - urls.clear(); - urlsAsString.clear(); - } - - } -} Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GenerateFromModelsMojo.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GenerateFromModelsMojo.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GenerateFromModelsMojo.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,501 +0,0 @@ -package org.nuiton.eugene.plugin; - -import org.apache.commons.lang.StringUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Resource; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.project.MavenProject; -import org.nuiton.eugene.ModelReader; -import org.nuiton.eugene.Template; -import org.nuiton.eugene.models.Model; -import org.nuiton.plugin.PluginHelper; -import org.nuiton.plugin.PluginIOContext; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.*; - -/** - * Created: 15 déc. 2009 - * - * @author Tony Chemit <chemit@codelutin.com> Copyright Code Lutin - * @version $Revision$ - * <p/> - * Mise a jour: $Date$ par : - * $Author: tchemit $ - * @goal generate-from-models - * @requiresProject true - * @since 2.0.0 (replace previous goal {@link EugenePlugin}). - */ -public class GenerateFromModelsMojo extends AbstractEugeneMojo { - - /** - * Les entrées sorties du plugin. - * <p/> - * <p/> - * <p/> - * En entrée on demande des répertoires où chercher les fichiers objectmodel a convertir. - * <p/> - * En sortie on demande le répertoire ou generer les classes java. - * <p/> - * Par défaut on a les valeurs suivantes : - * </p> - * <pre> - * <generateResources> - * </p> - * <input>target/generated-sources/models</input> - * </p> - * <output>target/generated-sources/java</output> - * </p> - * </generateResources> - * </pre> - * </p> - * <p/> - * Note: si {@link #testPhase} est activée, les valeurs par défaut sont : - * </p> - * <pre> - * <generateResources> - * </p> - * <input>target/generated-sources/test-models</input> - * </p> - * <output>target/generated-sources/test-java</output> - * </p> - * </generateResources> - * </pre> - * - * @parameter - * @since 1.0.0-rc-8 - */ - protected PluginIOContext generateResources; - /** - * Templates à utiliser, séparés par des virgules. - * - * @parameter expression="${eugene.templates}" - * @required - * @since 0.50 - */ - protected String templates; - /** - * Templates à ne pas utiliser. - * - * @parameter expression="${eugene.excludeTemplates}" - * @since 0.63 - */ - protected String[] excludeTemplates; - /** - * Fichier à inclure. - * - * @parameter expression="${eugene.includes}" default-value="*.*model" - * @since 0.50 - */ - protected String includes; - /** - * Nom par défaut du paquetage généré. - * - * @parameter expression="${eugene.defaultPackage}" default-value="${project.groupId}.${project.artifactId}" - * @since 0.50 - */ - protected String defaultPackage; - /** - * List of packages to generate (comma separated). - * <p/> - * If the parameter is not filled, will generate all packages. - * - * @parameter expression="${eugene.generatedPackages}" - * @since 1.0.0-rc-8 - */ - protected String generatedPackages; - /** - * To define a specific reader to use to transform input files in a Model to generate. - * <p/> - * If nothing is specified, will use the reader corresponding to the given {@link #modelType}. - * - * @parameter expression="${eugene.reader}" - * @since 1.1.0 - */ - protected String reader; - /** - * All available writers - * - * @component role="org.nuiton.eugene.ModelReader" - */ - protected Map<String, ModelReader<?>> availableReaders; - /** - * All available templates - * - * @component role="org.nuiton.eugene.Template" - */ - protected Map<String, Template<?>> availableTemplates; - - /** - * model reader instance - */ - protected ModelReader<?> modelReader; - /** - * fixed classloader - */ - protected ClassLoader fixedClassLoader; - /** - * list of templates to apply - */ - protected List<Template<Model>> templatesList; - /** - * list of model files to load in the memory reader via the model reader - */ - protected File[] modelFiles; - - @Override - protected boolean init() throws Exception { - boolean b = super.init(); - if (!b) { - // something wrong from the super class, skip now - return false; - } - - // init goal io context - - generateResources = initResources(); - - if (generateResources == null) { - // could not be init... - return false; - } - - // init reader - - modelReader = getModelReader(); - if (modelReader == null) { - // could not be init... - return false; - } - - // get templates to use - - templatesList = getTemplates(getFixedClassLoader()); - - if (templatesList == null || templatesList.isEmpty()) { - getLog().error("No template to apply."); - return false; - } - - //TODO Check excludeTemplates are sane :) - - // get models to treate - - modelFiles = getModelFiles(generateResources); - if (modelFiles.length == 0) { - // can skip - getLog().warn("No model to treate."); - return false; - } - return true; - } - - @Override - public void doAction() throws MojoExecutionException, MojoFailureException { - - getLog().info("Generating java sources from models"); - getLog().info(" reader : " + modelReader.getClass().getName()); - getLog().info(" includes : " + includes); - getLog().info(" using template : " + templates); - getLog().info(" using defaultPackage : " + defaultPackage); - - if (verbose) { - for (File m : modelFiles) { - getLog().info("will treate model file : " + m); - } - } - - // prepare template properties - - Properties templateProperties = new Properties(); - templateProperties.setProperty(Template.PROP_DEFAULT_PACKAGE, defaultPackage); - templateProperties.setProperty(Template.PROP_OVERWRITE, String.valueOf(overwrite)); - templateProperties.setProperty(Template.PROP_ENCODING, encoding); - templateProperties.setProperty(Template.PROP_LAST_MODIFIED_SOURCE, String.valueOf(modelReader.getLastModifiedSource())); - if (StringUtils.isEmpty(generatedPackages)) { - getLog().info(" generating all packages"); - } else { - templateProperties.setProperty(Template.PROP_GENERATED_PACKAGES, generatedPackages); - getLog().info(" generating only for packages " + generatedPackages); - } - templateProperties.setProperty(Template.PROP_EXCLUDE_TEMPLATES, getExcludeTemplatesAsString()); - - // read the model - - Model model = modelReader.read(modelFiles); - - // apply all templates to the model - - for (Template<Model> template : templatesList) { - getLog().info("Apply " + template.getClass().getSimpleName() + " generator"); - - try { - - // init template - template.setProperties(templateProperties); - - // apply template - template.applyTemplate(model, generateResources.getOutput()); - } catch (IOException eee) { - throw new MojoExecutionException("Generation problem", eee); - } - } - - // fix compile root sources - - fixCompileSourceRoots(); - - } - - /** - * Init the {@link #generateResources} io context and return it. - * <p/> - * <b>Note:</b> If something wrong appears, then return a {@code null} value. - * - * @return the io context to use for the goal, or {@code null} if something was wrong - */ - protected PluginIOContext initResources() { - - File defaultIn = getFileFromBasedir("target", "generated-sources", "models"); - File defaultOut = getFileFromBasedir("target", "generated-sources", "java"); - - File defaultTestIn = getFileFromBasedir("target", "generated-sources", "test-models"); - File defaultTestOut = getFileFromBasedir("target", "generated-sources", "test-java"); - - PluginIOContext p = initResources(generateResources, defaultIn, defaultOut, defaultTestIn, defaultTestOut); - - // check context - - if ((p.getInputs() == null || p.getInputs().length == 0)) { - getLog().error("no input defined"); - return null; - } - if (p.getOutput() == null) { - getLog().error("no output defined"); - return null; - } - - if (!p.getOutput().exists()) { - boolean b2 = p.getOutput().mkdirs(); - if (!b2) { - getLog().error("could not create directory " + p.getOutput()); - p = null; - } - } - - return p; - } - - /** - * Obtain the reader to use to read the model. - * <p/> - * <b>Note:</b> If something wrong appears, the return a {@code null} value. - * - * @return the model reader to use to obtain the model to treate, or {@code null} if something was wrong. - */ - protected ModelReader<?> getModelReader() { - - ModelReader<?> modelReader; - - if (reader != null && !reader.trim().isEmpty()) { - // try to load a specific reader - try { - ClassLoader fixedClassLoader = getFixedClassLoader(); - modelReader = (ModelReader<?>) Class.forName(reader, true, fixedClassLoader).newInstance(); - //TODO : should check that the reader is compatible with given modelType - } catch (Exception eee) { - getLog().error("could not obtain reader " + reader + " for reason : " + eee.getMessage()); - return null; - } - } else { - modelReader = availableReaders.get(modelType); - if (modelReader == null) { - getLog().error("could not find a model reader for modelType : " + modelType + ", availables readers : " + availableReaders.values()); - return null; - } - } - return modelReader; - } - - /** - * Recuperation de la liste des fichiers de modele a traite. - * - * @param ioContext io context - * @return la liste des modeles a utiliser - */ - protected File[] getModelFiles(PluginIOContext ioContext) { - - List<File> modelFiles = new ArrayList<File>(); - String[] includePatterns = includes.split(","); - - for (File srcDirGen : ioContext.getInputs()) { - - if (verbose) { - getLog().info("Search for " + Arrays.toString(includePatterns) + " in " + srcDirGen.getAbsolutePath()); - } - List<File> currentFiles = PluginHelper.getIncludedFiles(srcDirGen, includePatterns, null); - modelFiles.addAll(currentFiles); - } - return modelFiles.toArray(new File[modelFiles.size()]); - } - - /** - * Obtain the list of templates to apply to model. - * <p/> - * <b>Note:</b> If something wrong appears, then return a {@code null} value. - * - * @param fixedClassLoader classloader to use to seek of templates - * @return list of templates to apply, or {@code null} if something was wrong - */ - protected List<Template<Model>> getTemplates(ClassLoader fixedClassLoader) { - - List<Template<Model>> templatesList = new ArrayList<Template<Model>>(); - String[] templatesNames = templates.split(","); - for (String templateName : templatesNames) { - // remove trailing spaces - templateName = templateName.trim(); - Template<Model> template; - - template = (Template<Model>) availableTemplates.get(templateName); - if (template == null) { - getLog().warn("template [" + templateName + "] is not registred via plexus, try to load it directly"); - try { - template = (Template<Model>) Class.forName(templateName, true, fixedClassLoader).newInstance(); - } catch (Exception e) { - getLog().error("Can't obtain template [" + templateName + "] for reason " + e.getMessage(), e); - return null; - } - // will use this template - templatesList.add(template); - } - } - return templatesList; - } - - /** - * @return the string representation of excludesTemplates (separated by comma) - */ - protected String getExcludeTemplatesAsString() { - String result = ""; - for (int i = 0; i < excludeTemplates.length; i++) { - result += excludeTemplates[i]; - if (i != excludeTemplates.length - 1) { - result += ","; - } - } - return result; - } - - /** - * Prepare le classLoader a utiliser dans le generateur. - * <p/> - * Si un {@link #extraClassPathDirectory} a été renseigné, il est rajouté. - * <p/> - * Si des références à des sibling modules, ils seront rajoutés aussi. - * - * @return le class loader modifie - * @throws MojoExecutionException if any pb - */ - - public ClassLoader getFixedClassLoader() throws MojoExecutionException { - - if (fixedClassLoader == null) { - - List<URL> urls = new ArrayList<URL>(); - Set<String> urlsAsString = new HashSet<String>(); - try { - ClassLoader loader; - File extraClassPathDirectory = getExtraClassPathDirectory(); - if (extraClassPathDirectory != null) { - if (verbose) { - getLog().info("Add extra directory in generator's classLoader : " + extraClassPathDirectory); - } - addDirectoryToUrlsList(extraClassPathDirectory, urls, urlsAsString); - } - if (project.getProjectReferences() != null) { - // this case is for multi-module when calling from a parent module - for (Object o : project.getProjectReferences().entrySet()) { - Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; - MavenProject relatedProject = (MavenProject) entry.getValue(); - if (verbose) { - getLog().info("Add project reference in generator's classLoader : '" + relatedProject.getArtifact() + "'"); - } - //TODO il faudrait peut-etre aussi ajouter les dependances ? - addDirectoryToUrlsList(relatedProject.getArtifact().getFile(), urls, urlsAsString); - } - } - if (!project.getArtifacts().isEmpty()) { - // this is a special case when artifacts were resolved (for example in site phase) - if (verbose) { - getLog().info("Use resolved artifacts to build class-path"); - } - for (Object o : project.getArtifacts()) { - Artifact a = (Artifact) o; - if (!a.getScope().equals("provided")) { - addDirectoryToUrlsList(a.getFile(), urls, urlsAsString); - } - } - } - // we ask to add the directory in classloader - loader = getClass().getClassLoader(); - if (!urls.isEmpty()) { - loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), - loader); - } - fixedClassLoader = loader; - } catch (MalformedURLException e) { - throw new MojoExecutionException(e.getMessage()); - } finally { - urls.clear(); - urlsAsString.clear(); - } - } - return fixedClassLoader; - } - - /** - * permet d'ajout le répertoire de génération des fichiers java dans les répertoires - * de compilation du projet Maven. - */ - protected void fixCompileSourceRoots() { - - //FIXME-TC20091215 : should never have a null project, this is not normal - if (project == null) { - // no project defined, can not fix anything - // this case could appears if we wanted to do some tests of the plugin - return; - } - - File destDirGen = generateResources.getOutput(); - - //TODO-TC20091016 should use AbstractPlugin api - if (testPhase) { - if (!project.getTestCompileSourceRoots().contains(destDirGen.getPath())) { - getLog().info("Add test compile source root : " + destDirGen); - project.addTestCompileSourceRoot(destDirGen.getPath()); - Resource resources = new Resource(); - resources.setDirectory(destDirGen.getAbsolutePath()); - resources.setExcludes(Arrays.asList("**/*.java")); - getLog().info("Add test resource root :" + resources); - project.addTestResource(resources); - } - } else { - if (!project.getCompileSourceRoots().contains(destDirGen.getPath())) { - getLog().info("Add compile source root : " + destDirGen); - project.addCompileSourceRoot(destDirGen.getPath()); - Resource resources = new Resource(); - resources.setDirectory(destDirGen.getAbsolutePath()); - resources.setExcludes(Arrays.asList("**/*.java")); - getLog().info("Add resource root :" + resources); - project.addResource(resources); - } - } - } - - -} Copied: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/SmartGenerateMojo.java (from rev 763, trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/GeneratateModelFilesMojo.java) =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/SmartGenerateMojo.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/SmartGenerateMojo.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,644 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin; + +import org.apache.commons.lang.StringUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.project.MavenProject; +import org.apache.maven.settings.Settings; +import org.nuiton.eugene.ModelReader; +import org.nuiton.eugene.Template; +import org.nuiton.eugene.models.Model; +import org.nuiton.eugene.plugin.writer.BaseChainedFileWriter; +import org.nuiton.eugene.plugin.writer.BaseXmiToChainedFileWriter; +import org.nuiton.eugene.plugin.writer.ModelChainedFileWriter; +import org.nuiton.eugene.writer.ChainedFileWriter; +import org.nuiton.eugene.writer.ChainedFileWriterConfiguration; +import org.nuiton.eugene.writer.ChainedFileWriterEntry; +import org.nuiton.eugene.writer.ChainedWriterEngine; +import org.nuiton.plugin.AbstractPlugin; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.*; + +/** + * Smart file generator. + * <p/> + * Fill inputs and mojo will chained needed writer. + * <p/> + * User: chemit + * Date: 24 nov. 2009 + * Time: 00:22:37 + * + * @goal smart-generate + * @requiresProject true + * @requiresDependencyResolution compile + */ +public class SmartGenerateMojo extends AbstractPlugin implements ChainedFileWriterConfiguration { + + /** + * Inputs files to used to generate the required model files. + * </p> + * An include has the following pattern : + * <pre> + * writer: + * </pre> + * when you want to use a specific writer with his default io values. + * <p/> + * Can also write : + * <pre> + * [writer:]directory:includes + * </pre> + * where {@code includes} is the pattern to find files from the directory given and must be terminated by the extension + * of files. + * <p/> + * Specifying the {@code writer} can be usefull when you want to use a writer for an unknown extension + * by any writer. + * <p/> + * Example : + * <pre> + * <inputs> + * <input>zargo:</input> + * <input>src/main/xmi2:**\/*.zargo</input> + * <input>zargo:src/main/xmi:**\/*.zargo2</input> + * </inputs> + * </pre> + * + * @parameter expression="${eugene.inputs}" + * @required + * @since 2.0.0 + */ + protected String[] inputs; + /** + * List of input (protocol) not to treate separated by comma. + * <p/> + * Example : + * <pre> + * <skipInputs>xmi</skipInputs> + * <skipInputs>xmi,model</skipInputs> + * </pre> + * + * @parameter expression="${eugene.skipInputs}" + * @since 2.0.0 + */ + protected String skipInputs; + /** + * Where to generate files. + * + * @parameter expression="${eugene.outputDirectory}" default-value="target/generated-sources" + * @required + * @since 2.0.0 + */ + protected File outputDirectory; + /** + * Ecrase les fichiers générés. + * + * @parameter expression="${eugene.overwrite}" default-value="false" + * @since 2.0.0 + */ + protected boolean overwrite; + /** + * Pour activer le mode verbeux. + * + * @parameter expression="${eugene.verbose}" default-value="${maven.verbose}" + * @since 2.0.0 + */ + protected boolean verbose; + /** + * Encoding to be used for generation of files. + * + * @parameter expression="${eugene.encoding}" default-value="${project.build.sourceEncoding}" + * @since 2.0.0 + */ + protected String encoding; + /** + * A flag to mark the mojo to be used in a test phase. This will permits to add generated sources in test compile roots. + * + * @parameter expression="${eugene.testPhase}" default-value="false" + * @since 2.0.0 + */ + protected boolean testPhase; + /** + * The type of model to be used. + * <p/> + * By default, use an {@code objectmodel}. + * + * @parameter expression="${eugene.modelType}" default-value="objectmodel" + * @required + * @since 2.0.0 + */ + protected String modelType; +// /** +// * An extra directory to be added to the classpath. +// * + // * @parameter expression="${eugene.extraClassPathDirectory}" +// * @since 2.0.0 +// */ +// protected File extraClassPathDirectory; + /** + * Properties to pass to writer. + * + * @parameter + * @since 2.0.0 + */ + protected Map<String, Object> properties; + /** + * Ne génère rien, analyse juste la configuration. + * + * @parameter expression="${eugene.dryRun}" default-value="false" + * @since 2.0.0 + */ + protected boolean dryRun; + /** + * Nom du paquetage pour les fichiers générés (xmi input sepcific). + * + * @parameter expression="${generator.fullPackagePath}" default-value="${project.groupId}.${project.artifactId}" + * @since 2.0.0 + */ + protected String fullPackagePath; +// /** +// * Nom du paquetage à générer (xmi input sepcific). +// * + // * @parameter expression="${generator.extractedPackages}" default-value="${project.groupId}.${project.artifactId}" +// * @since 2.0.0 +// */ +// protected String extractedPackages; + /** + * Nom du resolver a utiliser pour les transformations xmi vers model (xmi input sepcific). + * + * @parameter expression="${generator.resolver}" default-value="org.nuiton.util.ResourceResolver" + * @since 2.0.0 + */ + protected String resolver; + /** + * Templates à utiliser, séparés par des virgules pour les transformations depuis les models (model input sepcific). + * + * @parameter expression="${eugene.templates}" + * @since 0.50 + */ + protected String templates; + /** + * Templates à ne pas utiliser lors de la transformations des models (model input sepcific). + * + * @parameter expression="${eugene.excludeTemplates}" + * @since 0.63 + */ + protected String[] excludeTemplates; + /** + * Nom par défaut du paquetage généré (model input sepcific). + * + * @parameter expression="${eugene.defaultPackage}" default-value="${project.groupId}.${project.artifactId}" + * @since 0.50 + */ + protected String defaultPackage; + /** + * List of packages to generate (comma separated). (model input sepcific). + * <p/> + * If the parameter is not filled, will generate all packages. + * + * @parameter expression="${eugene.generatedPackages}" + * @since 1.0.0-rc-8 + */ + protected String generatedPackages; + /** + * Maven project. + * + * @parameter default-value="${project}" + * @readonly + * @since 2.0.0 + */ + protected MavenProject project; + /** + * Le settings (pour obtenir le mode offline). + * + * @parameter default-value="${settings}" + * @readonly + * @since 2.0.0 + */ + protected Settings settings; + + /** + * All available models (obtain by plexus, keys are plexus roles, values are a + * instance of corresponding model). + * + * @component role="org.nuiton.eugene.models.Model" + */ + protected Map<String, Model> _models; + /** + * All available writers introspects via plexus + * + * @component role="org.nuiton.eugene.writer.ChainedFileWriter" + */ + protected Map<String, ChainedFileWriter> writers; + /** + * All available writers introspects via plexus + * + * @component role="org.nuiton.eugene.ModelReader" + */ + protected Map<String, ModelReader<?>> modelReaders; + /** + * All available templates introspects via plexus + * + * @component role="org.nuiton.eugene.Template" + */ + protected Map<String, Template<?>> modelTemplates; + /** + * The engine to compute {@link org.nuiton.eugene.writer.ChainedFileWriter} from inputs entries. + * + * @component role="org.nuiton.eugene.writer.ChainedWriterEngine" + */ + protected ChainedWriterEngine engine; + /** + * class instance of the given {@link #modelType} + */ + protected Class<? extends Model> modelClass; + /** + * fixed classloader + */ + protected ClassLoader fixedClassLoader; + + @Override + protected boolean init() throws Exception { + // on recupere le fqn du model à traiter via le container plexus (plus pratique dans ce cas où on veut + // pouvoir associé un nom à un type de service). + Model model = _models.get(modelType.trim().toLowerCase()); + if (model == null) { + throw new MojoExecutionException("No modelType named '" + modelType + "', use one of " + _models.keySet()); + } + modelClass = model.getClass(); + + if (inputs.length == 0) { + throw new MojoExecutionException("Must specify something to include using the includes property"); + } + //FIXME-TC20091217 use a configurator in plexus ? + // Actually we obtain a different instance of the mojo conflit with mojo and plexus :) + engine.setConfiguration(this); + + Set<ChainedFileWriter> availableWriters = engine.getAvailableWriters(); + + if (availableWriters.isEmpty()) { + throw new MojoExecutionException("Could not find any writer in class-path."); + } + + for (ChainedFileWriter writer : availableWriters) { + if (writer instanceof BaseChainedFileWriter) { + // add log support + ((BaseChainedFileWriter) writer).setLog(getLog()); + } + } + + // detect top level writers + for (String include : inputs) { + + getLog().info("Register include : " + include); + engine.registerInclude(include); + } + + if (engine.getSelectedWriters().isEmpty()) { + getLog().warn("No phase was detected, skip the goal."); + return false; + } + + if (properties == null) { + properties = new LinkedHashMap<String, Object>(); + } + + if (engine.containsWriter("xmi")) { + + // add xmi writer support + + ClassLoader loader = getFixedClassLoader(); + + properties.put(BaseXmiToChainedFileWriter.PROP_CLASS_LOADER, loader); + properties.put(BaseXmiToChainedFileWriter.PROP_FULL_PACKAGE_PATH, fullPackagePath); + //properties.put("extractedPackages", extractedPackages); + properties.put(BaseXmiToChainedFileWriter.PROP_RESOLVER, resolver); + } + + if (engine.containsWriter("model")) { + + // add model writer support + + ClassLoader loader = getFixedClassLoader(); + + properties.put(ModelChainedFileWriter.PROP_CLASS_LOADER, loader); + properties.put(ModelChainedFileWriter.PROP_MODEL_TYPE, modelType); + properties.put(ModelChainedFileWriter.PROP_DEFAULT_PACKAGE, defaultPackage); + properties.put(ModelChainedFileWriter.PROP_GENERATED_PACKAGES, generatedPackages); + properties.put(ModelChainedFileWriter.PROP_TEMPLATES, templates); + properties.put(ModelChainedFileWriter.PROP_EXCLUDE_TEMPLATES, getExcludeTemplatesAsString()); + } + + return true; + } + + @Override + protected void doAction() throws Exception { + if (dryRun) { + getLog().warn("dryRun property is set, no file will be generated."); + } + if (isVerbose()) { + if (isTestPhase()) { + getLog().info(" using testPhase"); + } + } + try { + + List<String> skipInputList = new ArrayList<String>(); + + if (!StringUtils.isEmpty(skipInputs)) { + + for (String s : skipInputs.split(",")) { + skipInputList.add(s.trim()); + } + } + + // launch writers in incoming order of dicovering of them + + for (ChainedFileWriter writer : engine.getSelectedWriters()) { + if (skipInputList.contains(writer.getInputProtocol())) { + getLog().info("Skip phase [" + writer.getInputProtocol() + "] as required in skipInputs configuration."); + continue; + } + int size = writer.getEntries().size(); + if (size == 1) { + getLog().info("Process phase [" + writer.getInputProtocol() + "] for one entry."); + } else { + getLog().info("Process phase [" + writer.getInputProtocol() + "] for " + size + " entries."); + } + if (dryRun || isVerbose()) { + for (ChainedFileWriterEntry entry : writer.getEntries()) { + getLog().info(" entry : " + entry.getInputDirectory() + " - " + entry.getIncludePattern()); + } + if (dryRun) { + continue; + } + } + if (getLog().isDebugEnabled()) { + getLog().debug("Generating files and copying resources..."); + } + + try { + writer.generate(this); + } catch (Exception e) { + throw new MojoExecutionException("could not generate for writer " + writer.getInputProtocol(), e); + } + + if ("model".equals(writer.getInputProtocol())) { + + // must fix source compile roots + File outputDir = writer.getOutputDirectory(getOutputDirectory(), isTestPhase()); + + fixCompileSourceRoots(outputDir); + } + } + + } finally { + // always clear everything to avoid side-effects in goal is invoked more than once + properties.clear(); + engine.clear(); + } + } + + @Override + public File getOutputDirectory() { + return outputDirectory; + } + + @Override + public Map<String, Object> getProperties() { + return properties; + } + + @Override + public MavenProject getProject() { + return project; + } + + @Override + public void setProject(MavenProject project) { + this.project = project; + } + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public String getEncoding() { + return encoding; + } + + @Override + public boolean isOverwrite() { + return overwrite; + } + + @Override + public boolean isOffline() { + return settings.isOffline(); + } + + @Override + public boolean isTestPhase() { + return testPhase; + } + + @Override + public Class<? extends Model> getModelClass() { + return modelClass; + } + + @Override + public Map<String, ChainedFileWriter> getWriters() { + return writers; + } + + @Override + public Map<String, ModelReader<?>> getModelReaders() { + return modelReaders; + } + + @Override + public Map<String, Template<?>> getModelTemplates() { + return modelTemplates; + } + + @Override + public File getBasedir() { + return getProject().getBasedir(); + } + + /** + * @return the string representation of excludesTemplates (separated by comma) + */ + protected String getExcludeTemplatesAsString() { + String result = ""; + for (int i = 0; i < excludeTemplates.length; i++) { + result += excludeTemplates[i]; + if (i != excludeTemplates.length - 1) { + result += ","; + } + } + return result; + } + + /** + * Prepare le classLoader a utiliser dans le generateur. + * <p/> + * Si le mojo est en phase de test {@link #testPhase} a été renseigné, target/classes est rajouté. + * <p/> + * Si des références à des sibling modules, ils seront rajoutés aussi. + * + * @return le class loader modifie + * @throws MojoExecutionException if any pb + */ + + public ClassLoader getFixedClassLoader() throws MojoExecutionException { + if (fixedClassLoader == null) { + Set<String> urlsAsString = new HashSet<String>(); + List<URL> urls = new ArrayList<URL>(); + try { + ClassLoader loader; + + if (testPhase) { + File extraClassPathDirectory = new File(getProject().getBuild().getOutputDirectory()); +// if (verbose) { + getLog().info("Add in generator's classLoader : " + extraClassPathDirectory); +// } + addDirectoryToUrlsList(extraClassPathDirectory, urls, urlsAsString); + } + if (project.getProjectReferences() != null) { + // this case is for multi-module when calling from a parent module + for (Object o : project.getProjectReferences().entrySet()) { + Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; + MavenProject relatedProject = (MavenProject) entry.getValue(); + if (verbose) { + getLog().info("Add project reference in generator's classLoader : '" + relatedProject.getArtifact() + "'"); + } + //TODO il faudrait peut-etre aussi ajouter les dependances ? + addDirectoryToUrlsList(relatedProject.getArtifact().getFile(), urls, urlsAsString); + } + } + if (!project.getArtifacts().isEmpty()) { + // this is a special case when artifacts were resolved (for example in site phase) + if (verbose) { + getLog().info("Use resolved artifacts to build class-path"); + } + for (Object o : project.getArtifacts()) { + Artifact a = (Artifact) o; + if (!a.getScope().equals("provided")) { + addDirectoryToUrlsList(a.getFile(), urls, urlsAsString); + } + } + } + // we ask to add the directory in classloader + loader = getClass().getClassLoader(); + if (getLog().isDebugEnabled()) { + getLog().info("original classloader " + loader); + } + if (loader instanceof URLClassLoader) { + // on reinjecte les urls de loader de base + // car sinon on risque de ne pas retrouver les resources... + for (URL u : ((URLClassLoader) loader).getURLs()) { + addUrlToUrlsList(u, urls, urlsAsString); + if (getLog().isDebugEnabled()) { + getLog().debug("original cp entry: " + u); + } + } + // et on force l'utilisation du classloader parent + // s'il existe + if (loader.getParent() != null) { + loader = loader.getParent(); + } + } + if (!urls.isEmpty()) { + loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), + loader); + } + if (getLog().isDebugEnabled()) { + for (URL u : urls) { + getLog().debug("cp entry: " + u); + } + } + fixedClassLoader = loader; + } catch (MalformedURLException e) { + throw new MojoExecutionException(e.getMessage()); + } finally { + urls.clear(); + urlsAsString.clear(); + } + } + return fixedClassLoader; + } + + /** + * permet d'ajout le répertoire de génération des fichiers java dans les répertoires + * de compilation du projet Maven. + * + * @param destDirGen le repertoire a traiter + */ + protected void fixCompileSourceRoots(File destDirGen) { + + //FIXME-TC20091215 : should never have a null project, this is not normal + if (project == null) { + // no project defined, can not fix anything + // this case could appears if we wanted to do some tests of the plugin + return; + } + + //TODO-TC20091016 should use AbstractPlugin api + if (isTestPhase()) { + if (!project.getTestCompileSourceRoots().contains(destDirGen.getPath())) { + getLog().info("Add test compile source root : " + destDirGen); + project.addTestCompileSourceRoot(destDirGen.getPath()); + Resource resources = new Resource(); + resources.setDirectory(destDirGen.getAbsolutePath()); + resources.setExcludes(Arrays.asList("**/*.java")); + getLog().info("Add test resource root :" + resources); + project.addTestResource(resources); + } + } else { + if (!project.getCompileSourceRoots().contains(destDirGen.getPath())) { + getLog().info("Add compile source root : " + destDirGen); + project.addCompileSourceRoot(destDirGen.getPath()); + Resource resources = new Resource(); + resources.setDirectory(destDirGen.getAbsolutePath()); + resources.setExcludes(Arrays.asList("**/*.java")); + getLog().info("Add resource root :" + resources); + project.addResource(resources); + } + } + } + + +} \ No newline at end of file Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/SmartGenerateMojo.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Copied: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseChainedFileWriter.java (from rev 760, trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseModelFileWriter.java) =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseChainedFileWriter.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseChainedFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,87 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin.writer; + +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugin.logging.SystemStreamLog; +import org.nuiton.eugene.writer.AbstractChainedFileWriter; +import org.nuiton.eugene.writer.ChainedFileWriterConfiguration; + +import java.util.Map; +import java.util.Set; + +/** + * Surcharge de l'implentation abstraite pour avoir le logger de la console maven. + * + * @author tchemit + * @since 2.0.0 + */ +public abstract class BaseChainedFileWriter extends AbstractChainedFileWriter { + + /** + * Logger + */ + private Log log; + + protected BaseChainedFileWriter(String... propertyNameAndDescriptions) { + super(propertyNameAndDescriptions); + } + + public void setLog(Log log) { + this.log = log; + } + + public Log getLog() { + if (log == null) { + log = new SystemStreamLog(); + } + + return log; + } + + @Override + protected void initWriter(ChainedFileWriterConfiguration configuration) { + super.initWriter(configuration); + + // log writer config + + StringBuilder buffer = new StringBuilder(); + Set<Map.Entry<String, String>> set = getAuthorizedPropertyDescriptions().entrySet(); + if (set.isEmpty()) { + buffer.append("Writer [").append(getInputProtocol()).append("]").append(" does not use any specific properties."); + } else { + buffer.append("Writer [").append(getInputProtocol()).append("]").append(" use ").append(properties.size()).append(" properties :"); + if (getLog().isInfoEnabled()) { + for (Map.Entry<String, String> e : set) { + + String key = e.getKey(); + Object value = properties.get(key); + if (value != null) { + buffer.append("\n").append(" [").append(key).append("] (").append(e.getValue()).append(") : ").append(value); + } + } + } + } + getLog().info(buffer.toString()); + } + + +} Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseChainedFileWriter.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseModelFileWriter.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseModelFileWriter.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseModelFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,58 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin.writer; - -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.logging.SystemStreamLog; -import org.nuiton.eugene.AbstractModelFileWriter; - -/** - * Surcharge de l'implentation abstraite pour avoir le logger de la console maven. - * - * @author tchemit - * @since 2.0.0 - */ -public abstract class BaseModelFileWriter extends AbstractModelFileWriter { - - /** - * Logger - */ - private Log log; - public static final String PROP_CLASS_LOADER = "classLoader"; - - public void setLog(Log log) { - this.log = log; - } - - public Log getLog() { - if (log == null) { - log = new SystemStreamLog(); - } - - return log; - } - - public ClassLoader getClassLoader() { - return getProperty(PROP_CLASS_LOADER, ClassLoader.class); - } - - -} Copied: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToChainedFileWriter.java (from rev 761, trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToModelFileWriter.java) =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToChainedFileWriter.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToChainedFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,275 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin.writer; + +import org.nuiton.eugene.models.Model; +import org.nuiton.eugene.writer.ChainedFileWriterConfiguration; +import org.nuiton.plugin.PluginHelper; +import org.nuiton.plugin.PluginIOContext; +import org.nuiton.util.FasterCachedResourceResolver; +import org.nuiton.util.FileUtil; +import org.nuiton.util.Resource; +import org.nuiton.util.ResourceResolver; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.net.URL; +import java.util.List; + +/** + * Implentation pour les writer to type xmi (qui transforme du xmi via xsl). + * + * @author tchemit + * @since 2.0.0 + */ +public abstract class BaseXmiToChainedFileWriter extends BaseChainedFileWriter { + + public static final String PROP_RESOLVER = "resolver"; + // public static final String PROP_EXTRACTED_PACKAGES = "extractedPackages"; + public static final String PROP_FULL_PACKAGE_PATH = "fullPackagePath"; + public static final String PROP_CLASS_LOADER = "classLoader"; + + public BaseXmiToChainedFileWriter() { + super(PROP_CLASS_LOADER, "classLoader", PROP_RESOLVER, "resolver", PROP_FULL_PACKAGE_PATH, "fullPackagePath"); + } + + /** + * Get style sheet. + * + * @param model the model file used to determine the stylesheet to use + * @return the stylesheet name + */ + protected abstract String getStyleSheet(File model); + + /** + * Get extension. + * + * @return the extension + */ + protected abstract String getExtension(); + + @Override + public String getInputProtocol() { + return "xmi"; + } + + @Override + public <M extends Model> String getOutputProtocol(Class<M> modelType) { + // next writer : write from model files + return "model"; + } + + @Override + public boolean acceptInclude(String include) { + return include.startsWith("xmi:") || include.endsWith(".xmi") || include.endsWith(".uml"); + } + + @Override + public String getDefaultIncludes() { + return "**/*.xmi"; + } + + @Override + public String getDefaultInputDirectory() { + return "src/main/xmi"; + } + + @Override + public String getDefaultOutputDirectory() { + return "models"; + } + + @Override + public String getDefaultTestInputDirectory() { + return "src/test/xmi"; + } + + @Override + public String getDefaultTestOutputDirectory() { + return "test-models"; + } + + protected TransformerFactory transformerFactory; + + protected TransformerFactory getTransformerFactory() { + if (transformerFactory == null) { + transformerFactory = TransformerFactory.newInstance(); + } + return transformerFactory; + } + + public String getFullPackagePath() { + return getProperty(PROP_FULL_PACKAGE_PATH, String.class); + } + +// public String getExtractedPackages() { +// return getProperty(PROP_EXTRACTED_PACKAGES, String.class); +// } + + public String getResolver() { + return getProperty(PROP_RESOLVER, String.class); + } + + + public ClassLoader getClassLoader() { + return getProperty(PROP_CLASS_LOADER, ClassLoader.class); + } + + + @Override + public void generate(ChainedFileWriterConfiguration configuration, File outputDir, File inputDirectory, String includePattern) throws IOException { + long t0 = System.nanoTime(); + + boolean overwrite = configuration.isOverwrite(); + try { + getLog().info("Processing XSL tranformation on " + inputDirectory + " for " + includePattern); + + getLog().info(" with fullPackagePath : " + getFullPackagePath()); +// getLog().info(" with extractedPackages : " + getExtractedPackages()); +// getLog().info(" with acceptedXmiTypes : " + getFullPackagePath()); + getLog().info(" with resolver : " + getResolver()); + + // recuperation des fichiers a traiter + List<File> files = PluginHelper.getIncludedFiles(inputDirectory, new String[]{includePattern}, null); + + // lancement des traitements xsl sur les fichiers trouvés + // dans le repertoire + actionXsl(configuration, outputDir, inputDirectory, files, overwrite); + } finally { + getLog().info("xsl done in " + PluginHelper.convertTime(System.nanoTime() - t0)); + } + + getLog().info("Copy resources files"); + + PluginIOContext ioContext = new PluginIOContext(); + ioContext.setInput(inputDirectory); + ioContext.setOutput(outputDir); +// String[] excludes = getSuffixPattern("**/*"); + PluginHelper.copyFiles(ioContext, null, new String[]{includePattern}, overwrite); + } + + + protected void actionXsl(ChainedFileWriterConfiguration configuration, File outputDir, File dir, List<File> files, boolean overwrite) throws IOException { + + for (File file : files) { + try { + if (getLog().isDebugEnabled()) { + getLog().debug("treate file : " + file); + } + // Prepare resolver, stylesheet + URIResolver fileResolver = getUriResolver(configuration, file); + String styleSheet = getStyleSheet(file); + URL xsl = Resource.getURL(styleSheet); + + //TC-20090820 : using recursive for xmi +// File result = new File(destDirModel, FileUtil.basename(file, +// acceptedSuffixes).concat(".").concat(getExtension())); + + String extension = "." + FileUtil.extension(file); + String filename = FileUtil.basename(file, extension).concat(".").concat(getExtension()); + String relatifPath = file.getParentFile().getAbsolutePath().substring(dir.getAbsolutePath().length()); + File dstDir = outputDir; + if (!relatifPath.isEmpty()) { + dstDir = new File(dstDir, relatifPath); + if (!dstDir.exists()) { + boolean b = dstDir.mkdirs(); + if (!b) { + throw new IOException("could not create directory " + dstDir); + } + } + } + File result = new File(dstDir, filename); + if (!overwrite && file.lastModified() < result.lastModified()) { + getLog().info("file up-to-date : " + result); + continue; + } + if (getLog().isDebugEnabled()) { + getLog().debug("generate " + result); + } + + // Create the xsl transformer and set parameters + Transformer transformer = getTransformerFactory().newTransformer(new StreamSource(xsl.openStream())); + + transformer.setParameter(PROP_FULL_PACKAGE_PATH, getFullPackagePath()); + //transformer.setParameter("extraPackages", getExtractedPackages()); + + transformer.setURIResolver(fileResolver); + transformer.transform(new StreamSource(file), new StreamResult( + new FileOutputStream(result))); + + } catch (Exception e) { + throw new IOException(e.getMessage(), e); + } + } + } + + protected URIResolver getUriResolver(ChainedFileWriterConfiguration configuration, File model) { + URIResolver result = null; + + try { + ClassLoader loader = getClassLoader(); + Class<?> clazz = Class.forName(getResolver(), true, loader); + + // Try to set the base using the constructor + try { + // Look for a constructor with a String parameter (base) + Constructor<?> withBaseConstructor = clazz.getConstructor(String.class); + // Set the xmi folder as the base + String base = model.getParentFile().getAbsolutePath(); + // Instantiate + result = (URIResolver) withBaseConstructor.newInstance(base); + } catch (Exception eee) { + getLog().warn("Unable to instantiate resolver with String parameter", + eee); + } + + // If resolver is still not created, create it using the default + // constructor + if (result == null) { + result = (URIResolver) clazz.newInstance(); + } + + if (result instanceof ResourceResolver) { + ((ResourceResolver) result).setVerbose(configuration.isVerbose()); + ((ResourceResolver) result).setCl(loader); + if (result instanceof FasterCachedResourceResolver) { + boolean offline = configuration.isOffline(); + getLog().debug("using offline mode ? : " + offline); + ((FasterCachedResourceResolver) result).setOffline(offline); + } + } + + } catch (Exception eee) { + getLog().warn("Unable to instantiate resolver using the default constructor", eee); + } + + return result; + } + + +} Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToChainedFileWriter.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToModelFileWriter.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToModelFileWriter.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/BaseXmiToModelFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,261 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin.writer; - -import org.nuiton.eugene.models.Model; -import org.nuiton.plugin.PluginHelper; -import org.nuiton.plugin.PluginIOContext; -import org.nuiton.util.FasterCachedResourceResolver; -import org.nuiton.util.FileUtil; -import org.nuiton.util.Resource; -import org.nuiton.util.ResourceResolver; - -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.URIResolver; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.net.URL; -import java.util.List; - -/** - * Implentation pour les writer to type xmi (qui transforme du xmi via xsl). - * - * @author tchemit - * @since 2.0.0 - */ -public abstract class BaseXmiToModelFileWriter extends BaseModelFileWriter { - public static final String PROP_RESOLVER = "resolver"; -// public static final String PROP_EXTRACTED_PACKAGES = "extractedPackages"; - public static final String PROP_FULL_PACKAGE_PATH = "fullPackagePath"; - - /** - * Get style sheet. - * - * @param model the model file used to determine the stylesheet to use - * @return the stylesheet name - */ - protected abstract String getStyleSheet(File model); - - /** - * Get extension. - * - * @return the extension - */ - protected abstract String getExtension(); - - @Override - public String getInputProtocol() { - return "xmi"; - } - - @Override - public <M extends Model> String getOutputProtocol(Class<M> modelType) { - // no next writer : write model files - return null; - } - - @Override - public boolean acceptInclude(String include) { - return include.startsWith("xmi:") || include.endsWith(".xmi") || include.endsWith(".uml"); - } - - @Override - public String getDefaultIncludes() { - return "**/*.xmi"; - } - - @Override - public String getDefaultInputDirectory() { - return "src/main/xmi"; - } - - @Override - public String getDefaultOutputDirectory() { - return "models"; - } - - @Override - public String getDefaultTestInputDirectory() { - return "src/test/xmi"; - } - - @Override - public String getDefaultTestOutputDirectory() { - return "test-models"; - } - - protected TransformerFactory transformerFactory; - - protected TransformerFactory getTransformerFactory() { - if (transformerFactory == null) { - transformerFactory = TransformerFactory.newInstance(); - } - return transformerFactory; - } - - public String getFullPackagePath() { - return getProperty(PROP_FULL_PACKAGE_PATH, String.class); - } - -// public String getExtractedPackages() { -// return getProperty(PROP_EXTRACTED_PACKAGES, String.class); -// } - - public String getResolver() { - return getProperty(PROP_RESOLVER, String.class); - } - - - @Override - public void generate(File outputDir, File inputDirectory, String includePattern, boolean overwrite) throws IOException { - long t0 = System.nanoTime(); - try { - getLog().info("Processing XSL tranformation on " + inputDirectory + " for " + includePattern); - - getLog().info(" with fullPackagePath : " + getFullPackagePath()); -// getLog().info(" with extractedPackages : " + getExtractedPackages()); -// getLog().info(" with acceptedXmiTypes : " + getFullPackagePath()); - getLog().info(" with resolver : " + getResolver()); - - // recuperation des fichiers a traiter - List<File> files = PluginHelper.getIncludedFiles(inputDirectory, new String[]{includePattern}, null); - - // lancement des traitements xsl sur les fichiers trouvés - // dans le repertoire - actionXsl(outputDir, inputDirectory, files, getClassLoader(), overwrite); - } finally { - getLog().info("xsl done in " + PluginHelper.convertTime(System.nanoTime() - t0)); - } - - getLog().info("Copy resources files"); - - PluginIOContext ioContext = new PluginIOContext(); - ioContext.setInput(inputDirectory); - ioContext.setOutput(outputDir); -// String[] excludes = getSuffixPattern("**/*"); - PluginHelper.copyFiles(ioContext, null, new String[]{includePattern}, overwrite); - } - - - protected void actionXsl(File outputDir, File dir, List<File> files, ClassLoader fixedClassLoader, boolean overwrite) throws IOException { - - for (File file : files) { - try { - if (getLog().isDebugEnabled()) { - getLog().debug("treate file : " + file); - } - // Prepare resolver, stylesheet - URIResolver fileResolver = getUriResolver(file, fixedClassLoader); - String styleSheet = getStyleSheet(file); - URL xsl = Resource.getURL(styleSheet); - - //TC-20090820 : using recursive for xmi -// File result = new File(destDirModel, FileUtil.basename(file, -// acceptedSuffixes).concat(".").concat(getExtension())); - - String extension = "." + FileUtil.extension(file); - String filename = FileUtil.basename(file, extension).concat(".").concat(getExtension()); - String relatifPath = file.getParentFile().getAbsolutePath().substring(dir.getAbsolutePath().length()); - File dstDir = outputDir; - if (!relatifPath.isEmpty()) { - dstDir = new File(dstDir, relatifPath); - if (!dstDir.exists()) { - boolean b = dstDir.mkdirs(); - if (!b) { - throw new IOException("could not create directory "+dstDir); - } - } - } - File result = new File(dstDir, filename); - if (!overwrite && file.lastModified() < result.lastModified()) { - getLog().info("file up-to-date : " + result); - continue; - } - if (getLog().isDebugEnabled()) { - getLog().debug("generate " + result); - } - - // Create the xsl transformer and set parameters - Transformer transformer = getTransformerFactory().newTransformer(new StreamSource(xsl.openStream())); - - transformer.setParameter(PROP_FULL_PACKAGE_PATH, getFullPackagePath()); - //transformer.setParameter("extraPackages", getExtractedPackages()); - - transformer.setURIResolver(fileResolver); - transformer.transform(new StreamSource(file), new StreamResult( - new FileOutputStream(result))); - - } catch (Exception e) { - throw new IOException(e.getMessage(), e); - } - } - } - - - protected URIResolver getUriResolver(File model, ClassLoader cl) { - URIResolver result = null; - - try { - Class<?> clazz = Class.forName(getResolver(), true, cl); - - // Try to set the base using the constructor - try { - // Look for a constructor with a String parameter (base) - Constructor<?> withBaseConstructor = clazz.getConstructor(String.class); - // Set the xmi folder as the base - String base = model.getParentFile().getAbsolutePath(); - // Instantiate - result = (URIResolver) withBaseConstructor.newInstance(base); - } catch (Exception eee) { - getLog().warn("Unable to instantiate resolver with String parameter", - eee); - } - - // If resolver is still not created, create it using the default - // constructor - if (result == null) { - result = (URIResolver) clazz.newInstance(); - } - - if (result instanceof ResourceResolver) { - ((ResourceResolver) result).setVerbose(getConfiguration().isVerbose()); - ((ResourceResolver) result).setCl(cl); - if (result instanceof FasterCachedResourceResolver) { - boolean offline = getConfiguration().isOffline(); - getLog().debug("using offline mode ? : " + offline); - ((FasterCachedResourceResolver) result).setOffline(offline); - } - } - - } catch (Exception eee) { - getLog().warn("Unable to instantiate resolver using the default constructor", eee); - } - - return result; - } - - -} Added: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ModelChainedFileWriter.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ModelChainedFileWriter.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ModelChainedFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,265 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin.writer; + +import org.apache.commons.lang.StringUtils; +import org.nuiton.eugene.ModelReader; +import org.nuiton.eugene.Template; +import org.nuiton.eugene.models.Model; +import org.nuiton.eugene.writer.ChainedFileWriterConfiguration; +import org.nuiton.plugin.PluginHelper; +import org.nuiton.plugin.PluginIOContext; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + +/** + * To write model files from zargo files. + * + * @author tchemit + * @plexus.component role="org.nuiton.eugene.writer.ChainedFileWriter" role-hint="model2Java" + * @since 2.0.0 + */ +public class ModelChainedFileWriter extends BaseChainedFileWriter { + + public static final String PROP_GENERATED_PACKAGES = "generatedPackages"; + public static final String PROP_EXCLUDE_TEMPLATES = "excludetemplates"; + public static final String PROP_TEMPLATES = "templates"; + public static final String PROP_TEMPLATES_LIST = "templatesList"; + public static final String PROP_DEFAULT_PACKAGE = "defaultPackage"; + public static final String PROP_MODEL_READER = "modelReader"; + public static final String PROP_MODEL_TYPE = "modelType"; + public static final String PROP_READER = "reader"; + public static final String PROP_CLASS_LOADER = "classLoader"; + + public ModelChainedFileWriter() { + super( + PROP_TEMPLATES, "templates", + PROP_TEMPLATES_LIST, "templatesList", + PROP_EXCLUDE_TEMPLATES, "excludetemplates", + PROP_READER, "reader", + PROP_MODEL_TYPE, "modelType", + PROP_MODEL_READER, "modelReader", + PROP_GENERATED_PACKAGES, "generatedPackages", + PROP_DEFAULT_PACKAGE, "defaultPackage", + PROP_CLASS_LOADER, "classLoader"); + } + + @Override + public String getInputProtocol() { + return "model"; + } + + @Override + public <M extends Model> String getOutputProtocol(Class<M> modelType) { + // nothing after java files + return null; + } + + @Override + public <M extends Model> boolean acceptModel(Class<M> modelType) { + // accept all models + return true; + } + + @Override + public boolean acceptInclude(String include) { + return include.startsWith("model:") || include.endsWith(".objectmodel") || include.endsWith(".statemodel"); + } + + @Override + public String getDefaultIncludes() { + return "**/*.*model"; + } + + @Override + public String getDefaultInputDirectory() { + return "src/main/models"; + } + + @Override + public String getDefaultOutputDirectory() { + return "java"; + } + + @Override + public String getDefaultTestInputDirectory() { + return "src/test/models"; + } + + @Override + public String getDefaultTestOutputDirectory() { + return "test-java"; + } + + public String getDefaultPackage() { + return getProperty(PROP_DEFAULT_PACKAGE, String.class); + } + + public String[] getExcludeTemplates() { + return getProperty(PROP_EXCLUDE_TEMPLATES, String[].class); + } + + public String getGeneratedPackages() { + return getProperty(PROP_GENERATED_PACKAGES, String.class); + } + + public List<Template<Model>> getTemplatesList() { + return getProperty(PROP_TEMPLATES_LIST, List.class); + } + + public String getTemplates() { + return getProperty(PROP_TEMPLATES, String.class); + } + + protected ModelReader<?> getModelReader() { + return getProperty(PROP_MODEL_READER, ModelReader.class); + } + + protected String getReader() { + return getProperty(PROP_READER, String.class); + } + + protected String getModelType() { + return getProperty(PROP_MODEL_TYPE, String.class); + } + + public ClassLoader getClassLoader() { + return getProperty(PROP_CLASS_LOADER, ClassLoader.class); + } + + @Override + protected void initWriter(ChainedFileWriterConfiguration configuration) { + super.initWriter(configuration); + + // obtain a reader + ClassLoader loader = getClassLoader(); + if (getModelReader() == null) { + + if (getReader() != null) { + // use a specific reader + String reader = getReader(); + try { + ClassLoader fixedClassLoader = loader; + ModelReader<?> modelReader = (ModelReader<?>) Class.forName(reader, true, fixedClassLoader).newInstance(); + //TODO : should check that the reader is compatible with given modelType + properties.put(PROP_MODEL_READER, modelReader); + } catch (Exception eee) { + throw new IllegalStateException("could not obtain reader " + reader, eee); + } + } else { + String modelType = getModelType(); + ModelReader<?> modelReader = configuration.getModelReaders().get(modelType); + if (modelReader == null) { + throw new IllegalStateException("could not find a model reader for modelType : " + modelType + ", availables readers : " + configuration.getModelReaders().values()); + } + properties.put(PROP_MODEL_READER, modelReader); + } + } + + Properties templateProperties = new Properties(); + templateProperties.setProperty(Template.PROP_DEFAULT_PACKAGE, getDefaultPackage()); + templateProperties.setProperty(Template.PROP_OVERWRITE, String.valueOf(configuration.isOverwrite())); + templateProperties.setProperty(Template.PROP_ENCODING, configuration.getEncoding()); + templateProperties.setProperty(Template.PROP_LAST_MODIFIED_SOURCE, String.valueOf(getModelReader().getLastModifiedSource())); + String generatedPackages = getGeneratedPackages(); + if (StringUtils.isEmpty(generatedPackages)) { + getLog().info(" generating all packages"); + } else { + templateProperties.put(Template.PROP_GENERATED_PACKAGES, generatedPackages); + getLog().info(" generating only for packages " + generatedPackages); + } + + // init templates + + List<Template<Model>> templatesList = new ArrayList<Template<Model>>(); + String[] templatesNames = getTemplates().split(","); + for (String templateName : templatesNames) { + // remove trailing spaces + templateName = templateName.trim(); + Template<Model> template; + + template = (Template<Model>) configuration.getModelTemplates().get(templateName); + if (template == null) { + getLog().warn("template [" + templateName + "] is not registred via plexus, try to load it directly"); + try { + template = (Template<Model>) Class.forName(templateName, true, loader).newInstance(); + } catch (Exception e) { + throw new IllegalStateException("Can't obtain template [" + templateName + "] for reason " + e.getMessage(), e); + } + + // will use this template + templatesList.add(template); + + // set the properties of the template + template.setProperties(templateProperties); + } + } + + properties.put(PROP_TEMPLATES_LIST, templatesList); + } + + + @Override + public void generate(ChainedFileWriterConfiguration configuration, File outputDir, File inputDirectory, String includePattern) throws IOException { + + PluginIOContext ioContext = new PluginIOContext(); + ioContext.setInput(inputDirectory); + ioContext.setOutput(outputDir); + + // obtain files + + List<File> modelFiles = new ArrayList<File>(); + String[] includePatterns = includePattern.split(","); + + getLog().info("Generating from " + inputDirectory + " : " + includePattern); + + for (File srcDirGen : ioContext.getInputs()) { + + if (configuration.isVerbose()) { + getLog().info("Search for " + Arrays.toString(includePatterns) + " in " + srcDirGen.getAbsolutePath()); + } + List<File> currentFiles = PluginHelper.getIncludedFiles(srcDirGen, includePatterns, null); + modelFiles.addAll(currentFiles); + } + + // read the model + + Model model = getModelReader().read(modelFiles.toArray(new File[modelFiles.size()])); + + // apply all templates to the model + + for (Template<Model> template : getTemplatesList()) { + getLog().info("Apply " + template.getClass().getSimpleName() + " generator"); + + // apply template + template.applyTemplate(model, ioContext.getOutput()); + + } + + + } + +} \ No newline at end of file Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ModelChainedFileWriter.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Copied: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelChainedFileWriter.java (from rev 761, trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelFileWriter.java) =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelChainedFileWriter.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelChainedFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,135 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin.writer; + +import org.nuiton.eugene.models.Model; +import org.nuiton.eugene.models.object.ObjectModel; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import java.io.File; +import java.io.IOException; + +/** + * To write a object model files from xmi files. + * <p/> + * This {@link org.nuiton.eugene.writer.ChainedFileWriter} transform xmi files to object model file. + * + * @author tchemit + * @plexus.component role="org.nuiton.eugene.writer.ChainedFileWriter" role-hint="xmi2objectmodel" + * @since 2.0.0 + */ +public class XmiToObjectModelChainedFileWriter extends BaseXmiToChainedFileWriter { + + @Override + public <M extends Model> boolean acceptModel(Class<M> modelType) { + // accept only state models + return ObjectModel.class.isAssignableFrom(modelType); + } + + @Override + public String getExtension() { + return "objectmodel"; + } + + @Override + protected String getStyleSheet(File model) { + String styleSheet = null; + + String version = getXmiVersion(model); + if (version.startsWith("1.")) { + styleSheet = "xmi1.2ToObjectModel.xsl"; + } else if (version.startsWith("2.")) { + styleSheet = "xmi2.1ToObjectModel.xsl"; + } else { + getLog().error("Unsupported xmi version [" + version + "]"); + } + + return styleSheet; + } + + /** + * Try to find xmi version on a file. + * + * @param xmiFile file to inspect + * @return version or null if version can't have been found + */ + protected String getXmiVersion(File xmiFile) { + String version = null; + + SAXParserFactory factory = SAXParserFactory.newInstance(); + + try { + SAXParser parser = factory.newSAXParser(); + + XmiVersionHandler handler = new XmiVersionHandler(); + parser.parse(xmiFile, handler); + + version = handler.getVersion(); + } catch (ParserConfigurationException e) { + getLog().debug("Can't parse file as xmi", e); + } catch (SAXException e) { + getLog().debug("Can't parse file as xmi", e); + } catch (IOException e) { + getLog().debug("Can't parse file as xmi", e); + } + + return version; + } + + /** + * Sax handler to find xmi version into xmi document. + */ + protected class XmiVersionHandler extends DefaultHandler { + + protected String version = null; + + public XmiVersionHandler() { + super(); + } + + public String getVersion() { + return version; + } + + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { + + if (qName.equals("XMI")) { + version = attributes.getValue("xmi.version"); + getLog().debug("XMI version found : " + version); + } + + if (version == null) { + version = attributes.getValue("xmi:version"); + getLog().debug("XMI version found : " + version); + } + + } + } + + +} Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelChainedFileWriter.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelFileWriter.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelFileWriter.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToObjectModelFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,136 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin.writer; - -import org.nuiton.eugene.models.Model; -import org.nuiton.eugene.models.object.ObjectModel; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import java.io.File; -import java.io.IOException; - -/** - * To write a object model files from xmi files. - * <p/> - * This {@link org.nuiton.eugene.ModelFileWriter} transform xmi files to object model file. - * - * @author tchemit - * @plexus.component role="org.nuiton.eugene.ModelFileWriter" role-hint="xmi2objectmodel" - * @since 2.0.0 - */ -public class XmiToObjectModelFileWriter extends BaseXmiToModelFileWriter { - - - @Override - public <M extends Model> boolean acceptModel(Class<M> modelType) { - // accept only state models - return ObjectModel.class.isAssignableFrom(modelType); - } - - @Override - public String getExtension() { - return "objectmodel"; - } - - @Override - protected String getStyleSheet(File model) { - String styleSheet = null; - - String version = getXmiVersion(model); - if (version.startsWith("1.")) { - styleSheet = "xmi1.2ToObjectModel.xsl"; - } else if (version.startsWith("2.")) { - styleSheet = "xmi2.1ToObjectModel.xsl"; - } else { - getLog().error("Unsupported xmi version [" + version + "]"); - } - - return styleSheet; - } - - /** - * Try to find xmi version on a file. - * - * @param xmiFile file to inspect - * @return version or null if version can't have been found - */ - protected String getXmiVersion(File xmiFile) { - String version = null; - - SAXParserFactory factory = SAXParserFactory.newInstance(); - - try { - SAXParser parser = factory.newSAXParser(); - - XmiVersionHandler handler = new XmiVersionHandler(); - parser.parse(xmiFile, handler); - - version = handler.getVersion(); - } catch (ParserConfigurationException e) { - getLog().debug("Can't parse file as xmi", e); - } catch (SAXException e) { - getLog().debug("Can't parse file as xmi", e); - } catch (IOException e) { - getLog().debug("Can't parse file as xmi", e); - } - - return version; - } - - /** - * Sax handler to find xmi version into xmi document. - */ - protected class XmiVersionHandler extends DefaultHandler { - - public String version = null; - - public XmiVersionHandler() { - super(); - } - - public String getVersion() { - return version; - } - - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - - if (qName.equals("XMI")) { - version = attributes.getValue("xmi.version"); - getLog().debug("XMI version found : " + version); - } - - if (version == null) { - version = attributes.getValue("xmi:version"); - getLog().debug("XMI version found : " + version); - } - - } - } - - -} Copied: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelChainedFileWriter.java (from rev 760, trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelFileWriter.java) =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelChainedFileWriter.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelChainedFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,53 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin.writer; + +import org.nuiton.eugene.models.Model; +import org.nuiton.eugene.models.state.StateModel; + +import java.io.File; + +/** + * To write state model files from xmi files. + * + * @author tchemit + * @plexus.component role="org.nuiton.eugene.writer.ChainedFileWriter" role-hint="xmi2statemodel" + * @since 2.0.0 + */ +public class XmiToStateModelChainedFileWriter extends BaseXmiToChainedFileWriter { + + @Override + public <M extends Model> boolean acceptModel(Class<M> modelType) { + // accept only state models + return StateModel.class.isAssignableFrom(modelType); + } + + @Override + protected String getExtension() { + return "statemodel"; + } + + @Override + protected String getStyleSheet(File model) { + //TODO when StateModel will be supported in 2.1, compute the version to resolve the correct stylesheet + return "xmi1.2ToStateModel.xsl"; + } +} Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelChainedFileWriter.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelFileWriter.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelFileWriter.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/XmiToStateModelFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,53 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin.writer; - -import org.nuiton.eugene.models.Model; -import org.nuiton.eugene.models.state.StateModel; - -import java.io.File; - -/** - * To write state model files from xmi files. - * - * @author tchemit - * @plexus.component role="org.nuiton.eugene.ModelFileWriter" role-hint="xmi2statemodel" - * @since 2.0.0 - */ -public class XmiToStateModelFileWriter extends BaseXmiToModelFileWriter { - - @Override - public <M extends Model> boolean acceptModel(Class<M> modelType) { - // accept only state models - return StateModel.class.isAssignableFrom(modelType); - } - - @Override - protected String getExtension() { - return "statemodel"; - } - - @Override - protected String getStyleSheet(File model) { - //TODO when StateModel will be supported in 2.1, compute the version to resolve the correct stylesheet - return "xmi1.2ToStateModel.xsl"; - } -} Copied: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoChainedFileWriter.java (from rev 761, trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoModelFileWriter.java) =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoChainedFileWriter.java (rev 0) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoChainedFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -0,0 +1,104 @@ +/* + * *##% + * EUGene :: Maven plugin + * Copyright (C) 2006 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.eugene.plugin.writer; + +import org.nuiton.eugene.models.Model; +import org.nuiton.eugene.writer.ChainedFileWriterConfiguration; +import org.nuiton.plugin.PluginHelper; +import org.nuiton.plugin.PluginIOContext; + +import java.io.File; +import java.io.IOException; + +/** + * To write model files from zargo files. + * + * @author tchemit + * @plexus.component role="org.nuiton.eugene.writer.ChainedFileWriter" role-hint="zargo2xmi" + * @since 2.0.0 + */ +public class ZargoChainedFileWriter extends BaseChainedFileWriter { + + public static final String[] XMI_FILE_FILTER = new String[]{"*.xmi", "**/*.xmi"}; + + @Override + public String getInputProtocol() { + return "zargo"; + } + + @Override + public <M extends Model> String getOutputProtocol(Class<M> modelType) { + // next writer to use is a xmi to model one + return "xmi"; + } + + @Override + public <M extends Model> boolean acceptModel(Class<M> modelType) { + // accept all models + return true; + } + + @Override + public boolean acceptInclude(String include) { + return include.startsWith("zargo:") || include.endsWith(".zargo") || include.endsWith(".zuml"); + } + + @Override + public String getDefaultIncludes() { + return "**/*.zargo"; + } + + @Override + public String getDefaultInputDirectory() { + return "src/main/xmi"; + } + + @Override + public String getDefaultOutputDirectory() { + return "xmi"; + } + + @Override + public String getDefaultTestInputDirectory() { + return "src/test/xmi"; + } + + @Override + public String getDefaultTestOutputDirectory() { + return "test-xmi"; + } + + @Override + public void generate(ChainedFileWriterConfiguration configuration, File outputDir, File inputDirectory, String includePattern) throws IOException { + + boolean overwrite = configuration.isOverwrite(); + + PluginIOContext ioContext = new PluginIOContext(); + ioContext.setInput(inputDirectory); + ioContext.setOutput(outputDir); + + getLog().info("Expanding xmi from " + inputDirectory + " : " + includePattern); + PluginHelper.expandFiles(ioContext, new String[]{includePattern}, null, XMI_FILE_FILTER, overwrite); + + getLog().info("Copying resources from " + inputDirectory + " : " + includePattern); + PluginHelper.copyFiles(ioContext, null, new String[]{includePattern}, overwrite); + } +} Property changes on: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoChainedFileWriter.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Deleted: trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoModelFileWriter.java =================================================================== --- trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoModelFileWriter.java 2009-12-18 10:23:09 UTC (rev 764) +++ trunk/maven-eugene-plugin/src/main/java/org/nuiton/eugene/plugin/writer/ZargoModelFileWriter.java 2009-12-18 10:26:52 UTC (rev 765) @@ -1,101 +0,0 @@ -/* - * *##% - * EUGene :: Maven plugin - * Copyright (C) 2006 - 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton.eugene.plugin.writer; - -import org.nuiton.eugene.models.Model; -import org.nuiton.plugin.PluginHelper; -import org.nuiton.plugin.PluginIOContext; - -import java.io.File; -import java.io.IOException; - -/** - * To write model files from zargo files. - * - * @author tchemit - * @plexus.component role="org.nuiton.eugene.ModelFileWriter" role-hint="zargo2xmi" - * @since 2.0.0 - */ -public class ZargoModelFileWriter extends BaseModelFileWriter { - - public static final String[] XMI_FILE_FILTER = new String[]{"*.xmi", "**/*.xmi"}; - - @Override - public String getInputProtocol() { - return "zargo"; - } - - @Override - public <M extends Model> String getOutputProtocol(Class<M> modelType) { - // next writer to use is a xmi to model one - return "xmi"; - } - - @Override - public <M extends Model> boolean acceptModel(Class<M> modelType) { - // accept all models - return true; - } - - @Override - public boolean acceptInclude(String include) { - return include.startsWith("zargo:") || include.endsWith(".zargo") || include.endsWith(".zuml"); - } - - @Override - public String getDefaultIncludes() { - return "**/*.zargo"; - } - - @Override - public String getDefaultInputDirectory() { - return "src/main/xmi"; - } - - @Override - public String getDefaultOutputDirectory() { - return "xmi"; - } - - @Override - public String getDefaultTestInputDirectory() { - return "src/test/xmi"; - } - - @Override - public String getDefaultTestOutputDirectory() { - return "test-xmi"; - } - - @Override - public void generate(File outputDir, File inputDirectory, String includePattern, boolean overwrite) throws IOException { - - PluginIOContext ioContext = new PluginIOContext(); - ioContext.setInput(inputDirectory); - ioContext.setOutput(outputDir); - - getLog().info("Expanding xmi from " + inputDirectory + " : " + includePattern); - PluginHelper.expandFiles(ioContext, new String[]{includePattern}, null, XMI_FILE_FILTER, overwrite); - - getLog().info("Copying resources from " + inputDirectory + " : " + includePattern); - PluginHelper.copyFiles(ioContext, null, new String[]{includePattern}, overwrite); - } -}
participants (1)
-
tchemit@users.nuiton.org