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

com.alphasystem.docbook.builder.BuilderFactory Maven / Gradle / Ivy

The newest version!
package com.alphasystem.docbook.builder;

import com.alphasystem.commons.SystemException;
import com.alphasystem.commons.util.AppUtil;
import com.alphasystem.docbook.util.ConfigurationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class BuilderFactory {

    private static final BuilderFactory instance;

    static {
        instance = new BuilderFactory();
    }

    public static BuilderFactory getInstance() {
        return instance;
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final ConfigurationUtils configurationUtils = ConfigurationUtils.getInstance();

    private final Map> buildersClassMap = new HashMap<>();

    /*
     * Do not let any one instantiate this class
     */
    private BuilderFactory() {
        loadBuilders();
    }

    private Builder getBuilder(Object o, Builder parent) {
        if (Objects.isNull(o)) {
            throw new NullPointerException("Object cannot be null.");
        }
        final var name = o.getClass().getName();
        final var builderClass = buildersClassMap.get(name);
        try {
            return (Builder) AppUtil.initObject(builderClass, new Class[]{o.getClass(), Builder.class}, new Object[]{o, parent});
        } catch (SystemException e) {
            logger.warn("No builder found for: {}", name);
            throw new RuntimeException(e);
        }
    }

    private void loadBuilders() {
        final var config = configurationUtils.getConfig("docbook-docx.builders");
        config.entrySet().forEach(entry -> {
            final var key = entry.getKey();
            final var builderClassName = entry.getValue().unwrapped().toString();
            logger.info("Loading builder \"{}\" for \"{}\".", builderClassName, key);
            try {
                buildersClassMap.put(key, Class.forName(builderClassName));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public List process(Object o, Builder parent) {
        return getBuilder(o, parent).process();
    }
}