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

com.dangdang.config.service.file.protocol.Protocols Maven / Gradle / Ivy

package com.dangdang.config.service.file.protocol;

import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Protocol factory
 *
 * @author Yuxuan Wang
 */
public final class Protocols {

    private Map> protocols;

    private static Protocols INSTANCE = new Protocols();

    private static final String REGISTER_FILE = "META-INF/toolkit/com.dangdang.config.service.file.protocol.Protocol";

    private Protocols() {
        try {
            Properties props = new Properties();

            // Load register file contents
            Enumeration registerFiles = this.getClass().getClassLoader().getResources(REGISTER_FILE);
            URL registerFile = null;
            while (registerFiles.hasMoreElements()) {
                registerFile = registerFiles.nextElement();
                try (InputStream in = registerFile.openStream()) {
                    props.load(in);
                }
            }

            // Initialize protocol beans
            protocols = new HashMap<>();
            for (Map.Entry entry : props.entrySet()) {
                final String protocolName = ((String) entry.getKey()).toLowerCase();
                @SuppressWarnings("unchecked") final Class protocolBeanClazz = (Class) Class.forName((String) entry.getValue());
                protocols.put(protocolName, protocolBeanClazz);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Protocols getInstance() {
        return INSTANCE;
    }

    public Class get(String protocolName) {
        final Class protocolClass = protocols.get(protocolName);
        if (protocolClass == null) {
            throw new IllegalArgumentException("Procotol with name " + protocolName + " not registered.");
        }
        return protocolClass;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy