001 package de.deepamehta.core.impl;
002
003 import de.deepamehta.core.osgi.PluginContext;
004 import de.deepamehta.core.service.PluginService;
005
006 import java.lang.reflect.Field;
007
008
009
010 class InjectableService {
011
012 // ---------------------------------------------------------------------------------------------- Instance Variables
013
014 private PluginContext pluginContext;
015 private Class<? extends PluginService> serviceInterface;
016 private Field injectableField;
017
018 private PluginService service;
019
020 // ---------------------------------------------------------------------------------------------------- Constructors
021
022 InjectableService(PluginContext pluginContext, Class<? extends PluginService> serviceInterface,
023 Field injectableField) {
024 this.pluginContext = pluginContext;
025 this.serviceInterface = serviceInterface;
026 this.injectableField = injectableField;
027 }
028
029 // -------------------------------------------------------------------------------------------------- Public Methods
030
031 @Override
032 public String toString() {
033 return serviceInterface.getName();
034 }
035
036 // ----------------------------------------------------------------------------------------- Package Private Methods
037
038 Class<? extends PluginService> getServiceInterface() {
039 return serviceInterface;
040 }
041
042 PluginService getService() {
043 if (!isServiceAvailable()) {
044 throw new RuntimeException("Service " + this + " is not available (consumed by " + pluginContext + ")");
045 }
046 return service;
047 }
048
049 boolean isServiceAvailable() {
050 return service != null;
051 }
052
053 void injectService(PluginService service) {
054 this.service = service;
055 injectValue(service);
056 }
057
058 // ------------------------------------------------------------------------------------------------- Private Methods
059
060 private void injectValue(Object value) {
061 try {
062 injectableField.set(pluginContext, value); // throws IllegalAccessException
063 } catch (Exception e) {
064 throw new RuntimeException("Injecting " + (value == null ? "null for " : "") + this + " failed", e);
065 }
066 }
067 }