All Downloads are FREE. Search and download functionalities are using the official Maven repository.

liquibase.command.CommandFactory Maven / Gradle / Ivy

There is a newer version: 3.6.2.5.inovus
Show newest version
package liquibase.command;

import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.ServiceLocator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Manages {@link LiquibaseCommand} implementations.
 */
public class CommandFactory  {

    private static CommandFactory instance;

    private List commands;

    private CommandFactory() {
        Class[] classes;

        commands = new ArrayList<>();
        try {
            classes = ServiceLocator.getInstance().findClasses(LiquibaseCommand.class);

            for (Class clazz : classes) {
                register(clazz.getConstructor().newInstance());
            }
        } catch (Exception e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }

    public static synchronized CommandFactory getInstance() {
        if (instance == null) {
            instance = new CommandFactory();
        }
        return instance;
    }

    public static synchronized void reset() {
        instance = new CommandFactory();
    }


    public LiquibaseCommand getCommand(final String commandName) {

        Comparator commandComparator = new Comparator() {
            @Override
            public int compare(LiquibaseCommand o1, LiquibaseCommand o2) {
                return Integer.valueOf(o2.getPriority(commandName)).compareTo(o1.getPriority(commandName));
            }
        };


        List sortedCommands = new ArrayList<>(commands);
        Collections.sort(sortedCommands, commandComparator);
        if (sortedCommands.isEmpty()) {
            throw new UnexpectedLiquibaseException("Could not find command class for "+commandName);
        }
        try {
            LiquibaseCommand command = sortedCommands.iterator().next().getClass().getConstructor().newInstance();

            if (command.getPriority(commandName) <= 0) {
                throw new UnexpectedLiquibaseException("Could not find command class for "+commandName);
            }
            return command;
        } catch (Exception e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }

    public void register(LiquibaseCommand command) {
        commands.add(command);
    }

    public void unregister(LiquibaseCommand command) {
        commands.remove(command);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy