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

liquibase.serializer.ChangeLogSerializerFactory Maven / Gradle / Ivy

The newest version!
package liquibase.serializer;

import liquibase.Scope;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.PrioritizedService;
import lombok.Getter;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Getter
public class ChangeLogSerializerFactory {
    private static ChangeLogSerializerFactory instance;

    private final Map> serializers = new ConcurrentHashMap<>();

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

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

        return instance;
    }

    private ChangeLogSerializerFactory() {
        try {
            for (ChangeLogSerializer serializer : Scope.getCurrentScope().getServiceLocator().findInstances(ChangeLogSerializer.class)) {
                register(serializer);
            }
        } catch (Exception e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }

    public List getSerializers(String fileNameOrExtension) {
        fileNameOrExtension = fileNameOrExtension.replaceAll(".*\\.", ""); //just need the extension
        List changeLogSerializers = serializers.get(fileNameOrExtension);
        if (changeLogSerializers == null) {
            return Collections.emptyList();
        }
        return changeLogSerializers;
    }

    public ChangeLogSerializer getSerializer(String fileNameOrExtension) {
        List changeLogSerializers = getSerializers(fileNameOrExtension);
        if (changeLogSerializers.isEmpty()) {
            throw new RuntimeException("No serializers associated with the filename or extension '" + fileNameOrExtension + "'");
        }
        return changeLogSerializers.get(0);
    }

    public void register(ChangeLogSerializer changeLogSerializer) {
        for (String extension : changeLogSerializer.getValidFileExtensions()) {
            List changeLogSerializers = serializers.computeIfAbsent(extension, k -> new ArrayList<>());
            changeLogSerializers.add(changeLogSerializer);
            changeLogSerializers.sort(PrioritizedService.COMPARATOR);
        }
    }

    public void unregister(ChangeLogSerializer changeLogSerializer) {
        for (Iterator>> entryIterator = serializers.entrySet().iterator(); entryIterator.hasNext();) {
            Map.Entry> entry = entryIterator.next();
            List changeLogSerializers = entry.getValue();
            changeLogSerializers.removeIf(value -> value.equals(changeLogSerializer));
            if (changeLogSerializers.isEmpty()) {
                entryIterator.remove();
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy