Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.liquibase.maven.plugins;
  
  import java.util.*;
  
  import liquibase.*;
A base class for providing Liquibase liquibase.Liquibase functionality.

Author(s):
Peter Murray Test dependency is used because when you run a goal outside the build phases you want to have the same dependencies that it would had if it was ran inside test phase
RequiresDependencyResolution:
test
 
 public abstract class AbstractLiquibaseMojo extends AbstractMojo {

    
Suffix for fields that are representing a default value for a another field.
 
     private static final String DEFAULT_FIELD_SUFFIX = "Default";

    
The fully qualified name of the driver class to use to connect to the database.

Parameter:
expression="${liquibase.driver}"
 
     protected String driver;

    
The Database URL to connect to for executing Liquibase.

Parameter:
expression="${liquibase.url}"
 
     protected String url;

    
The Maven Wagon manager to use when obtaining server authentication details.

Component:
role="org.apache.maven.artifact.manager.WagonManager"
Required:
Readonly:
 
     protected WagonManager wagonManager;
    
The server id in settings.xml to use when authenticating with.

Parameter:
expression="${liquibase.server}"
 
     private String server;

    
The database username to use to connect to the specified database.

Parameter:
expression="${liquibase.username}"
 
     protected String username;

    
The database password to use to connect to the specified database.

Parameter:
expression="${liquibase.password}"
 
     protected String password;

    
Use an empty string as the password for the database connection. This should not be used along side the password setting.

Deprecated:
Use an empty or null value for the password instead.
Parameter:
expression="${liquibase.emptyPassword}" default-value="false"
 
     protected boolean emptyPassword;

    
The default schema name to use the for database connection.

Parameter:
expression="${liquibase.defaultSchemaName}"
 
     protected String defaultSchemaName;

    
The class to use as the database object.

Parameter:
expression="${liquibase.databaseClass}"
    protected String databaseClass;

    
Controls the prompting of users as to whether or not they really want to run the changes on a database that is not local to the machine that the user is current executing the plugin on.

Parameter:
expression="${liquibase.promptOnNonLocalDatabase}" default-value="true"
    protected boolean promptOnNonLocalDatabase;
    private boolean promptOnNonLocalDatabaseDefault = true;

    
Allows for the maven project artifact to be included in the class loader for obtaining the Liquibase property and DatabaseChangeLog files.

Parameter:
expression="${liquibase.includeArtifact}" default-value="true"
    protected boolean includeArtifact;
    private boolean includeArtifactDefault = true;

    
Allows for the maven test output directory to be included in the class loader for obtaining the Liquibase property and DatabaseChangeLog files.

Parameter:
expression="${liquibase.includeTestOutputDirectory}" default-value="true"
    protected boolean includeTestOutputDirectory;
    private boolean includeTestOutputDirectoryDefault = true;

    
Controls the verbosity of the output from invoking the plugin.

Parameter:
expression="${liquibase.verbose}" default-value="false"
Description:
Controls the verbosity of the plugin when executing
    protected boolean verbose;
    private boolean verboseDefault = false;

    
Controls the level of logging from Liquibase when executing. The value can be "all", "finest", "finer", "fine", "info", "warning", "severe" or "off". The value is case insensitive.

Parameter:
expression="${liquibase.logging}" default-value="INFO"
Description:
Controls the verbosity of the plugin when executing
    protected String logging;
    private String loggingDefault = "INFO";

    
The Liquibase properties file used to configure the Liquibase liquibase.Liquibase.

Parameter:
expression="${liquibase.propertyFile}"
    protected String propertyFile;

    
Flag allowing for the Liquibase properties file to override any settings provided in the Maven plugin configuration. By default if a property is explicity specified it is not overridden if it also appears in the properties file.

Parameter:
expression="${liquibase.propertyFileWillOverride}" default-value="false"
    protected boolean propertyFileWillOverride;

    
Flag for forcing the checksums to be cleared from teh DatabaseChangeLog table.

Parameter:
expression="${liquibase.clearCheckSums}" default-value="false"
    protected boolean clearCheckSums;
    private boolean clearCheckSumsDefault = false;

    
List of system properties to pass to the database.

Parameter:
                                                                                                                                                                          
    protected Properties systemProperties;

    
The Maven project that plugin is running under.

Parameter:
expression="${project}"
Required:
Readonly:
    protected MavenProject project;

    
The liquibase.Liquibase object used modify the database.
    private Liquibase liquibase;

    
Array to put a expression variable to maven plugin.

Parameter:
    private Properties expressionVars;

    
Set this to 'true' to skip running liquibase. Its use is NOT RECOMMENDED, but quite convenient on occasion.

Parameter:
expression="${liquibase.should.run}"
    protected boolean skip;

    
Array to put a expression variable to maven plugin.

Parameter:
    private Map expressionVariables;
    public void execute() throws MojoExecutionExceptionMojoFailureException {
        if ( info != null ) {
             = info.getUserName();
             = info.getPassword();
        }
        String shouldRunProperty = System.getProperty(.);
        if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) {
            getLog().warn("Liquibase did not run because '" + .
                    + "' system property was set to false");
            return;
        }
        if () {
            getLog().warn("Liquibase skipped due to maven configuration");
            return;
        }
        processSystemProperties();
        ClassLoader artifactClassLoader = getMavenArtifactClassLoader();
        configureFieldsAndValues(getFileOpener(artifactClassLoader));
        try {
            LogFactory.setLoggingLevel();
        }
        catch (IllegalArgumentException e) {
            throw new MojoExecutionException("Failed to set logging level: " + e.getMessage(),
                    e);
        }
        // Displays the settings for the Mojo depending of verbosity mode.
        displayMojoSettings();
        // Check that all the parameters that must be specified have been by the user.
        Database database = null;
        try {
            String dbPassword =  ||  == null ? "" : ;
            database = CommandLineUtils.createDatabaseObject(artifactClassLoader,
                    ,
                    ,
                    dbPassword,
                    ,
                    ,
                    );
             = createLiquibase(getFileOpener(artifactClassLoader), database);
            getLog().debug("expressionVars = " + String.valueOf());
            if ( != null) {
                for (Map.Entry<ObjectObjectvar : .entrySet()) {
                    this..setChangeLogParameter(var.getKey().toString(), var.getValue());
                }
            }
            getLog().debug("expressionVariables = " + String.valueOf());
            if ( != null) {
                for (Map.Entry var : (Set<Map.Entry>) .entrySet()) {
                    if (var.getValue() != null) {
                        this..setChangeLogParameter(var.getKey().toString(), var.getValue());
                    }
                }
            }
            if () {
                getLog().info("Clearing the Liquibase Checksums on the database");
                .clearCheckSums();
            }
            getLog().info("Executing on Database: " + );
            if (isPromptOnNonLocalDatabase()) {
                if (!.isSafeToRunMigration()) {
                    if (UIFactory.getInstance().getFacade().promptForNonLocalDatabase(.getDatabase())) {
                        throw new LiquibaseException("User decided not to run against non-local database");
                    }
                }
            }
            performLiquibaseTask();
        }
        catch (LiquibaseException e) {
            cleanup(database);
            throw new MojoExecutionException("Error setting up or running Liquibase: " + e.getMessage(), e);
        }
        cleanup(database);
        getLog().info("");
    }
    protected Liquibase getLiquibase() {
        return ;
    }
    protected abstract void performLiquibaseTask(Liquibase liquibase)
            throws LiquibaseException;
    protected boolean isPromptOnNonLocalDatabase() {
        return ;
    }
    private void displayMojoSettings() {
        if () {
            getLog().info("Settings----------------------------");
            printSettings("    ");
            getLog().info(.);
        }
    }
        try {
            return new Liquibase(""fodb);
        } catch (LiquibaseException ex) {
            throw new MojoExecutionException("Error creating liquibase: "+ex.getMessage(),ex);
        }
    }
            throws MojoExecutionExceptionMojoFailureException {
        // Load the properties file if there is one, but only for values that the user has not
        // already specified.
        if ( != null) {
            getLog().info("Parsing Liquibase Properties File");
            getLog().info("  File: " + );
            try {
                InputStream is = fo.getResourceAsStream();
                if (is == null) {
                    throw new MojoFailureException("Failed to resolve the properties file.");
                }
                parsePropertiesFile(is);
                getLog().info(.);
            }
            catch (IOException e) {
                throw new MojoExecutionException("Failed to resolve properties file"e);
            }
        }
    }
        try {
            return MavenUtils.getArtifactClassloader(,
                    ,
                    ,
                    getClass(),
                    getLog(),
                    );
        }
        catch (MalformedURLException e) {
            throw new MojoExecutionException("Failed to create artifact classloader"e);
        }
    }
    protected ResourceAccessor getFileOpener(ClassLoader cl) {
        ResourceAccessor mFO = new MavenResourceAccessor(cl);
        return new CompositeResourceAccessor(mFOfsFO);
    }

    
Performs some validation after the properties file has been loaded checking that all properties required have been specified.

Throws:
org.apache.maven.plugin.MojoFailureException If any property that is required has not been specified.
    protected void checkRequiredParametersAreSpecified() throws MojoFailureException {
        if ( == null) {
            throw new MojoFailureException("The driver has not been specified either as a "
                    + "parameter or in a properties file.");
        } else if ( == null) {
            throw new MojoFailureException("The database URL has not been specified either as "
                    + "a parameter or in a properties file.");
        }
        if ( != null && ) {
            throw new MojoFailureException("A password cannot be present and the empty "
                    + "password property both be specified.");
        }
    }

    
Prints the settings that have been set of defaulted for the plugin. These will only be shown in verbose mode.

Parameters:
indent The indent string to use when printing the settings.
    protected void printSettings(String indent) {
        if (indent == null) {
            indent = "";
        }
        getLog().info(indent + "driver: " + );
        getLog().info(indent + "url: " + );
        getLog().info(indent + "username: " + );
        getLog().info(indent + "password: " + );
        getLog().info(indent + "use empty password: " + );
        getLog().info(indent + "properties file: " + );
        getLog().info(indent + "properties file will override? " + );
        getLog().info(indent + "prompt on non-local database? " + );
        getLog().info(indent + "clear checksums? " + );
    }
    protected void cleanup(Database db) {
        // Release any locks that we may have on the database.
        if (getLiquibase() != null) {
            try {
                getLiquibase().forceReleaseLocks();
            }
            catch (LiquibaseException e) {
                getLog().error(e.getMessage(), e);
            }
        }
        // Clean up the connection
        if (db != null) {
            try {
                db.rollback();
                db.close();
            }
            catch (DatabaseException e) {
                getLog().error("Failed to close open connection to database."e);
            }
        }
    }

    
Parses a properties file and sets the assocaited fields in the plugin.

Parameters:
propertiesInputStream The input stream which is the Liquibase properties that needs to be parsed.
Throws:
org.apache.maven.plugin.MojoExecutionException If there is a problem parsing the file.
    protected void parsePropertiesFile(InputStream propertiesInputStream)
            throws MojoExecutionException {
        if (propertiesInputStream == null) {
            throw new MojoExecutionException("Properties file InputStream is null.");
        }
        Properties props = new Properties();
        try {
            props.load(propertiesInputStream);
        }
        catch (IOException e) {
            throw new MojoExecutionException("Could not load the properties Liquibase file"e);
        }
        for (Iterator it = props.keySet().iterator(); it.hasNext();) {
            String key = null;
            try {
                key = (Stringit.next();
                Field field = MavenUtils.getDeclaredField(this.getClass(), key);
                if () {
                    getLog().debug("  properties file setting value: " + field.getName());
                    setFieldValue(fieldprops.get(key).toString());
                } else {
                    if (!isCurrentFieldValueSpecified(field)) {
                        getLog().debug("  properties file setting value: " + field.getName());
                        setFieldValue(fieldprops.get(key).toString());
                    }
                }
            }
            catch (Exception e) {
                getLog().info("  '" + key + "' in properties file is not being used by this "
                        + "task.");
            }
        }
    }

    
This method will check to see if the user has specified a value different to that of the default value. This is not an ideal solution, but should cover most situations in the use of the plugin.

Parameters:
f The Field to check if a user has specified a value for.
Returns:
true if the user has specified a value.
    private boolean isCurrentFieldValueSpecified(Field fthrows IllegalAccessException {
        Object currentValue = f.get(this);
        if (currentValue == null) {
            return false;
        }
        Object defaultValue = getDefaultValue(f);
        if (defaultValue == null) {
            return currentValue != null;
        } else {
            // There is a default value, check to see if the user has selected something other
            // than the default
            return !defaultValue.equals(f.get(this));
        }
    }
    private Object getDefaultValue(Field fieldthrows IllegalAccessException {
        List<FieldallFields = new ArrayList<Field>();
        allFields.addAll(Arrays.asList(getClass().getDeclaredFields()));
        allFields.addAll(Arrays.asList(AbstractLiquibaseMojo.class.getDeclaredFields()));
        for (Field f : allFields) {
            if (f.getName().equals(field.getName() + )) {
                f.setAccessible(true);
                return f.get(this);
            }
        }
        return null;
    }
    private void setFieldValue(Field fieldString valuethrows IllegalAccessException {
        if (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class)) {
            field.set(this, Boolean.valueOf(value));
        } else {
            field.set(thisvalue);
        }
    }
    
    @SuppressWarnings("unchecked")
    private void processSystemProperties() {
        if ( == null)
        {
             = new Properties();
        }
        // Add all system properties configured by the user
        Iterator iter = .keySet().iterator();
        while (iter.hasNext()) {
            String key = (Stringiter.next();
            String value = .getProperty(key);
            System.setProperty(keyvalue);
        }
    }
New to GrepCode? Check out our FAQ X