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

com.orientechnologies.common.factory.OConfigurableStatefulFactory Maven / Gradle / Ivy

/*
 *
 *  Copyright 2010-2014 Orient Technologies LTD (info(at)orientechnologies.com)
 *  
 *  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 com.orientechnologies.common.factory;

import com.orientechnologies.common.exception.OException;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * Configurable stateful factory. New instances are created when newInstance() is called, invoking its default empty constructor.
 * 
 * @param 
 *          Factory key
 * @param 
 *          Instance type
 */
public class OConfigurableStatefulFactory {
  protected final Map> registry = new LinkedHashMap>();
  protected Class               defaultClass;

  public Class get(final K iKey) {
    return registry.get(iKey);
  }

  public V newInstance(final K iKey) {
    if (iKey == null && defaultClass == null)
      throw new IllegalArgumentException("Cannot create implementation for type null");

    final Class cls = registry.get(iKey);
    if (cls != null) {
      try {
        return cls.newInstance();
      } catch (Exception e) {
        throw new OException(String.format("Error on creating new instance of class '%s' registered in factory with key '%s'", cls,
            iKey), e);
      }
    }

    return newInstanceOfDefaultClass();
  }

  public V newInstanceOfDefaultClass() {
    if (defaultClass != null) {
      try {
        return defaultClass.newInstance();
      } catch (Exception e) {
        throw new OException(String.format("Error on creating new instance of default class '%s'", defaultClass), e);
      }
    }
    return null;
  }
  
  public Set getKeys()
  {
	  return registry.keySet();
  }

  public OConfigurableStatefulFactory register(final K iKey, final Class iValue) {
    registry.put(iKey, iValue);
    return this;
  }

  public OConfigurableStatefulFactory unregister(final K iKey) {
    registry.remove(iKey);
    return this;
  }

  public OConfigurableStatefulFactory unregisterAll() {
    registry.clear();
    return this;
  }

  public Class getDefaultClass() {
    return defaultClass;
  }

  public > OConfigurableStatefulFactory setDefaultClass(final C defaultClass) {
    this.defaultClass = defaultClass;
    return this;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy