/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

package org.apache.kylin.metadata.realization;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.util.ClassUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 */
public class RealizationRegistry {

    private static final Logger logger = LoggerFactory.getLogger(RealizationRegistry.class);
    private static final ConcurrentHashMap<KylinConfig, RealizationRegistry> CACHE = new ConcurrentHashMap<KylinConfig, RealizationRegistry>();

    public static RealizationRegistry getInstance(KylinConfig config) {
        RealizationRegistry r = CACHE.get(config);
        if (r != null) {
            return r;
        }

        synchronized (RealizationRegistry.class) {
            r = CACHE.get(config);
            if (r != null) {
                return r;
            }
            try {
                r = new RealizationRegistry(config);
                CACHE.put(config, r);
                if (CACHE.size() > 1) {
                    logger.warn("More than one singleton exist");
                }
                return r;
            } catch (IOException e) {
                throw new IllegalStateException("Failed to init CubeManager from " + config, e);
            }
        }
    }

    public static void clearCache() {
        CACHE.clear();
    }

    // ============================================================================

    private Map<RealizationType, IRealizationProvider> providers;
    private KylinConfig config;

    private RealizationRegistry(KylinConfig config) throws IOException {
        logger.info("Initializing RealizationRegistry with metadata url " + config);
        this.config = config;
        init();
    }

    private void init() {
        providers = Maps.newConcurrentMap();

        // use reflection to load providers
        String[] providerNames = config.getRealizationProviders();
        List<Throwable> es = Lists.newArrayList();
        for (String clsName : providerNames) {
            try {
                Class<? extends IRealizationProvider> cls = ClassUtil.forName(clsName, IRealizationProvider.class);
                IRealizationProvider p = (IRealizationProvider) cls.getMethod("getInstance", KylinConfig.class).invoke(null, config);
                providers.put(p.getRealizationType(), p);

            } catch (Exception | NoClassDefFoundError e) {
                es.add(e);
            }

            if (es.size() > 0) {
                for (Throwable exceptionOrError : es) {
                    logger.error("Create new store instance failed ", exceptionOrError);
                }
                throw new IllegalArgumentException("Failed to find metadata store by url: " + config.getMetadataUrl());
            }
        }

        logger.info("RealizationRegistry is " + providers);
    }

    public Set<RealizationType> getRealizationTypes() {
        return Collections.unmodifiableSet(providers.keySet());
    }

    public IRealization getRealization(RealizationType type, String name) {
        IRealizationProvider p = providers.get(type);
        if (p == null) {
            logger.warn("No provider for realization type " + type);
            return null;
        }

        try {
            return p.getRealization(name);
        } catch (Exception ex) {
            // exception is possible if e.g. cube metadata is wrong
            logger.warn("Failed to load realization " + type + ":" + name, ex);
            return null;
        }
    }

}

@@ -911,31 +911,8 @@
 ns;%0A
-import java.util.List;%0A
 impo
@@ -1152,48 +1152,8 @@
 y;%0A%0A
-import com.google.common.collect.Lists;%0A
 impo
@@ -2881,59 +2881,8 @@
 ();%0A
-        List%3CThrowable%3E es = Lists.newArrayList();%0A
     
@@ -3330,31 +3330,94 @@
     
-es.add(e);%0A    
+if (e instanceof ClassNotFoundException %7C%7C e instanceof NoClassDefFoundError)%0A
         
 %7D%0A%0A 
@@ -3404,35 +3404,32 @@
 dError)%0A        
-%7D%0A%0A
             if (
@@ -3428,171 +3428,163 @@
     
-if (es.size() %3E 0) %7B%0A                for (Throwable exceptionOrError : es) %7B%0A                    logger.error(%22Create new store instance failed %22, exceptionOrError
+logger.warn(%22Failed to create realization provider %22 + e);%0A                else%0A                    logger.error(%22Failed to create realization provider%22, e
 );%0A 
@@ -3589,35 +3589,71 @@
 %0A           
+ %7D%0A
      
-%7D%0A 
    
+%7D%0A%0A        if (providers.isEmpty())%0A
             
@@ -3707,22 +3707,28 @@
 ind 
-metadata store
+realization provider
  by 
@@ -3765,32 +3765,8 @@
 ());
-%0A            %7D%0A        %7D
 %0A%0A  

fix RealizationRegistry related tests