|
| 1 | +package com.fasterxml.jackson.module.osgi; |
| 2 | + |
| 3 | +import org.osgi.framework.BundleContext; |
| 4 | +import org.osgi.framework.InvalidSyntaxException; |
| 5 | +import org.osgi.framework.ServiceReference; |
| 6 | + |
| 7 | +import com.fasterxml.jackson.databind.BeanProperty; |
| 8 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 9 | +import com.fasterxml.jackson.databind.InjectableValues; |
| 10 | + |
| 11 | +/** |
| 12 | + * Injects OSGI services in deserialized objects |
| 13 | + * <br/> |
| 14 | + * Use the {@link com.fasterxml.jackson.annotation.JacksonInject} in the constructor parameters or the class members ask for injecting a matching OSGI services. |
| 15 | + * Use the {@link com.fasterxml.jackson.annotation.JacksonInject#value()} to specify an OSGI filter to select more accurately the OSGI services. |
| 16 | + * Null is injected when no matching OSGI service is registered. |
| 17 | + */ |
| 18 | +public class OsgiInjectableValues extends InjectableValues |
| 19 | +{ |
| 20 | + private final BundleContext bundleContext; |
| 21 | + |
| 22 | + public OsgiInjectableValues(BundleContext bundleContext) |
| 23 | + { |
| 24 | + this.bundleContext = bundleContext; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public Object findInjectableValue(Object valueId, |
| 29 | + DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) |
| 30 | + { |
| 31 | + return findService(serviceType(forProperty), serviceFilter(valueId)); |
| 32 | + } |
| 33 | + |
| 34 | + private Object findService(String type, String filter) |
| 35 | + { |
| 36 | + try |
| 37 | + { |
| 38 | + ServiceReference<?>[] srs = bundleContext.getServiceReferences(type, filter); |
| 39 | + if (srs == null || srs.length == 0) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + return bundleContext.getService(srs[0]); |
| 43 | + } catch (InvalidSyntaxException e) { |
| 44 | + // this will never happen as the filter was checked before |
| 45 | + throw new RuntimeException(e); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + private static String serviceType(BeanProperty forProperty) |
| 50 | + { |
| 51 | + return forProperty.getType().toCanonical(); |
| 52 | + } |
| 53 | + |
| 54 | + private String serviceFilter(Object valueId) |
| 55 | + { |
| 56 | + try { |
| 57 | + return bundleContext.createFilter(valueId.toString()).toString(); |
| 58 | + } catch (InvalidSyntaxException e) { |
| 59 | + return null; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments