Search in sources :

Example 11 with InvalidSyntaxException

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

the class ImportedServiceImpl method generateAttributeFilter.

private Filter generateAttributeFilter(Map<String, String> attrsToPopulate) throws InvalidAttributeException {
    logger.debug(LOG_ENTRY, "generateAttributeFilter", new Object[] { attrsToPopulate });
    Filter result = null;
    try {
        attrsToPopulate.put(ModellingConstants.OBR_SERVICE, ModellingConstants.OBR_SERVICE);
        if (_blueprintFilter != null) {
            // We may get blueprint filters of the form (&(a=b)(c=d)). We can't put these in 'whole' because we'll 
            // end up generating a filter of the form (&(objectClass=foo)(&(a=b)(c=d)) which subsequent calls to 
            // parseFilter will choke on. So as an interim fix we'll strip off a leading &( and trailing ) if present. 
            String reducedBlueprintFilter;
            if (_blueprintFilter.startsWith("(&")) {
                reducedBlueprintFilter = _blueprintFilter.substring(2, _blueprintFilter.length() - 1);
            } else {
                reducedBlueprintFilter = _blueprintFilter;
            }
            attrsToPopulate.put(ManifestHeaderProcessor.NESTED_FILTER_ATTRIBUTE, reducedBlueprintFilter);
        }
        if (_componentName != null) {
            attrsToPopulate.put("osgi.service.blueprint.compname", _componentName);
        }
        if (_iface != null) {
            attrsToPopulate.put(Constants.OBJECTCLASS, _iface);
        }
        _attribFilterString = ManifestHeaderProcessor.generateFilter(_attributes);
        if (!"".equals(_attribFilterString)) {
            result = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_attribFilterString));
        }
    } catch (InvalidSyntaxException isx) {
        InvalidAttributeException iax = new InvalidAttributeException("A syntax error occurred attempting to parse the blueprint filter string '" + _blueprintFilter + "' for element with id " + _id + ": " + isx.getLocalizedMessage(), isx);
        logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[] { isx });
        throw iax;
    }
    logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[] { result });
    return result;
}
Also used : InvalidAttributeException(org.apache.aries.application.InvalidAttributeException) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException)

Example 12 with InvalidSyntaxException

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

the class ProviderBundleTrackerCustomizer method addingBundle.

public List<ServiceRegistration> addingBundle(final Bundle bundle, BundleEvent event) {
    log(LogService.LOG_DEBUG, "Bundle Considered for SPI providers: " + bundle.getSymbolicName());
    if (bundle.equals(spiBundle))
        // don't process the SPI bundle itself
        return null;
    List<String> providedServices = null;
    Map<String, Object> customAttributes = new HashMap<String, Object>();
    if (bundle.getHeaders().get(SpiFlyConstants.REQUIRE_CAPABILITY) != null) {
        try {
            providedServices = readServiceLoaderMediatorCapabilityMetadata(bundle, customAttributes);
        } catch (InvalidSyntaxException e) {
            log(LogService.LOG_ERROR, "Unable to read capabilities from bundle " + bundle, e);
        }
    }
    boolean fromSPIProviderHeader = false;
    String spiProviderHeader = getHeaderFromBundleOrFragment(bundle, SpiFlyConstants.SPI_PROVIDER_HEADER);
    if (providedServices == null && spiProviderHeader != null) {
        String header = spiProviderHeader.trim();
        if ("*".equals(header)) {
            providedServices = new ArrayList<String>();
        } else {
            providedServices = Arrays.asList(header.split(","));
        }
        fromSPIProviderHeader = true;
    }
    if (providedServices == null) {
        log(LogService.LOG_DEBUG, "No '" + SpiFlyConstants.SPI_PROVIDER_HEADER + "' Manifest header. Skipping bundle: " + bundle.getSymbolicName());
        return null;
    } else {
        log(LogService.LOG_INFO, "Examining bundle for SPI provider: " + bundle.getSymbolicName());
    }
    for (String svc : providedServices) {
        // Eagerly register any services that are explicitly listed, as they may not be found in META-INF/services
        activator.registerProviderBundle(svc, bundle, customAttributes);
    }
    List<URL> serviceFileURLs = new ArrayList<URL>();
    @SuppressWarnings("unchecked") Enumeration<URL> entries = bundle.findEntries(METAINF_SERVICES, "*", false);
    if (entries != null) {
        serviceFileURLs.addAll(Collections.list(entries));
    }
    Object bcp = bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH);
    if (bcp instanceof String) {
        for (String entry : ((String) bcp).split(",")) {
            entry = entry.trim();
            if (entry.equals("."))
                continue;
            URL url = bundle.getResource(entry);
            if (url != null) {
                serviceFileURLs.addAll(getMetaInfServiceURLsFromJar(url));
            }
        }
    }
    final List<ServiceRegistration> registrations = new ArrayList<ServiceRegistration>();
    for (URL serviceFileURL : serviceFileURLs) {
        log(LogService.LOG_INFO, "Found SPI resource: " + serviceFileURL);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(serviceFileURL.openStream()));
            String className = null;
            while ((className = reader.readLine()) != null) {
                try {
                    className = className.trim();
                    if (className.length() == 0)
                        // empty line
                        continue;
                    if (className.startsWith("#"))
                        // a comment
                        continue;
                    String serviceFile = serviceFileURL.toExternalForm();
                    int idx = serviceFile.lastIndexOf('/');
                    String registrationClassName = className;
                    if (serviceFile.length() > idx) {
                        registrationClassName = serviceFile.substring(idx + 1);
                    }
                    if (providedServices.size() > 0 && !providedServices.contains(registrationClassName))
                        continue;
                    final Class<?> cls = bundle.loadClass(className);
                    log(LogService.LOG_INFO, "Loaded SPI provider: " + cls);
                    final Hashtable<String, Object> properties;
                    if (fromSPIProviderHeader)
                        properties = new Hashtable<String, Object>();
                    else
                        properties = findServiceRegistrationProperties(bundle.getHeaders(), registrationClassName, className);
                    if (properties != null) {
                        properties.put(SpiFlyConstants.SERVICELOADER_MEDIATOR_PROPERTY, spiBundle.getBundleId());
                        properties.put(SpiFlyConstants.PROVIDER_IMPLCLASS_PROPERTY, cls.getName());
                        ServiceRegistration reg = null;
                        SecurityManager sm = System.getSecurityManager();
                        if (sm != null) {
                            if (bundle.hasPermission(new ServicePermission(registrationClassName, ServicePermission.REGISTER))) {
                                reg = bundle.getBundleContext().registerService(registrationClassName, new ProviderServiceFactory(cls), properties);
                            } else {
                                log(LogService.LOG_INFO, "Bundle " + bundle + " does not have the permission to register services of type: " + registrationClassName);
                            }
                        } else {
                            reg = bundle.getBundleContext().registerService(registrationClassName, new ProviderServiceFactory(cls), properties);
                        }
                        if (reg != null) {
                            registrations.add(reg);
                            log(LogService.LOG_INFO, "Registered service: " + reg);
                        }
                    }
                    activator.registerProviderBundle(registrationClassName, bundle, customAttributes);
                    log(LogService.LOG_INFO, "Registered provider: " + registrationClassName + " in bundle " + bundle.getSymbolicName());
                } catch (Exception e) {
                    log(LogService.LOG_WARNING, "Could not load SPI implementation referred from " + serviceFileURL, e);
                }
            }
        } catch (IOException e) {
            log(LogService.LOG_WARNING, "Could not read SPI metadata from " + serviceFileURL, e);
        }
    }
    return registrations;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) URL(java.net.URL) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceRegistration(org.osgi.framework.ServiceRegistration) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) IOException(java.io.IOException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException) ServicePermission(org.osgi.framework.ServicePermission) BufferedReader(java.io.BufferedReader)

Example 13 with InvalidSyntaxException

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

the class ServerSideClass method getInitialComponents.

/**
	 * this is invoked by a page onload.. so until it's invoked.. we dont care
	 * about components
	 */
