Search in sources :

Example 91 with InvalidSyntaxException

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

the class SesameYardComponent method activate.

/**
     * Register a service tracker for the KiWiRepositoryService; once it is there, register a new SesameYard.
     *
     * @param context
     * @throws ConfigurationException
     * @throws RepositoryException
     */
@Activate
protected final void activate(ComponentContext context) throws ConfigurationException, RepositoryException {
    @SuppressWarnings("unchecked") Dictionary<String, Object> config = context.getProperties();
    this.config = config;
    this.bundleContext = context.getBundleContext();
    repoId = (String) config.get(REPOSITORY_ID);
    if (repoId != null && repoId.trim().isEmpty()) {
        repoId = null;
    }
    log.info(" - repository ID: {}", repoId);
    String filterStr;
    if (repoId != null) {
        filterStr = String.format("(&(objectClass=%s)(%s=%s))", Repository.class.getName(), REPOSITORY_ID, repoId);
    } else {
        filterStr = String.format("(&(objectClass=%s))", Repository.class.getName());
    }
    Filter filter;
    try {
        log.info(" - service Filter: {}", filterStr);
        filter = bundleContext.createFilter(filterStr);
    } catch (InvalidSyntaxException e) {
        throw new ConfigurationException(REPOSITORY_ID, "Unable to build Service " + "Filter with parsed Repository ID '" + repoId + "' (filter: '" + filterStr + "')", e);
    }
    yardConfig = new SesameYardConfig(config);
    //check context is set 
    Object value = config.get(SesameYard.CONTEXT_ENABLED);
    if (value == null || value.toString().trim().isEmpty()) {
        //not set ... set default to TRUE
        yardConfig.setContextEnabled(true);
    } else if (!yardConfig.isContextEnabled()) {
        //want to allow)!
        throw new ConfigurationException(SesameYard.CONTEXT_ENABLED, "Sesame Contexts MUST BE enabled for the Kiwi TripleStore Yard");
    }
    repositoryTracker = new ServiceTracker(bundleContext, filter, this);
    log.info(" ... start tracking for Sesame Repositories");
    repositoryTracker.open();
}
Also used : SesameYardConfig(org.apache.stanbol.entityhub.yard.sesame.SesameYardConfig) Filter(org.osgi.framework.Filter) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceTracker(org.osgi.util.tracker.ServiceTracker) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Activate(org.apache.felix.scr.annotations.Activate)

Example 92 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project bnd by bndtools.

the class ResolveProcess method resolveRequired.

public Map<Resource, List<Wire>> resolveRequired(Processor properties, Project project, Registry plugins, Resolver resolver, Collection<ResolutionCallback> callbacks, LogService log) throws ResolutionException {
    required = new HashMap<Resource, List<Wire>>();
    optional = new HashMap<Resource, List<Wire>>();
    BndrunResolveContext rc = new BndrunResolveContext(properties, project, plugins, log);
    rc.addCallbacks(callbacks);
    // 1. Resolve initial requirements
    Map<Resource, List<Wire>> wirings;
    try {
        wirings = resolver.resolve(rc);
    } catch (ResolutionException re) {
        throw augment(rc, re);
    }
    // 2. Save initial requirement resolution
    Pair<Resource, List<Wire>> initialRequirement = null;
    for (Map.Entry<Resource, List<Wire>> wiring : wirings.entrySet()) {
        if (rc.getInputResource() == wiring.getKey()) {
            initialRequirement = new Pair<Resource, List<Wire>>(wiring.getKey(), wiring.getValue());
            break;
        }
    }
    // 3. Save the resolved root resources
    final List<Resource> resources = new ArrayList<Resource>();
    for (Resource r : rc.getMandatoryResources()) {
        reqs: for (Requirement req : r.getRequirements(null)) {
            for (Resource found : wirings.keySet()) {
                String filterStr = req.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
                try {
                    org.osgi.framework.Filter filter = filterStr != null ? org.osgi.framework.FrameworkUtil.createFilter(filterStr) : null;
                    for (Capability c : found.getCapabilities(req.getNamespace())) {
                        if (filter != null && filter.matches(c.getAttributes())) {
                            resources.add(found);
                            continue reqs;
                        }
                    }
                } catch (InvalidSyntaxException e) {
                }
            }
        }
    }
    // 4. Add any 'osgi.wiring.bundle' requirements
    List<Resource> wiredBundles = new ArrayList<Resource>();
    for (Resource resource : resources) {
        addWiredBundle(wirings, resource, wiredBundles);
    }
    for (Resource resource : wiredBundles) {
        if (!resources.contains(resource)) {
            resources.add(resource);
        }
    }
    final Map<Resource, List<Wire>> discoveredOptional = new LinkedHashMap<Resource, List<Wire>>();
    // 5. Resolve the rest
    BndrunResolveContext rc2 = new BndrunResolveContext(properties, project, plugins, log) {

        @Override
        public Collection<Resource> getMandatoryResources() {
            return resources;
        }

        @Override
        public boolean isInputResource(Resource resource) {
            for (Resource r : resources) {
                if (GenericResolveContext.resourceIdentityEquals(r, resource)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public List<Capability> findProviders(Requirement requirement) {
            List<Capability> toReturn = super.findProviders(requirement);
            if (toReturn.isEmpty() && isEffective(requirement) && RESOLUTION_OPTIONAL.equals(requirement.getDirectives().get(REQUIREMENT_RESOLUTION_DIRECTIVE))) {
                for (Capability cap : findProvidersFromRepositories(requirement, new LinkedHashSet<Capability>())) {
                    Resource optionalRes = cap.getResource();
                    List<Wire> list = discoveredOptional.get(optionalRes);
                    if (list == null) {
                        list = new ArrayList<>();
                        discoveredOptional.put(optionalRes, list);
                    }
                    WireImpl candidateWire = new WireImpl(cap, requirement);
                    if (!list.contains(candidateWire))
                        list.add(candidateWire);
                }
            }
            return toReturn;
        }
    };
    rc2.addCallbacks(callbacks);
    try {
        wirings = resolver.resolve(rc2);
    } catch (ResolutionException re) {
        throw augment(rc2, re);
    }
    if (initialRequirement != null) {
        wirings.put(initialRequirement.getFirst(), initialRequirement.getSecond());
    }
    Map<Resource, List<Wire>> result = invertWirings(wirings, rc2);
    removeFrameworkAndInputResources(result, rc2);
    required.putAll(result);
    optional = tidyUpOptional(wirings, discoveredOptional, log);
    return result;
}
Also used : Capability(org.osgi.resource.Capability) Resource(org.osgi.resource.Resource) ArrayList(java.util.ArrayList) WireImpl(aQute.bnd.osgi.resource.WireImpl) Wire(org.osgi.resource.Wire) LinkedHashMap(java.util.LinkedHashMap) ResolutionException(org.osgi.service.resolver.ResolutionException) Requirement(org.osgi.resource.Requirement) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 93 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project bnd by bndtools.

the class OSGiTestCase method withService.

/**
	 * <p>
	 * Perform the specified operation against a service, if available.
	 * </p>
	 * <p>
	 * <strong>Example:</strong>
	 * </p>
	 * 
	 * <pre>
	 * String reply = withService(HelloService.class, null, 0, new Operation&lt;HelloService,String&gt;() {
	 * 	public String call(HelloService service) {
	 * 		return service.sayHello();
	 * 	}
	 * });
	 * </pre>
	 * 
	 * @param <S> The service type.
	 * @param <R> The result type.
	 * @param service The service class.
	 * @param filter An additional filter expression, or {@code
	 * null}.
	 * @param timeout The maximum time to wait (in ms) for a service to become
	 *            available; a zero or negative timeout implies we should fail
	 *            if the service is not immediatelt available.
	 * @param operation The operation to perform against the service.
	 * @throws Exception
	 */
protected <S, R> R withService(Class<S> service, String filter, long timeout, Operation<? super S, R> operation) throws Exception {
    BundleContext context = getBundleContext();
    ServiceTracker tracker = null;
    if (filter != null) {
        try {
            Filter combined = FrameworkUtil.createFilter("(" + Constants.OBJECTCLASS + "=" + service.getName() + ")");
            tracker = new ServiceTracker(context, combined, null);
        } catch (InvalidSyntaxException e) {
            fail("Invalid filter syntax.");
            return null;
        }
    } else {
        tracker = new ServiceTracker(context, service.getName(), null);
    }
    try {
        tracker.open();
        Object instance;
        if (timeout <= 0) {
            instance = tracker.getService();
        } else {
            instance = tracker.waitForService(timeout);
        }
        if (instance == null || !service.isInstance(instance))
            fail(MessageFormat.format("Service \"{0}\" not available.", service.getName()));
        @SuppressWarnings("unchecked") S casted = (S) instance;
        return operation.perform(casted);
    } catch (InterruptedException e) {
        fail("Interrupted.");
    } finally {
        tracker.close();
    }
    // unreachable
    return null;
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleContext(org.osgi.framework.BundleContext)

Example 94 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project bnd by bndtools.

the class CapabilityIndex method appendMatchingCapabilities.

public void appendMatchingCapabilities(Requirement requirement, Collection<? super Capability> capabilities) {
    List<Capability> caps;
    synchronized (this) {
        if (capabilityMap.containsKey(requirement.getNamespace()))
            caps = new ArrayList<>(capabilityMap.get(requirement.getNamespace()));
        else
            caps = Collections.emptyList();
    }
    if (caps.isEmpty())
        return;
    try {
        String filterStr = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
        Filter filter = filterStr != null ? FrameworkUtil.createFilter(filterStr) : null;
        for (Capability cap : caps) {
            boolean match;
            if (filter == null)
                match = true;
            else
                match = filter.match(new MapToDictionaryAdapter(cap.getAttributes()));
            if (match)
                capabilities.add(cap);
        }
    } catch (InvalidSyntaxException e) {
    // Assume no matches
    }
}
Also used : Capability(org.osgi.resource.Capability) Filter(org.osgi.framework.Filter) ArrayList(java.util.ArrayList) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException)

Example 95 with InvalidSyntaxException

use of org.osgi.framework.InvalidSyntaxException in project ddf by codice.

the class XsltMetacardTransformer method transform.

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException {
    LOGGER.debug("Entering metacard xslt transform.");
    Transformer transformer;
    Map<String, Object> mergedMap = new HashMap<String, Object>(localMap);
    if (arguments != null) {
        mergedMap.putAll(arguments);
    }
    // adding metacard data not in document
    mergedMap.put("id", getValueOrEmptyString(metacard.getId()));
    mergedMap.put("siteName", getValueOrEmptyString(metacard.getSourceId()));
    mergedMap.put("title", getValueOrEmptyString(metacard.getTitle()));
    mergedMap.put("type", getValueOrEmptyString(metacard.getMetacardType()));
    mergedMap.put("date", getValueOrEmptyString(metacard.getCreatedDate()));
    mergedMap.put("product", getValueOrEmptyString(metacard.getResourceURI()));
    mergedMap.put("thumbnail", getValueOrEmptyString(metacard.getThumbnail()));
    mergedMap.put("geometry", getValueOrEmptyString(metacard.getLocation()));
    ServiceReference[] refs = null;
    try {
        LOGGER.debug("Searching for other Metacard Transformers.");
        // TODO INJECT THESE!!!
        refs = context.getServiceReferences(MetacardTransformer.class.getName(), null);
    } catch (InvalidSyntaxException e) {
    // can't happen because filter is null
    }
    if (refs != null) {
        List<String> serviceList = new ArrayList<String>();
        LOGGER.debug("Found other Metacard transformers, adding them to a service reference list.");
        for (ServiceReference ref : refs) {
            if (ref != null) {
                String title = null;
                String shortName = (String) ref.getProperty(Constants.SERVICE_SHORTNAME);
                if ((title = (String) ref.getProperty(Constants.SERVICE_TITLE)) == null) {
                    title = "View as " + shortName.toUpperCase();
                }
                String url = "/services/catalog/" + metacard.getId() + "?transform=" + shortName;
                // define the services
                serviceList.add(title);
                serviceList.add(url);
            }
        }
        mergedMap.put("services", serviceList);
    } else {
        LOGGER.debug("No other Metacard transformers were found.");
    }
    // TODO: maybe add updated, type, and uuid here?
    // map.put("updated", fmt.print(result.getPostedDate().getTime()));
    // map.put("type", card.getSingleType().getValue());
    BinaryContent resultContent;
    StreamResult resultOutput = null;
    XMLReader xmlReader = null;
    try {
        XMLReader xmlParser = XMLReaderFactory.createXMLReader();
        xmlParser.setFeature("http://xml.org/sax/features/external-general-entities", false);
        xmlParser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        xmlParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        xmlReader = new XMLFilterImpl(xmlParser);
    } catch (SAXException e) {
        LOGGER.debug(e.getMessage(), e);
    }
    Source source = new SAXSource(xmlReader, new InputSource(new StringReader(metacard.getMetadata())));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resultOutput = new StreamResult(baos);
    try {
        transformer = templates.newTransformer();
    } catch (TransformerConfigurationException tce) {
        throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(), tce.getCause());
    }
    if (!mergedMap.isEmpty()) {
        for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
            LOGGER.debug("Adding parameter to transform {}:{}", entry.getKey(), entry.getValue());
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
    }
    try {
        transformer.transform(source, resultOutput);
        byte[] bytes = baos.toByteArray();
        IOUtils.closeQuietly(baos);
        LOGGER.debug("Transform complete.");
        resultContent = new XsltTransformedContent(bytes, mimeType);
    } catch (TransformerException te) {
        throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getMessage(), te.getCause());
    } finally {
    // TODO: if we ever start to reuse transformers, we should add this
    // code back in
    // transformer.reset();
    }
    return resultContent;
}
Also used : InputSource(org.xml.sax.InputSource) Transformer(javax.xml.transform.Transformer) MetacardTransformer(ddf.catalog.transform.MetacardTransformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) BinaryContent(ddf.catalog.data.BinaryContent) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) SAXException(org.xml.sax.SAXException) XMLFilterImpl(org.xml.sax.helpers.XMLFilterImpl) StringReader(java.io.StringReader) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) XMLReader(org.xml.sax.XMLReader) TransformerException(javax.xml.transform.TransformerException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServiceReference(org.osgi.framework.ServiceReference) SAXSource(javax.xml.transform.sax.SAXSource) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

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