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