| 1 | |
package liquibase.precondition; |
| 2 | |
|
| 3 | |
import liquibase.exception.UnexpectedLiquibaseException; |
| 4 | |
import liquibase.servicelocator.ServiceLocator; |
| 5 | |
|
| 6 | |
import java.util.HashMap; |
| 7 | |
import java.util.Map; |
| 8 | |
|
| 9 | |
public class PreconditionFactory { |
| 10 | |
@SuppressWarnings("unchecked") |
| 11 | |
private final Map<String, Class<? extends Precondition>> preconditions; |
| 12 | |
|
| 13 | |
private static PreconditionFactory instance; |
| 14 | |
|
| 15 | |
@SuppressWarnings("unchecked") |
| 16 | 8 | private PreconditionFactory() { |
| 17 | 8 | preconditions = new HashMap<String, Class<? extends Precondition>>(); |
| 18 | |
Class[] classes; |
| 19 | |
try { |
| 20 | 8 | classes = ServiceLocator.getInstance().findClasses(Precondition.class); |
| 21 | |
|
| 22 | 152 | for (Class<? extends Precondition> clazz : classes) { |
| 23 | 144 | register(clazz); |
| 24 | |
} |
| 25 | 0 | } catch (Exception e) { |
| 26 | 0 | throw new UnexpectedLiquibaseException(e); |
| 27 | 8 | } |
| 28 | 8 | } |
| 29 | |
|
| 30 | |
public static PreconditionFactory getInstance() { |
| 31 | 16 | if (instance == null) { |
| 32 | 1 | instance = new PreconditionFactory(); |
| 33 | |
} |
| 34 | 16 | return instance; |
| 35 | |
} |
| 36 | |
|
| 37 | |
public static void reset() { |
| 38 | 7 | instance = new PreconditionFactory(); |
| 39 | 7 | } |
| 40 | |
|
| 41 | |
public Map<String, Class<? extends Precondition>> getPreconditions() { |
| 42 | 8 | return preconditions; |
| 43 | |
} |
| 44 | |
|
| 45 | |
public void register(Class<? extends Precondition> clazz) { |
| 46 | |
try { |
| 47 | 147 | preconditions.put(clazz.newInstance().getName(), clazz); |
| 48 | 0 | } catch (Exception e) { |
| 49 | 0 | throw new UnexpectedLiquibaseException(e); |
| 50 | 147 | } |
| 51 | 147 | } |
| 52 | |
|
| 53 | |
public void unregister(String name) { |
| 54 | 1 | preconditions.remove(name); |
| 55 | 1 | } |
| 56 | |
|
| 57 | |
|
| 58 | |
|
| 59 | |
|
| 60 | |
public Precondition create(String tagName) { |
| 61 | 5 | Class<?> aClass = preconditions.get(tagName); |
| 62 | 5 | if (aClass == null) { |
| 63 | 0 | throw new UnexpectedLiquibaseException("Unknown tag: " + tagName); |
| 64 | |
} |
| 65 | |
try { |
| 66 | 5 | return (Precondition) aClass.newInstance(); |
| 67 | 0 | } catch (Exception e) { |
| 68 | 0 | throw new RuntimeException(e); |
| 69 | |
} |
| 70 | |
} |
| 71 | |
} |