001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase;
019
020import java.util.Iterator;
021import java.util.ServiceLoader;
022import org.apache.yetus.audience.InterfaceAudience;
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025
026/**
027 * Class that will create many instances of classes provided by the hbase-hadoop{1|2}-compat jars.
028 */
029@InterfaceAudience.Private
030public class CompatibilityFactory {
031
032  private static final Logger LOG = LoggerFactory.getLogger(CompatibilitySingletonFactory.class);
033  public static final String EXCEPTION_START = "Could not create  ";
034  public static final String EXCEPTION_END = " Is the hadoop compatibility jar on the classpath?";
035
036  /**
037   * This is a static only class don't let any instance be created.
038   */
039  protected CompatibilityFactory() {
040  }
041
042  public static synchronized <T> T getInstance(Class<T> klass) {
043    T instance = null;
044    try {
045      ServiceLoader<T> loader = ServiceLoader.load(klass);
046      Iterator<T> it = loader.iterator();
047      instance = it.next();
048      if (it.hasNext()) {
049        StringBuilder msg = new StringBuilder();
050        msg.append("ServiceLoader provided more than one implementation for class: ").append(klass)
051          .append(", using implementation: ").append(instance.getClass())
052          .append(", other implementations: {");
053        while (it.hasNext()) {
054          msg.append(it.next()).append(" ");
055        }
056        msg.append("}");
057        LOG.warn(msg.toString());
058      }
059    } catch (Exception e) {
060      throw new RuntimeException(createExceptionString(klass), e);
061    } catch (Error e) {
062      throw new RuntimeException(createExceptionString(klass), e);
063    }
064
065    // If there was nothing returned and no exception then throw an exception.
066    if (instance == null) {
067      throw new RuntimeException(createExceptionString(klass));
068    }
069    return instance;
070  }
071
072  protected static String createExceptionString(Class klass) {
073    return EXCEPTION_START + klass.toString() + EXCEPTION_END;
074  }
075}