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

org.ehcache.internal.classes.ClassInstanceProvider Maven / Gradle / Ivy

There is a newer version: 3.10.8
Show newest version
/*
 * Copyright Terracotta, Inc.
 *
 * Licensed 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.ehcache.internal.classes;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.spi.service.ServiceConfiguration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Alex Snaps
 */
public class ClassInstanceProvider {

  private final Map> preconfiguredLoaders = new HashMap>();

  private final Class> factoryConfig;
  private final Class> cacheLevelConfig;

  protected ClassInstanceProvider(final Class> factoryConfig, final Class> cacheLevelConfig) {
    this.factoryConfig = factoryConfig;
    this.cacheLevelConfig = cacheLevelConfig;
  }

  protected Class getPreconfigured(String alias) {
    return preconfiguredLoaders.get(alias);
  }

  protected T newInstance(final String alias, final CacheConfiguration cacheConfiguration) {
    Class clazz = null;
    for (ServiceConfiguration serviceConfiguration : cacheConfiguration.getServiceConfigurations()) {
      if(cacheLevelConfig.isAssignableFrom(serviceConfiguration.getClass())) {
        // TODO: What if we have multiple of the same type?
        clazz = cacheLevelConfig.cast(serviceConfiguration).getClazz();
      }
    }
    if(clazz == null) {
      clazz = getPreconfigured(alias);
    }
    try {
      return clazz != null ? clazz.newInstance() : null;
    } catch (InstantiationException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }



  public void start(final ServiceConfiguration config) {
    if(config != null && factoryConfig.isAssignableFrom(config.getClass())) {
      final ClassInstanceProviderFactoryConfig instanceProviderFactoryConfig = factoryConfig.cast(config);
      preconfiguredLoaders.putAll(instanceProviderFactoryConfig.getDefaults());
    }
  }

  public void stop() {
    preconfiguredLoaders.clear();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy