use of org.lanternpowered.server.inject.ServiceProvider in project LanternServer by LanternPowered.
the class ServiceObjectProvider method get.
@SuppressWarnings("unchecked")
@Override
public Service get() {
// noinspection unchecked
final Class serviceType = this.point.getType().resolveType(VALUE_VARIABLE).getRawType();
if (serviceType == null) {
throw new IllegalStateException("Missing service type.");
}
final ServiceProvider serviceProvider = this.point.getAnnotation(ServiceProvider.class);
final Service service = () -> {
final Optional<ProviderRegistration> optRegistration = this.serviceManager.getRegistration(serviceType);
return optRegistration.orElseThrow(() -> new IllegalStateException("Cannot find the service: " + serviceType.getName()));
};
final Optional<ProviderRegistration> optRegistration = this.serviceManager.getRegistration(serviceType);
if (serviceProvider == null || (!serviceProvider.override() && optRegistration.isPresent())) {
return service;
}
final Class<?> provider = serviceProvider.value();
final Object serviceInstance;
if (Provider.class.isAssignableFrom(provider)) {
serviceInstance = ((Provider) this.injector.getInstance(provider)).get();
} else if (Supplier.class.isAssignableFrom(provider)) {
serviceInstance = ((Supplier) this.injector.getInstance(provider)).get();
} else if (serviceType.isAssignableFrom(provider)) {
serviceInstance = this.injector.getInstance(provider);
} else {
throw new IllegalStateException(String.format("Invalid service instance provider %s for %s", serviceType.getName(), provider.getName()));
}
if (!serviceType.isInstance(serviceInstance)) {
throw new IllegalStateException(String.format("The provided service instance %s doesn't implement the service %s", serviceInstance.getClass().getName(), serviceType.getName()));
}
this.serviceManager.setProvider(this.pluginContainer, serviceType, serviceInstance);
return service;
}
Aggregations