Search in sources :

Example 66 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project opennms by OpenNMS.

the class GraphMLPropagateVertexStatusProvider method getStatusForVertices.

@Override
public Map<? extends VertexRef, ? extends Status> getStatusForVertices(final VertexProvider vertexProvider, final Collection<VertexRef> vertices, final Criteria[] criteria) {
    final List<Criteria> criteriaList = Lists.newArrayList(criteria);
    final LoopDetectionCriteria loopDetectionCriteria = Iterables.tryFind(criteriaList, c -> c instanceof LoopDetectionCriteria).transform(c -> (LoopDetectionCriteria) c).or(LoopDetectionCriteria::new);
    // Build map from namespace to opposite vertices
    final Multimap<String, VertexRef> oppositeVertices = HashMultimap.create();
    for (final VertexRef sourceVertex : vertices) {
        // Filter out loops
        if (loopDetectionCriteria.contains(sourceVertex)) {
            LOG.error("Loop detected with: {}:{}", sourceVertex.getNamespace(), sourceVertex.getId());
            continue;
        }
        for (VertexRef targetVertex : this.provider.getOppositeVertices(sourceVertex)) {
            oppositeVertices.put(targetVertex.getNamespace(), targetVertex);
        }
    }
    // Replace loop detection criteria with extended one
    criteriaList.remove(loopDetectionCriteria);
    criteriaList.add(loopDetectionCriteria.with(vertices));
    // Find and call status provider for each namespace and get result per opposite vertex
    final Map<VertexRef, Status> targetStatuses = Maps.newHashMap();
    try {
        final Collection<ServiceReference<StatusProvider>> statusProviderReferences = this.bundleContext.getServiceReferences(StatusProvider.class, null);
        for (final ServiceReference<StatusProvider> statusProviderReference : statusProviderReferences) {
            try {
                final StatusProvider statusProvider = bundleContext.getService(statusProviderReference);
                for (final Map.Entry<String, Collection<VertexRef>> e : oppositeVertices.asMap().entrySet()) {
                    if (statusProvider.contributesTo(e.getKey())) {
                        targetStatuses.putAll(statusProvider.getStatusForVertices(this.provider.getGraphProviderBy(e.getKey()), e.getValue(), criteriaList.toArray(new Criteria[0])));
                    }
                }
            } finally {
                bundleContext.ungetService(statusProviderReference);
            }
        }
    } catch (final InvalidSyntaxException e) {
    }
    // Merge statuses from targets to sources
    final Map<VertexRef, GraphMLVertexStatus> statuses = Maps.newHashMap();
    for (final VertexRef sourceVertex : vertices) {
        GraphMLVertexStatus mergedStatus = new GraphMLVertexStatus();
        for (VertexRef targetVertex : this.provider.getOppositeVertices(sourceVertex)) {
            if (targetStatuses.containsKey(targetVertex)) {
                mergedStatus = GraphMLVertexStatus.merge(mergedStatus, (GraphMLVertexStatus) targetStatuses.get(targetVertex));
            }
        }
        statuses.put(sourceVertex, mergedStatus);
    }
    return statuses;
}
Also used : Iterables(com.google.common.collect.Iterables) Logger(org.slf4j.Logger) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Multimap(com.google.common.collect.Multimap) Maps(com.google.common.collect.Maps) BundleContext(org.osgi.framework.BundleContext) HashSet(java.util.HashSet) Objects(java.util.Objects) StatusProvider(org.opennms.features.topology.api.topo.StatusProvider) List(java.util.List) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) VertexProvider(org.opennms.features.topology.api.topo.VertexProvider) Criteria(org.opennms.features.topology.api.topo.Criteria) Map(java.util.Map) GraphMLMetaTopologyProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLMetaTopologyProvider) Status(org.opennms.features.topology.api.topo.Status) VertexRef(org.opennms.features.topology.api.topo.VertexRef) ServiceReference(org.osgi.framework.ServiceReference) Status(org.opennms.features.topology.api.topo.Status) StatusProvider(org.opennms.features.topology.api.topo.StatusProvider) Criteria(org.opennms.features.topology.api.topo.Criteria) ServiceReference(org.osgi.framework.ServiceReference) Collection(java.util.Collection) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) VertexRef(org.opennms.features.topology.api.topo.VertexRef) Map(java.util.Map)

Example 67 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project opennms by OpenNMS.

the class SessionListenerRepository method getSessionListeners.

private List<SessionListener> getSessionListeners() {
    final List<SessionListener> sessionListeners = new ArrayList<>();
    try {
        final ServiceReference[] references = context.getAllServiceReferences(SessionListener.class.getName(), null);
        if (references != null) {
            for (ServiceReference eachReference : references) {
                Object service = context.getService(eachReference);
                if (service == null)
                    continue;
                sessionListeners.add((SessionListener) service);
            }
        }
    } catch (InvalidSyntaxException e) {
        LOG.error("Error retrieving SessionListeners", e);
    }
    return sessionListeners;
}
Also used : ArrayList(java.util.ArrayList) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Example 68 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project camel by apache.

the class CamelBlueprintHelper method getOsgiService.

public static <T> T getOsgiService(BundleContext bundleContext, Class<T> type, String filter, long timeout) {
    ServiceTracker<T, T> tracker = null;
    try {
        String flt;
        if (filter != null) {
            if (filter.startsWith("(")) {
                flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")";
            } else {
                flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))";
            }
        } else {
            flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
        }
        Filter osgiFilter = FrameworkUtil.createFilter(flt);
        tracker = new ServiceTracker<T, T>(bundleContext, osgiFilter, null);
        tracker.open(true);
        // Note that the tracker is not closed to keep the reference
        // This is buggy, as the service reference may change i think
        Object svc = tracker.waitForService(timeout);
        if (svc == null) {
            Dictionary<?, ?> dic = bundleContext.getBundle().getHeaders();
            LOG.warn("Test bundle headers: " + explode(dic));
            for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, null))) {
                LOG.warn("ServiceReference: " + ref + ", bundle: " + ref.getBundle() + ", symbolicName: " + ref.getBundle().getSymbolicName());
            }
            for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, flt))) {
                LOG.warn("Filtered ServiceReference: " + ref + ", bundle: " + ref.getBundle() + ", symbolicName: " + ref.getBundle().getSymbolicName());
            }
            throw new RuntimeException("Gave up waiting for service " + flt);
        }
        return type.cast(svc);
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException("Invalid filter", e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Example 69 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project graphdb by neo4j-attic.

the class OSGiExtensionLoader method loadExtensionsOfType.

public <T> Iterable<T> loadExtensionsOfType(Class<T> type) {
    try {
        System.out.println("Kernel: attempting to load extensions of type " + type.getName());
        ServiceReference[] services = bc.getServiceReferences(type.getName(), null);
        if (services != null) {
            Collection<T> serviceCollection = new LinkedList<T>();
            for (ServiceReference sr : services) {
                @SuppressWarnings("unchecked") T service = (T) bc.getService(sr);
                serviceCollection.add(service);
            }
            return serviceCollection;
        } else {
            return null;
        }
    } catch (InvalidSyntaxException e) {
        System.out.println("Failed to load extensions of type: " + type);
        e.printStackTrace();
    }
    return null;
}
Also used : InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) LinkedList(java.util.LinkedList) ServiceReference(org.osgi.framework.ServiceReference)

Example 70 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project karaf by apache.

the class EncryptionSupport method getEncryption.

public Encryption getEncryption() {
    if (encryption == null) {
        Map<String, String> encOpts = new HashMap<>();
        for (String key : options.keySet()) {
            if (key.startsWith("encryption.")) {
                encOpts.put(key.substring("encryption.".length()), options.get(key).toString());
            }
        }
        encryptionPrefix = encOpts.remove("prefix");
        encryptionSuffix = encOpts.remove("suffix");
        boolean enabled = Boolean.parseBoolean(encOpts.remove("enabled"));
        if (!enabled) {
            if (debug) {
                logger.debug("Encryption is disabled.");
            }
        } else {
            String name = encOpts.remove("name");
            if (debug) {
                if (name != null && name.length() > 0) {
                    logger.debug("Encryption is enabled. Using service " + name + " with options " + encOpts);
                } else {
                    logger.debug("Encryption is enabled. Using options " + encOpts);
                }
            }
            // lookup the encryption service reference
            ServiceReference[] encryptionServiceReferences;
            try {
                encryptionServiceReferences = bundleContext.getServiceReferences(EncryptionService.class.getName(), name != null && name.length() > 0 ? "(name=" + name + ")" : null);
                int timeout = 0;
                while (encryptionServiceReferences == null || encryptionServiceReferences.length == 0) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ie) {
                    // nothing to do
                    }
                    encryptionServiceReferences = bundleContext.getServiceReferences(EncryptionService.class.getName(), name != null && name.length() > 0 ? "(name=" + name + ")" : null);
                    timeout++;
                    if (timeout == 40)
                        break;
                }
            } catch (InvalidSyntaxException e) {
                throw new IllegalStateException("The encryption service filter is not well formed.", e);
            }
            if (encryptionServiceReferences == null || encryptionServiceReferences.length == 0) {
                if (name != null && name.length() > 0) {
                    throw new IllegalStateException("Encryption service " + name + " not found. Please check that the encryption service is correctly set up.");
                } else {
                    throw new IllegalStateException("No encryption service found. Please install the Karaf encryption feature and check that the encryption algorithm is supported.");
                }
            }
            Arrays.sort(encryptionServiceReferences);
            for (ServiceReference ref : encryptionServiceReferences) {
                try {
                    EncryptionService encryptionService = (EncryptionService) bundleContext.getService(ref);
                    if (encryptionService != null) {
                        try {
                            encryption = encryptionService.createEncryption(encOpts);
                            if (encryption != null) {
                                break;
                            }
                        } finally {
                            bundleContext.ungetService(ref);
                        }
                    }
                } catch (IllegalStateException e) {
                // continue
                }
            }
            if (encryption == null) {
                throw new IllegalStateException("No EncryptionService supporting the required options could be found.");
            }
        }
    }
    return encryption;
}
Also used : HashMap(java.util.HashMap) EncryptionService(org.apache.karaf.jaas.modules.EncryptionService) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Aggregations

InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)124 ServiceReference (org.osgi.framework.ServiceReference)59 Filter (org.osgi.framework.Filter)29 ArrayList (java.util.ArrayList)27 IOException (java.io.IOException)23 BundleContext (org.osgi.framework.BundleContext)21 HashMap (java.util.HashMap)17 ServiceTracker (org.osgi.util.tracker.ServiceTracker)14 BundleException (org.osgi.framework.BundleException)12 Configuration (org.osgi.service.cm.Configuration)12 Map (java.util.Map)11 Dictionary (java.util.Dictionary)9 Hashtable (java.util.Hashtable)9 Test (org.junit.Test)9 List (java.util.List)8 File (java.io.File)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)7 URL (java.net.URL)6 LinkedHashMap (java.util.LinkedHashMap)6 FilterImpl (org.eclipse.osgi.internal.framework.FilterImpl)6