001/* 
002 * JKNIV, whinstone one contract to access your database.
003 * 
004 * Copyright (C) 2017, the original author or authors.
005 *
006 * This library is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 2.1 of the License.
010 * 
011 * This library is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 * 
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with this library; if not, write to the Free Software Foundation, Inc., 
018 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
019 */
020package net.sf.jkniv.whinstone;
021
022import java.util.Iterator;
023import java.util.ServiceConfigurationError;
024import java.util.ServiceLoader;
025
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029import net.sf.jkniv.sqlegance.RepositoryConfigException;
030import net.sf.jkniv.sqlegance.RepositoryType;
031import net.sf.jkniv.whinstone.spi.RepositoryFactory;
032
033public class RepositoryService
034{
035    private static final Logger LOG = LoggerFactory.getLogger(RepositoryService.class);
036    private static RepositoryService         service;
037    private ServiceLoader<RepositoryFactory> loader;
038    
039    private RepositoryService()
040    {
041        loader = ServiceLoader.load(RepositoryFactory.class);
042    }
043    
044    public static synchronized RepositoryService getInstance()
045    {
046        if (service == null)
047            service = new RepositoryService();
048        return service;
049    }
050
051    public RepositoryFactory lookup(RepositoryType type)
052    {
053        return lookup(type.name());
054    }
055    
056    public RepositoryFactory lookup(String type)
057    {
058        RepositoryFactory factory = null;
059        try
060        {
061            Iterator<RepositoryFactory> factories = loader.iterator();
062            while (factory == null && factories.hasNext())
063            {
064                RepositoryFactory f = factories.next();
065                if (f != null && type.equals(f.getType().name()))
066                    factory = f;
067            }
068        }
069        catch (ServiceConfigurationError serviceError)
070        {
071            LOG.error("Unexpected error", serviceError);
072            factory = null;
073        }
074        if (factory == null)
075            throw new RepositoryConfigException("RepositoryFactory for ["+type+"] type cannot be found, verify if jar file from repository it's set in classpath");
076        
077        return factory;
078    }
079}