public void getInitialComponents(String dataProvider) {
    System.err.println("GET INITIAL BUNDLES ASKED TO USE DATAPROVIDER " + dataProvider);
    if (dataProvider == null)
        throw new IllegalArgumentException("Unable to accept 'null' as a dataProvider");
    // do we need to update?
    if (!this.modelInfoServiceHint.equals(dataProvider)) {
        this.modelInfoServiceHint = dataProvider;
        if (!(this.ModelInfoService == null)) {
            // we already had a provider.. we need to shut down the existing
            // components & relationships in the browsers..
            addFunctionCall("forgetAboutEverything");
        }
        ServletContext context = org.directwebremoting.ServerContextFactory.get().getServletContext();
        Object o = context.getAttribute("osgi-bundlecontext");
        if (o != null) {
            if (o instanceof BundleContext) {
                BundleContext b_ctx = (BundleContext) o;
                System.err.println("Looking up bcip");
                try {
                    ServiceReference[] sr = b_ctx.getServiceReferences(ModelInfoService.class.getName(), "(displayName=" + this.modelInfoServiceHint + ")");
                    if (sr != null) {
                        System.err.println("Getting bcip");
                        this.ModelInfoService = (ModelInfoService) b_ctx.getService(sr[0]);
                        System.err.println("Got bcip " + this.ModelInfoService);
                    } else {
                        System.err.println("UNABLE TO FIND BCIP!!");
                        System.err.println("UNABLE TO FIND BCIP!!");
                        System.err.println("UNABLE TO FIND BCIP!!");
                    }
                } catch (InvalidSyntaxException ise) {
                }
                if (this.ModelInfoService != null) {
                    if (!rlisteners.containsKey(this.ModelInfoService)) {
                        RelationshipInfoProvider.RelationshipInfoListener rl = new RelationshipInfoListenerImpl(this.modelInfoServiceHint);
                        rlisteners.put(this.ModelInfoService, rl);
                        this.ModelInfoService.getRelationshipInfoProvider().registerRelationshipInfoListener(rl);
                    }
                    if (!clisteners.containsKey(this.ModelInfoService)) {
                        ComponentInfoProvider.ComponentInfoListener cl = new ComponentInfoListenerImpl(this.modelInfoServiceHint);
                        clisteners.put(this.ModelInfoService, cl);
                        this.ModelInfoService.getComponentInfoProvider().registerComponentInfoListener(cl);
                    }
                }
            }
        }
    }
    Collection<ComponentInfo> bis = this.ModelInfoService.getComponentInfoProvider().getComponents();
    System.err.println("Got " + (bis == null ? "null" : bis.size()) + " components back from the provider ");
    if (bis != null) {
        for (ComponentInfo b : bis) {
            System.err.println("Adding Component .. " + b.getId());
            addFunctionCall("addComponent", b);
        }
    }
    Collection<RelationshipInfo> ris = this.ModelInfoService.getRelationshipInfoProvider().getRelationships();
    System.err.println("Got " + (ris == null ? "null" : ris.size()) + " relationships back from the provider ");
    if (ris != null) {
        for (RelationshipInfo r : ris) {
            System.err.println("Adding relationship type " + r.getType() + " called " + r.getName() + " from " + r.getProvidedBy().getId());
            addFunctionCall("addRelationship", r);
        }
    }
}
Also used : RelationshipInfoProvider(org.apache.aries.samples.goat.api.RelationshipInfoProvider) ComponentInfoProvider(org.apache.aries.samples.goat.api.ComponentInfoProvider) ModelInfoService(org.apache.aries.samples.goat.api.ModelInfoService) ServiceReference(org.osgi.framework.ServiceReference) RelationshipInfo(org.apache.aries.samples.goat.api.RelationshipInfo) ServletContext(javax.servlet.ServletContext) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ComponentInfo(org.apache.aries.samples.goat.api.ComponentInfo) BundleContext(org.osgi.framework.BundleContext)

Example 14 with InvalidSyntaxException

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

the class ServiceHelper method findService.

private static ServicePair findService(BundleContext ctx, String interface1, String filter) throws NamingException {
    ServicePair p = null;
    try {
        ServiceReference[] refs = ctx.getServiceReferences(interface1, filter);
        if (refs != null) {
            // natural order is the exact opposite of the order we desire.
            Arrays.sort(refs, new Comparator<ServiceReference>() {

                public int compare(ServiceReference o1, ServiceReference o2) {
                    return o2.compareTo(o1);
                }
            });
            for (ServiceReference ref : refs) {
                Object service = ctx.getService(ref);
                if (service != null) {
                    p = new ServicePair();
                    p.ref = ref;
                    p.service = service;
                    break;
                }
            }
        }
    } catch (InvalidSyntaxException e) {
    // If we get an invalid syntax exception we just ignore it. Null
    // will be returned which
    // is valid and that may result in a NameNotFoundException if that
    // is the right thing to do
    }
    return p;
}
Also used : InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Example 15 with InvalidSyntaxException

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

the class RequirementImpl method isSatisfied.

@SuppressWarnings("unchecked")
public boolean isSatisfied(Capability cap) {
    logger.debug(LOG_ENTRY, "isSatisfied", cap);
    boolean result = false;
    String name = getName();
    if (name.equals(cap.getName())) {
        String filterToCreate = getFilter();
        try {
            Filter f = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(filterToCreate));
            Hashtable<String, Object> hash = new Hashtable<String, Object>();
            Map<String, String> props = cap.getPropertiesAsMap();
            if ((props != null) && (!!!props.isEmpty())) {
                for (Map.Entry<String, String> propertyPair : props.entrySet()) {
                    hash.put(propertyPair.getKey(), propertyPair.getValue());
                }
            }
            result = f.match(hash);
        } catch (InvalidSyntaxException e) {
            logger.error(e.getMessage());
        }
    }
    logger.debug(LOG_EXIT, "isSatisfied", result);
    return result;
}
Also used : Filter(org.osgi.framework.Filter) Hashtable(java.util.Hashtable) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Map(java.util.Map)

Aggregations

InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)105 ServiceReference (org.osgi.framework.ServiceReference)54 Filter (org.osgi.framework.Filter)26 ArrayList (java.util.ArrayList)22 IOException (java.io.IOException)20 BundleContext (org.osgi.framework.BundleContext)16 ServiceTracker (org.osgi.util.tracker.ServiceTracker)14 HashMap (java.util.HashMap)12 Configuration (org.osgi.service.cm.Configuration)12 Map (java.util.Map)10 Test (org.junit.Test)9 Dictionary (java.util.Dictionary)8 Hashtable (java.util.Hashtable)8 List (java.util.List)6 ConfigurationException (org.osgi.service.cm.ConfigurationException)6 Metacard (ddf.catalog.data.Metacard)4 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)4 CatalogFramework (ddf.catalog.CatalogFramework)3 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)3 InputTransformer (ddf.catalog.transform.InputTransformer)3