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

ratpack.guice.internal.GuiceUtil Maven / Gradle / Ivy

Go to download

Integration with Google Guice for Ratpack applications - https://code.google.com/p/google-guice/

There is a newer version: 2.0.0-rc-1
Show newest version
/*
 * Copyright 2013 the original author or authors.
 *
 * 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 ratpack.guice.internal;

import com.google.common.collect.ImmutableList;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import ratpack.func.Action;

import java.util.Map;

import static ratpack.util.ExceptionUtils.uncheck;

public abstract class GuiceUtil {

  private GuiceUtil() {
  }

  public static  void eachOfType(Injector injector, TypeLiteral type, Action action) {
    Map, Binding> allBindings = injector.getAllBindings();
    for (Map.Entry, Binding> keyBindingEntry : allBindings.entrySet()) {
      Class rawType = keyBindingEntry.getKey().getTypeLiteral().getRawType();
      if (type.getRawType().isAssignableFrom(rawType)) {
        @SuppressWarnings("unchecked")
        T thing = (T) keyBindingEntry.getValue().getProvider().get();
        try {
          action.execute(thing);
        } catch (Exception e) {
          throw uncheck(e);
        }
      }
    }
  }

  public static  ImmutableList ofType(Injector injector, Class type) {
    return ofType(injector, TypeLiteral.get(type));
  }

  // CAREFUL: Does not validate compatibility of generic types.
  public static  ImmutableList ofType(Injector injector, TypeLiteral type) {
    final ImmutableList.Builder listBuilder = ImmutableList.builder();
    eachOfType(injector, type, new Action() {
      public void execute(T thing) {
        listBuilder.add(thing);
      }
    });
    return listBuilder.build();
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy