ServiceInvoker.java 1.69 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  org.osgi.framework.BundleContext
 *  org.osgi.framework.ServiceReference
 */
package com.adobe.aemfd.watchfolder.service;

import com.adobe.aemfd.watchfolder.service.ServiceCallback;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
public class ServiceInvoker<T, S> {
    public S lookupAndInvoke(BundleContext bundleContext, Class<T> svcClass, String filter, ServiceCallback<T, S> callback) throws Exception {
        ServiceReference[] refs = bundleContext.getServiceReferences(svcClass.getName(), filter);
        if (refs == null || refs.length == 0) {
            throw new Exception("No service of type " + svcClass + " found with filter " + filter);
        }
        if (refs.length == 1) {
            ServiceReference theRef = refs[0];
            Object cp = bundleContext.getService(theRef);
            if (cp != null) {
                try {
                    if (svcClass.isInstance(cp)) {
                        S s = callback.execute(cp);
                        return s;
                    }
                    throw new Exception("Failed to cast service " + cp + " to required type " + svcClass);
                }
                finally {
                    bundleContext.ungetService(theRef);
                }
            }
            throw new Exception("Failed to retrieve service of type " + svcClass + " with filter " + filter);
        }
        throw new Exception("Multiple services (" + refs.length + ") of type " + svcClass + " found with filter " + filter);
    }
}