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

com.github.tomakehurst.wiremock.extension.ExtensionLoader Maven / Gradle / Ivy

There is a newer version: 3.0.1
Show newest version
/*
 * Copyright (C) 2014-2021 Thomas Akehurst
 *
 * 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.github.tomakehurst.wiremock.extension;

import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;
import static com.google.common.collect.FluentIterable.from;
import static java.util.Arrays.asList;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import java.util.Map;

public class ExtensionLoader {

  @SuppressWarnings("unchecked")
  public static  Map loadExtension(String... classNames) {
    return (Map)
        asMap(from(asList(classNames)).transform(toClasses()).transform(toExtensions()));
  }

  public static Map load(String... classNames) {
    return loadExtension(classNames);
  }

  public static Map asMap(Iterable extensions) {
    return Maps.uniqueIndex(
        extensions,
        new Function() {
          public String apply(Extension extension) {
            return extension.getName();
          }
        });
  }

  public static Map load(Class... classes) {
    return asMap(from(asList(classes)).transform(toExtensions()));
  }

  private static Function, Extension> toExtensions() {
    return new Function, Extension>() {
      @SuppressWarnings("unchecked")
      public Extension apply(Class extensionClass) {
        try {
          return extensionClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
          return throwUnchecked(e, Extension.class);
        }
      }
    };
  }

  private static Function> toClasses() {
    return new Function>() {
      @SuppressWarnings("unchecked")
      public Class apply(String className) {
        try {
          return (Class) Class.forName(className);
        } catch (ClassNotFoundException e) {
          return throwUnchecked(e, Class.class);
        }
      }
    };
  }

  public static  Predicate> valueAssignableFrom(
      final Class extensionType) {
    return new Predicate>() {
      public boolean apply(Map.Entry input) {
        return extensionType.isAssignableFrom(input.getValue().getClass());
      }
    };
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy