ratpack.guice.internal.GuiceUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ratpack-guice Show documentation
Show all versions of ratpack-guice Show documentation
Integration with Google Guice for Ratpack applications - https://code.google.com/p/google-guice/
/*
* 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.common.reflect.TypeToken;
import com.google.inject.*;
import ratpack.func.Action;
import ratpack.func.Function;
import ratpack.util.Types;
import java.util.Map;
import static ratpack.util.Exceptions.uncheck;
public abstract class GuiceUtil {
private GuiceUtil() {
}
public static void search(Injector injector, TypeToken type, Function, Boolean> transformer) {
Map, Binding>> bindings = injector.getBindings();
for (Map.Entry, Binding>> keyBindingEntry : bindings.entrySet()) {
final Key> key = keyBindingEntry.getKey();
final Binding> binding = keyBindingEntry.getValue();
TypeLiteral> bindingType = key.getTypeLiteral();
if (type.isAssignableFrom(toTypeToken(bindingType))) {
@SuppressWarnings("unchecked") Provider extends T> provider = (Provider extends T>) binding.getProvider();
try {
if (!transformer.apply(provider)) {
return;
}
} catch (Exception e) {
throw uncheck(e);
}
}
}
Injector parent = injector.getParent();
if (parent != null) {
search(parent, type, transformer);
}
}
public static void eachOfType(Injector injector, TypeToken type, final Action super T> action) {
search(injector, type, from -> {
action.execute(from.get());
return true;
});
}
public static void eachProviderOfType(Injector injector, TypeToken type, final Action super Provider extends T>> action) {
search(injector, type, from -> {
action.execute(from);
return true;
});
}
public static ImmutableList> allProvidersOfType(Injector injector, TypeToken type) {
final ImmutableList.Builder> listBuilder = ImmutableList.builder();
eachProviderOfType(injector, type, listBuilder::add);
return listBuilder.build();
}
public static TypeToken toTypeToken(TypeLiteral type) {
return Types.cast(TypeToken.of(type.getType()));
}
public static TypeLiteral toTypeLiteral(TypeToken type) {
return Types.cast(TypeLiteral.get(type.getType()));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy