[prev in list] [next in list] [prev in thread] [next in thread] 

List:       jibx-cvs
Subject:    [Jibx-cvs] maven-jibx-plugin/src/main/java/org/jibx/maven
From:       Jerome Bernard <jeje () users ! sourceforge ! net>
Date:       2009-07-27 14:53:41
Message-ID: E1MVRa9-0006wJ-Ig () fdv4jf1 ! ch3 ! sourceforge ! com
[Download RAW message or body]

Update of /cvsroot/jibx/maven-jibx-plugin/src/main/java/org/jibx/maven
In directory fdv4jf1.ch3.sourceforge.com:/tmp/cvs-serv26663/src/main/java/org/jibx/maven


Added Files:
	CompileBindingMojo.java SchemaCodeGenMojo.java 
Removed Files:
	JibxMojo.java 
Log Message:
Added support for XSD->Java tool. Improved documentation.

--- NEW FILE: CompileBindingMojo.java ---
/*
 * Copyright (c) 2004-2005, Dennis M. Sosnoski All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, \
                are permitted provided that the
 * following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list \
                of conditions and the following
 * disclaimer. Redistributions in binary form must reproduce the above copyright \
                notice, this list of conditions and the
 * following disclaimer in the documentation and/or other materials provided with the \
                distribution. Neither the name of
 * JiBX nor the names of its contributors may be used to endorse or promote products \
                derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND \
                ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \
                FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR \
                ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \
                PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED \
                AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \
                ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.jibx.maven;

import java.io.File;
import java.io.FilenameFilter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FilenameUtils;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.oro.io.GlobFilenameFilter;

import org.jibx.binding.Compile;
import org.jibx.runtime.JiBXException;

/**
 * Runs the JiBX binding compiler.
 *
 * @author                        <a href="mailto:mail@andreasbrenk.com">Andreas \
                Brenk</a>
 * @author                        <a href="mailto:frankm.os@gmail.gom">Frank Mena</a>
 * @goal                          bind
 * @phase                         process-classes
 * @requiresDependencyResolution  compile
 */
public class CompileBindingMojo extends AbstractMojo {

    //~ Static fields/initializers \
-------------------------------------------------------------------------------------

    private static final String DEFAULT_INCLUDES = "binding.xml";

    //~ Instance fields \
------------------------------------------------------------------------------------------------


    /**
     * The directory which contains binding files.
     *
     * @parameter  expression="${directory}" default-value="src/main/config"
     * @required
     */
    private String directory;

    /**
     * Exclude pattern for binding files.
     *
     * @parameter  expression="${excludes}"
     */
    private ArrayList excludes;

    /**
     * Include pattern for binding files.
     *
     * @parameter  expression="${includes}"
     */
    private ArrayList includes;

    /**
     * Control flag for test loading generated/modified classes.
     *
     * @parameter  expression="${load}" default-value="false"
     * @required
     */
    private boolean load;

    /**
     * A list of modules to search for binding files in the format: \
                groupID:artifactID
     *
     * @parameter  expression="${modules}"
     */
    private HashSet modules;

    /**
     * Control flag multi-module mode.
     *
     * @parameter  expression="${multi-module}" default-value="false"
     * @required
     */
    private boolean multimodule;

    /**
     * The maven project.
     *
     * @resolveTransitiveDependencies
     * @parameter                      expression="${project}"
     * @required
     * @readonly
     */
    private MavenProject project;

    /**
     * Control flag for test loading generated/modified classes.
     *
     * @parameter  expression="${validate}" default-value="true"
     * @required
     */
    private boolean validate;

    /**
     * Control flag for verbose processing reports.
     *
     * @parameter  expression="${verbose}" default-value="false"
     * @required
     */
    private boolean verbose;

    /**
     * Control flag for verifying generated/modified classes with BCEL.
     *
     * @parameter  expression="${verify}" default-value="false"
     * @required
     */
    private boolean verify;

    //~ Methods --------------------------------------------------------------------------------------------------------


    /**
     * Determines if running in single- or multi-module mode, collects all bindings \
                and finally runs the binding
     * compiler.
     */
    public void execute() throws MojoExecutionException, MojoFailureException {
        checkConfiguration();

        String mode;
        String[] bindings;
        String[] classpaths;

        if (isMultiModuleMode()) {
            if (isRestrictedMultiModuleMode()) {
                mode = "restricted multi-module";
            } else {
                mode = "multi-module";
            }
            bindings = getMultiModuleBindings();
            classpaths = getMultiModuleClasspaths();
        } else {
            mode = "single-module";
            bindings = getSingleModuleBindings();
            classpaths = getSingleModuleClasspaths();
        }

        if (bindings.length == 0) {
            getLog().info("Not running JiBX binding compiler (" + mode + " mode) - no \
binding files");  } else {
            getLog().info("Running JiBX binding compiler (" + mode + " mode) on " + \
bindings.length  + " binding file(s)");
            compile(classpaths, bindings);
        }
    }

    /**
     * Removes all matching files in the given directory from the given bindingSet.
     */
    private void applyExcludePattern(Set bindingSet, File bindingdir) {
        Set matchedSet = matchPattern(bindingdir, this.excludes);
        bindingSet.removeAll(matchedSet);
    }

    /**
     * Adds all matching files in the given directory to the given bindingSet.
     */
    private void applyIncludePattern(Set bindingSet, File bindingdir) {
        Set matchedSet = matchPattern(bindingdir, this.includes);
        bindingSet.addAll(matchedSet);
    }

    /**
     * Verfifies the plugins configuration and sets default values if needed.
     */
    private void checkConfiguration() {
        if ((this.includes == null) || (this.includes.size() == 0)) {
            this.includes = new ArrayList();
            this.includes.add(DEFAULT_INCLUDES);
        }
        if (this.excludes == null) {
            this.excludes = new ArrayList();
        }
        if ((this.modules != null) && (this.modules.size() > 0)) {
            this.multimodule = true;
        } else {
            this.modules = null;
        }
    }

    /**
     * Creates and runs the JiBX binding compiler.
     */
    private void compile(String[] classpaths, String[] bindings) throws \
MojoExecutionException {  try {
            Compile compiler = new Compile();
            compiler.setLoad(this.load);
            compiler.setSkipValidate(!this.validate);
            compiler.setVerbose(this.verbose);
            compiler.setVerify(this.verify);
            compiler.compile(classpaths, bindings);
        } catch (JiBXException e) {
            Throwable cause = (e.getRootCause() != null) ? e.getRootCause() : e;
            throw new MojoExecutionException(cause.getLocalizedMessage(), cause);
        }
    }

    /**
     * Finds all binding files in the given bindingdir that match one of the \
                wildcards.
     */
    private Set matchPattern(File bindingdir, List wildcards) {
        Set matchedSet = new HashSet();

        for (Iterator iterator = wildcards.iterator(); iterator.hasNext();) {
            String wildcard = (String) iterator.next();
            FilenameFilter filter = new GlobFilenameFilter(wildcard);
            String[] bindings = bindingdir.list(filter);

            for (int i = 0; i < bindings.length; i++) {
                String binding = bindingdir.getAbsolutePath() + File.separator + \
bindings[i];  matchedSet.add(binding);
            }
        }

        return matchedSet;
    }

    /**
     * Normalizes all entries.
     */
    private String[] normalizeClasspaths(Set classpathSet) {
        String[] classpaths = (String[]) classpathSet.toArray(new \
String[classpathSet.size()]);

        for (int i = 0; i < classpaths.length; i++) {
            classpaths[i] = FilenameUtils.normalize(classpaths[i]);
        }

        return classpaths;
    }

    /**
     * Returns all bindings in the given directory according to the configured \
                include/exclude patterns.
     */
    private Set getBindings(String path) throws MojoExecutionException, \
MojoFailureException {  Set bindingSet = new HashSet();

        File bindingdir = new File(path);
        if (!bindingdir.isDirectory()) {
            return bindingSet;
        }

        applyIncludePattern(bindingSet, bindingdir);
        applyExcludePattern(bindingSet, bindingdir);

        return bindingSet;
    }

    /**
     * Returns all binding in the current project and all referenced projects \
                (multi-module mode)
     */
    private String[] getMultiModuleBindings() throws MojoExecutionException, \
MojoFailureException {  Set basedirSet = getProjectBasedirSet(this.project);
        Set bindingSet = new HashSet();

        for (Iterator iter = basedirSet.iterator(); iter.hasNext();) {
            String basedir = (String) iter.next();
            bindingSet.addAll(getBindings(basedir + File.separator + \
this.directory));  }

        return (String[]) bindingSet.toArray(new String[bindingSet.size()]);
    }

    /**
     * Returns the classpath for the binding compiler running in multi-module mode.
     */
    private String[] getMultiModuleClasspaths() throws MojoExecutionException, \
                MojoFailureException {
        Set classpathSet = getProjectCompileClasspathElementsSet(this.project);

        return normalizeClasspaths(classpathSet);
    }

    /**
     * Returns the basedir of the given project.
     */
    private String getProjectBasedir(MavenProject project) {
        return FilenameUtils.normalize(project.getBasedir().getAbsolutePath());
    }

    /**
     * Returns the basedir of the given project and all (or all in "modules" \
                specified) reference projects.
     */
    private Set getProjectBasedirSet(MavenProject project) {
        Set basedirSet = new HashSet();
        basedirSet.add(getProjectBasedir(project));

        Collection projectReferences = project.getProjectReferences().values();
        for (Iterator iter = projectReferences.iterator(); iter.hasNext();) {
            MavenProject projectReference = (MavenProject) iter.next();
            String projectId = projectReference.getGroupId() + ":" + \
projectReference.getArtifactId();

            if ((this.modules == null) || this.modules.contains(projectId)) {
                basedirSet.add(getProjectBasedir(projectReference));
            }
        }

        return basedirSet;
    }

    /**
     * Returns the build output directory of the given project.
     *
     * @throws  MojoExecutionException  if DependencyResolutionRequiredException \
                occurs
     */
    private Set getProjectCompileClasspathElements(MavenProject project) throws \
MojoExecutionException {  try {
            return new HashSet(project.getCompileClasspathElements());
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException(e.getLocalizedMessage(), e);
        }
    }

    /**
     * Returns the build output directory of the given project and all its reference \
                projects.
     *
     * @throws  MojoExecutionException  if DependencyResolutionRequiredException \
                occurs
     */
    private Set getProjectCompileClasspathElementsSet(MavenProject project) throws \
MojoExecutionException {  Set classpathElements = new HashSet();
        classpathElements.addAll(getProjectCompileClasspathElements(project));

        Collection projectReferences = project.getProjectReferences().values();
        for (Iterator iter = projectReferences.iterator(); iter.hasNext();) {
            MavenProject projectReference = (MavenProject) iter.next();
            classpathElements.addAll(getProjectCompileClasspathElements(projectReference));
  }

        return classpathElements;
    }

    /**
     * Returns all bindings in the current project (single-module mode).
     */
    private String[] getSingleModuleBindings() throws MojoExecutionException, \
MojoFailureException {  String basedir = getProjectBasedir(this.project);
        String bindingdir = basedir + File.separator + this.directory;
        Set bindingSet = getBindings(bindingdir);

        return (String[]) bindingSet.toArray(new String[bindingSet.size()]);
    }

    /**
     * Returns the classpath for the binding compiler running in single-module mode.
     */
    private String[] getSingleModuleClasspaths() throws MojoExecutionException, \
                MojoFailureException {
        Set classpathSet = getProjectCompileClasspathElements(this.project);

        return normalizeClasspaths(classpathSet);
    }

    /**
     * Determine if the plugin is running in "multi-module" mode.
     */
    private boolean isMultiModuleMode() {
        return this.multimodule;
    }

    /**
     * Determine if the plugin is running in "restricted multi-module" mode.
     */
    private boolean isRestrictedMultiModuleMode() {
        return isMultiModuleMode() && (this.modules != null);
    }

    /**
     * Determine if the plugin is running in "single-module" mode.
     */
    private boolean isSingleModuleMode() {
        return !isMultiModuleMode();
    }
}

--- NEW FILE: SchemaCodeGenMojo.java ---
/*
 * Copyright (c) 2004-2005, Dennis M. Sosnoski All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, \
                are permitted provided that the
 * following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list \
                of conditions and the following
 * disclaimer. Redistributions in binary form must reproduce the above copyright \
                notice, this list of conditions and the
 * following disclaimer in the documentation and/or other materials provided with the \
                distribution. Neither the name of
 * JiBX nor the names of its contributors may be used to endorse or promote products \
                derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND \
                ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \
                FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR \
                ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \
                PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED \
                AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \
                ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.jibx.maven;

import org.apache.commons.io.FilenameUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.oro.io.GlobFilenameFilter;
import org.jibx.runtime.JiBXException;
import org.jibx.schema.codegen.CodeGen;
import org.jibx.schema.codegen.CodeGenCommandLine;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.HashMap;
import java.util.Map;

/**
 * Generates Java sources from XSD schemas.
 * @author                        <a \
                href="mailto:jerome.bernard@elastic-grid.com">Jerome Bernard</a>
 * @goal                          schema-codegen
 * @phase                         generate-sources
 * @requiresDependencyResolution  compile
 */
public class SchemaCodeGenMojo extends org.apache.maven.plugin.AbstractMojo {
    private static final String DEFAULT_INCLUDES = "*.xsd";

    /**
     * The directory which contains XSD files.
     *
     * @parameter  expression="${directory}" default-value="src/main/config"
     * @required
     */
    private String directory;

    /**
     * Target directory where to generate Java source files.
     *
     * @parameter  expression="${targetDirectory}" \
                default-value="${basedir}/target/generated-sources"
     */
    private String targetDirectory;

    /**
     * Exclude pattern for binding files.
     *
     * @parameter  expression="${excludes}"
     */
    private ArrayList excludes;

    /**
     * Include pattern for schema files.
     *
     * @parameter  expression="${includes}"
     */
    private ArrayList includes;

    /**
     * Control flag for verbose processing reports.
     *
     * @parameter  expression="${verbose}" default-value="false"
     * @required
     */
    private boolean verbose;

    /**
     * Default package for code generated from schema definitions with no namespace.
     *
     * @parameter
     */
    private String defaultPackage = null;

    /**
     * Include pattern for customization files.
     *
     * @parameter  expression="${customizations}"
     */
    private ArrayList customizations;

    /**
     * Extra options to be given for customization via CLI.
     *
     * @parameter
     */
    private Map options;

    /**
     * The maven project.
     *
     * @resolveTransitiveDependencies
     * @parameter                      expression="${project}"
     * @required
     * @readonly
     */
    private MavenProject project;

    /**
     * @component
     */
    private MavenProjectHelper projectHelper;

    public void execute() throws MojoExecutionException, MojoFailureException {
        checkConfiguration();

        List args = new ArrayList();
        for (Iterator iterator = options.entrySet().iterator(); iterator.hasNext();) \
{  Map.Entry entry = (Map.Entry) iterator.next();
            String option = "--" + entry.getKey() + "=" + entry.getValue();
            getLog().debug("Adding option: " + option);
            args.add(option);
        }
        if (verbose)
            args.add("-v");
        if (defaultPackage != null) {
            args.add("-n");
            args.add(defaultPackage);
        }
        args.add("-t");
        args.add(targetDirectory);
        Set schemas = getSchemas(directory);
        for (Iterator iterator = schemas.iterator(); iterator.hasNext();) {
            String schema = (String) iterator.next();
            args.add(new File(schema).toURI().toString());
        }
        if (customizations.size() > 0) {
            args.add("-c");
            for (Iterator iterator = customizations.iterator(); iterator.hasNext();) \
{  String customization = (String) iterator.next();
                args.add(customization);
            }
        }
        try {
            getLog().info("Generating Java sources from schemas into " + \
                targetDirectory + "...");
            CodeGen.main((String[]) args.toArray(new String[args.size()]));
        } catch (JiBXException e) {
            Throwable cause = (e.getRootCause() != null) ? e.getRootCause() : e;
            throw new MojoExecutionException(cause.getLocalizedMessage(), cause);
        } catch (Exception e) {
            Throwable cause = (e.getCause() != null) ? e.getCause() : e;
            throw new MojoExecutionException(cause.getLocalizedMessage(), cause);
        }

        getLog().debug("Adding " + targetDirectory + " as source directory...");
        project.addCompileSourceRoot(targetDirectory);
    }

    /**
     * Verifies the plugins configuration and sets default values if needed.
     */
    private void checkConfiguration() {
        if ((this.includes == null) || (this.includes.size() == 0)) {
            this.includes = new ArrayList();
            this.includes.add(DEFAULT_INCLUDES);
        }
        if (this.excludes == null) {
            this.excludes = new ArrayList();
        }
        if (this.customizations == null) {
            this.customizations = new ArrayList();
        }
        if (this.options == null) {
            this.options = new HashMap();
        }
    }

    /**
     * Returns all bindings in the given directory according to the configured \
                include/exclude patterns.
     */
    private Set getSchemas(String path) throws MojoExecutionException, \
MojoFailureException {  Set bindingSet = new HashSet();

        File bindingdir = new File(path);
        if (!bindingdir.isDirectory()) {
            return bindingSet;
        }

        applyIncludePattern(bindingSet, bindingdir);
        applyExcludePattern(bindingSet, bindingdir);

        return bindingSet;
    }

    /**
     * Removes all matching files in the given directory from the given schemaSet.
     */
    private void applyExcludePattern(Set schemaSet, File schemaDir) {
        Set matchedSet = matchPattern(schemaDir, this.excludes);
        schemaSet.removeAll(matchedSet);
    }

    /**
     * Adds all matching files in the given directory to the given schemaSet.
     */
    private void applyIncludePattern(Set schemaSet, File schemaDir) {
        Set matchedSet = matchPattern(schemaDir, this.includes);
        schemaSet.addAll(matchedSet);
    }

    /**
     * Finds all binding files in the given bindingdir that match one of the \
                wildcards.
     */
    private Set matchPattern(File schemaDir, List wildcards) {
        Set matchedSet = new HashSet();

        for (Iterator iterator = wildcards.iterator(); iterator.hasNext();) {
            String wildcard = (String) iterator.next();
            FilenameFilter filter = new GlobFilenameFilter(wildcard);
            String[] schemas = schemaDir.list(filter);

            for (int i = 0; i < schemas.length; i++) {
                String schema = schemaDir.getAbsolutePath() + File.separator + \
schemas[i];  matchedSet.add(schema);
            }
        }

        return matchedSet;
    }
}
--- JibxMojo.java DELETED ---


------------------------------------------------------------------------------
_______________________________________________
Jibx-cvs mailing list
Jibx-cvs@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/jibx-cvs


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic