Search in sources :

Example 1 with MethodMetadata

use of org.apache.felix.ipojo.parser.MethodMetadata in project felix by apache.

the class EventAdminSubscriberHandler method configure.

/**
 * Constructor.
 *
 * @param metadata the omponent type metadata
 * @param conf the instance configuration
 * @throws ConfigurationException if one event subscription is not correct
 * @see org.apache.felix.ipojo.Handler#configure(org.apache.felix.ipojo.metadata.Element, java.util.Dictionary)
 */
public void configure(Element metadata, Dictionary conf) throws ConfigurationException {
    // Store the component manager
    m_manager = getInstanceManager();
    // Get the topics and filter instance configuration
    Dictionary instanceTopics = (Dictionary) conf.get(TOPICS_PROPERTY);
    Dictionary instanceFilter = (Dictionary) conf.get(FILTER_PROPERTY);
    // Get Metadata subscribers
    Element[] subscribers = metadata.getElements("subscriber", NAMESPACE);
    // The topics to listen
    Set topics = new TreeSet();
    if (subscribers != null) {
        // Configure all subscribers
        for (int i = 0; i < subscribers.length; i++) {
            // Extract the subscriber configuration
            EventAdminSubscriberMetadata subscriberMetadata = new EventAdminSubscriberMetadata(m_manager.getContext(), subscribers[i]);
            String name = subscriberMetadata.getName();
            info(LOG_PREFIX + "Configuring subscriber " + name);
            // Get the topics instance configuration if redefined
            String topicsString = (instanceTopics != null) ? (String) instanceTopics.get(name) : null;
            if (topicsString != null) {
                subscriberMetadata.setTopics(topicsString);
            }
            // Get the filter instance configuration if redefined
            String filterString = (instanceFilter != null) ? (String) instanceFilter.get(name) : null;
            if (filterString != null) {
                subscriberMetadata.setFilter(filterString);
            }
            // Check the publisher is correctly configured
            subscriberMetadata.check();
            // Add this subscriber's topics to the global list
            String[] subscriberTopics = subscriberMetadata.getTopics();
            for (int j = 0; j < subscriberTopics.length; j++) {
                topics.add(subscriberTopics[j]);
            }
            // Determine the event callback prototype
            PojoMetadata pojoMetadata = getPojoMetadata();
            String callbackType;
            if (subscriberMetadata.getDataKey() == null) {
                callbackType = Event.class.getName();
            } else {
                callbackType = subscriberMetadata.getDataType().getName();
            }
            // Create the specified callback and register it
            MethodMetadata methodMetadata = pojoMetadata.getMethod(subscriberMetadata.getCallback(), new String[] { callbackType });
            Callback callback = new Callback(methodMetadata, m_manager);
            m_callbacksByName.put(name, callback);
            // Add the subscriber list gloal map
            m_subscribersByName.put(name, subscriberMetadata);
        }
        // Construct the global topic list
        m_topics = new String[topics.size()];
        int i = 0;
        for (Iterator iterator = topics.iterator(); iterator.hasNext(); ) {
            String tmp = (String) iterator.next();
            m_topics[i++] = tmp;
        }
        m_description = new EventAdminSubscriberHandlerDescription(this, subscribers);
    } else {
        info(LOG_PREFIX + "No subscriber to configure");
    }
}
Also used : Element(org.apache.felix.ipojo.metadata.Element) Callback(org.apache.felix.ipojo.util.Callback) PojoMetadata(org.apache.felix.ipojo.parser.PojoMetadata) Event(org.osgi.service.event.Event) MethodMetadata(org.apache.felix.ipojo.parser.MethodMetadata)

Example 2 with MethodMetadata

use of org.apache.felix.ipojo.parser.MethodMetadata in project felix by apache.

the class EventAdminSubscriberHandler method initializeComponentFactory.

/**
 * Initializes the component type.
 *
 * @param cd component type description to populate.
 * @param metadata component type metadata.
 * @throws ConfigurationException if the metadata are incorrect.
 * @see org.apache.felix.ipojo.Handler#initializeComponentFactory(
 * org.apache.felix.ipojo.architecture.ComponentTypeDescription, org.apache.felix.ipojo.metadata.Element)
 */
public void initializeComponentFactory(ComponentTypeDescription cd, Element metadata) throws ConfigurationException {
    // Update the current component description
    Dictionary dict = new Properties();
    cd.addProperty(new PropertyDescription(TOPICS_PROPERTY, Dictionary.class.getName(), dict.toString()));
    dict = new Properties();
    cd.addProperty(new PropertyDescription(FILTER_PROPERTY, Dictionary.class.getName(), dict.toString()));
    // Get Metadata subscribers
    Element[] subscribers = metadata.getElements("subscriber", NAMESPACE);
    if (subscribers != null) {
        // Maps used to check name and field are unique
        Set nameSet = new HashSet();
        Set callbackSet = new HashSet();
        // Check all subscribers are well formed
        for (int i = 0; i < subscribers.length; i++) {
            // Check the subscriber configuration is correct by creating an
            // unused subscriber metadata
            EventAdminSubscriberMetadata subscriberMetadata = new EventAdminSubscriberMetadata(getFactory().getBundleContext(), subscribers[i]);
            String name = subscriberMetadata.getName();
            info(LOG_PREFIX + "Checking subscriber " + name);
            // Determine the event callback prototype
            PojoMetadata pojoMetadata = getPojoMetadata();
            String callbackType;
            if (subscriberMetadata.getDataKey() == null) {
                callbackType = Event.class.getName();
            } else {
                callbackType = subscriberMetadata.getDataType().getName();
            }
            // Check the event callback method is present
            MethodMetadata methodMetadata = pojoMetadata.getMethod(subscriberMetadata.getCallback(), new String[] { callbackType });
            String callbackSignature = subscriberMetadata.getCallback() + "(" + callbackType + ")";
            if (methodMetadata == null) {
                throw new ConfigurationException("Cannot find callback method " + callbackSignature);
            }
            // Warn if the same callback is used by several subscribers
            if (callbackSet.contains(callbackSignature)) {
                warn("The callback method is already used by another subscriber : " + callbackSignature);
            } else {
                callbackSet.add(callbackSignature);
            }
            // Check name is unique
            if (nameSet.contains(name)) {
                throw new ConfigurationException("A subscriber with the same name already exists : " + name);
            }
            nameSet.add(name);
        }
        m_description = new EventAdminSubscriberHandlerDescription(this, subscribers);
    } else {
        info(LOG_PREFIX + "No subscriber to check");
    }
}
Also used : Element(org.apache.felix.ipojo.metadata.Element) PropertyDescription(org.apache.felix.ipojo.architecture.PropertyDescription) ConfigurationException(org.apache.felix.ipojo.ConfigurationException) PojoMetadata(org.apache.felix.ipojo.parser.PojoMetadata) Event(org.osgi.service.event.Event) MethodMetadata(org.apache.felix.ipojo.parser.MethodMetadata)

Example 3 with MethodMetadata

use of org.apache.felix.ipojo.parser.MethodMetadata in project felix by apache.

the class DynamicMBeanImpl method invoke.

/**
 * Invokes the required method on the targeted POJO.
 *
 * @param operationName the name of the method called
 * @param params the parameters given to the method
 * @param signature the determine which method called
 * @return the object return by the method
 * @throws MBeanException if something bad occures
 * @throws ReflectionException if something bad occures
 */
public Object invoke(String operationName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
    MethodField method = m_configMap.getMethodFromName(operationName, signature);
    if (method != null) {
        MethodMetadata methodCall = method.getMethod();
        Callback mc = new Callback(methodCall, m_instanceManager);
        try {
            return mc.call(params);
        } catch (NoSuchMethodException e) {
            throw new ReflectionException(e);
        } catch (IllegalAccessException e) {
            throw new ReflectionException(e);
        } catch (InvocationTargetException e) {
            throw new MBeanException(e);
        }
    } else {
        throw new ReflectionException(new NoSuchMethodException(operationName), "Cannot find the operation " + operationName + " in " + m_className);
    }
}
Also used : ReflectionException(javax.management.ReflectionException) Callback(org.apache.felix.ipojo.util.Callback) MBeanException(javax.management.MBeanException) MethodMetadata(org.apache.felix.ipojo.parser.MethodMetadata) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with MethodMetadata

use of org.apache.felix.ipojo.parser.MethodMetadata in project felix by apache.

the class TemporalHandler method configure.

/**
 * Configure method. Creates managed dependencies.
 *
 * @param meta       the component type metadata.
 * @param dictionary the instance configuration.
 * @throws ConfigurationException if the dependency is not configured correctly
 * @see org.apache.felix.ipojo.Handler#configure(org.apache.felix.ipojo.metadata.Element, java.util.Dictionary)
 */
public void configure(Element meta, Dictionary dictionary) throws ConfigurationException {
    PojoMetadata manipulation = getFactory().getPojoMetadata();
    Element[] deps = meta.getElements("requires", NAMESPACE);
    // Also check with temporal is no requires.
    if (deps == null || deps.length == 0) {
        deps = meta.getElements("temporal", NAMESPACE);
    }
    // Get instance filters.
    Dictionary filtersConfiguration = getRequiresFilters(dictionary.get("temporal.filters"));
    if (filtersConfiguration == null || filtersConfiguration.isEmpty()) {
        // Fall back on the Requires handler configuration, if any
        filtersConfiguration = getRequiresFilters(dictionary.get("requires.filters"));
    }
    // Get from filters if any.
    Dictionary fromConfiguration = getRequiresFilters(dictionary.get("temporal.from"));
    if (fromConfiguration == null || fromConfiguration.isEmpty()) {
        // Fall back on the Requires handler configuration, if any
        fromConfiguration = getRequiresFilters(dictionary.get("requires.from"));
    }
    for (int i = 0; i < deps.length; i++) {
        if (!deps[i].containsAttribute("field") || m_dependencies.contains(deps[i].getAttribute("field"))) {
            error("One temporal dependency must be attached to a field or the field is already used");
            return;
        }
        String field = deps[i].getAttribute("field");
        String id = field;
        if (deps[i].containsAttribute("id")) {
            id = deps[i].getAttribute("id");
        }
        FieldMetadata fieldmeta = manipulation.getField(field);
        if (fieldmeta == null) {
            error("The field " + field + " does not exist in the class " + getInstanceManager().getClassName());
            return;
        }
        boolean agg = false;
        boolean collection = false;
        String spec = fieldmeta.getFieldType();
        if (spec.endsWith("[]")) {
            agg = true;
            spec = spec.substring(0, spec.length() - 2);
        } else if (Collection.class.getName().equals(spec)) {
            agg = true;
            collection = true;
            // Collection detected. Check for the specification attribute
            spec = deps[i].getAttribute("specification");
            if (spec == null) {
                error("A dependency injected inside a Collection must contain the 'specification' attribute");
            }
        }
        // Determine the filter
        String fil = deps[i].getAttribute("filter");
        // Override the filter if filter configuration if available in the instance configuration
        if (filtersConfiguration != null && id != null && filtersConfiguration.get(id) != null) {
            fil = (String) filtersConfiguration.get(id);
        }
        // Check the from attribute
        String from = deps[i].getAttribute("from");
        if (fromConfiguration != null && id != null && fromConfiguration.get(id) != null) {
            from = (String) fromConfiguration.get(id);
        }
        if (from != null) {
            String fromFilter = "(|(instance.name=" + from + ")(service.pid=" + from + "))";
            if (agg) {
                warn("The 'from' attribute is incompatible with aggregate requirements: only one provider will " + "match : " + fromFilter);
            }
            if (fil != null) {
                // Append the two filters
                fil = "(&" + fromFilter + fil + ")";
            } else {
                fil = fromFilter;
            }
        }
        Filter filter = null;
        if (fil != null) {
            try {
                filter = getInstanceManager().getContext().createFilter(fil);
            } catch (InvalidSyntaxException e) {
                throw new ConfigurationException("A requirement filter is invalid : " + filter, e);
            }
        }
        String prox = deps[i].getAttribute("proxy");
        // Use proxy by default except for array:
        boolean proxy = prox == null || prox.equals("true");
        if (prox == null && proxy) {
            // Proxy set because of the default.
            if (agg && !collection) {
                // Aggregate and array
                proxy = false;
            }
        }
        if (proxy && agg) {
            if (!collection) {
                error("Proxied aggregate temporal dependencies cannot be an array. Only collections are supported");
            }
        }
        long timeout = DEFAULT_TIMEOUT;
        if (deps[i].containsAttribute("timeout")) {
            String to = deps[i].getAttribute("timeout");
            if (to.equalsIgnoreCase("infinite") || to.equalsIgnoreCase("-1")) {
                // Infinite wait time ...
                timeout = Long.MAX_VALUE;
            } else {
                timeout = new Long(deps[i].getAttribute("timeout")).longValue();
            }
        }
        int policy = NO_POLICY;
        String di = null;
        String onTimeout = deps[i].getAttribute("onTimeout");
        if (onTimeout != null) {
            if (onTimeout.equalsIgnoreCase("nullable")) {
                policy = NULLABLE;
            } else if (onTimeout.equalsIgnoreCase("empty-array") || onTimeout.equalsIgnoreCase("empty")) {
                policy = EMPTY;
                if (!agg) {
                    // The empty array policy can only be used on aggregate dependencies
                    error("Cannot use the empty array policy for " + field + " : non aggregate dependency.");
                }
            } else if (onTimeout.equalsIgnoreCase("null")) {
                policy = NULL;
            } else if (onTimeout.length() > 0) {
                di = onTimeout;
                policy = DEFAULT_IMPLEMENTATION;
            }
        }
        Class specification = DependencyMetadataHelper.loadSpecification(spec, getInstanceManager().getContext());
        TemporalDependency dep = new TemporalDependency(specification, agg, collection, proxy, filter, getInstanceManager().getContext(), timeout, policy, di, this);
        m_dependencies.add(dep);
        if (!proxy) {
            // Register method interceptor only if are not a proxy
            MethodMetadata[] methods = manipulation.getMethods();
            for (int k = 0; k < methods.length; k++) {
                getInstanceManager().register(methods[k], dep);
            }
        }
        getInstanceManager().register(fieldmeta, dep);
    }
}
Also used : FieldMetadata(org.apache.felix.ipojo.parser.FieldMetadata) Element(org.apache.felix.ipojo.metadata.Element) Filter(org.osgi.framework.Filter) ConfigurationException(org.apache.felix.ipojo.ConfigurationException) PojoMetadata(org.apache.felix.ipojo.parser.PojoMetadata) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) MethodMetadata(org.apache.felix.ipojo.parser.MethodMetadata)

Example 5 with MethodMetadata

use of org.apache.felix.ipojo.parser.MethodMetadata in project felix by apache.

the class TransactionHandler method configure.

public void configure(Element arg0, Dictionary arg1) throws ConfigurationException {
    Element[] elements = arg0.getElements(NAME, NAMESPACE);
    if (elements.length > 1) {
        throw new ConfigurationException("The handler " + NAMESPACE + ":" + NAME + " cannot be declared several times");
    }
    String field = elements[0].getAttribute(FIELD_ATTRIBUTE);
    if (field != null) {
        FieldMetadata meta = getPojoMetadata().getField(field);
        if (meta == null) {
            throw new ConfigurationException("The transaction field does not exist in the pojo class : " + field);
        }
        if (!meta.getFieldType().equals(Transaction.class.getName())) {
            throw new ConfigurationException("The transaction field type must be " + Transaction.class.getName());
        }
        // Register the interceptor
        getInstanceManager().register(meta, this);
    }
    String oncommit = elements[0].getAttribute(ONCOMMIT_ATTRIBUTE);
    if (oncommit != null) {
        m_onCommit = new Callback(oncommit, new String[] { Transaction.class.getName() }, false, getInstanceManager());
    }
    String onrollback = elements[0].getAttribute(ONROLLBACK_ATTRIBUTE);
    if (onrollback != null) {
        m_onRollback = new Callback(onrollback, new String[] { Transaction.class.getName() }, false, getInstanceManager());
    }
    Element[] sub = elements[0].getElements(TRANSACTIONAL_ELEMENT);
    if (sub == null || sub.length == 0) {
        throw new ConfigurationException("The handler " + NAMESPACE + ":" + NAME + " must have " + TRANSACTIONAL_ELEMENT + " subelement");
    }
    for (int i = 0; i < sub.length; i++) {
        String method = sub[i].getAttribute(METHOD_ATTRIBUTE);
        String to = sub[i].getAttribute(TIMEOUT_ATTRIBUTE);
        String propa = sub[i].getAttribute(PROPAGATION_ATTRIBUTE);
        String nrbf = sub[i].getAttribute(NOROLLBACKFOR_ATTRIBUTE);
        String eorb = sub[i].getAttribute(EXCEPTIONONROLLBACK_ATTRIBUTE);
        if (method == null) {
            throw new ConfigurationException("A transactional element must specified the method attribute");
        }
        MethodMetadata meta = this.getPojoMetadata().getMethod(method);
        if (meta == null) {
            throw new ConfigurationException("A transactional method is not in the pojo class : " + method);
        }
        int timeout = 0;
        if (to != null) {
            timeout = new Integer(to).intValue();
        }
        int propagation = DEFAULT_PROPAGATION;
        if (propa != null) {
            propagation = parsePropagation(propa);
        }
        List<String> exceptions = new ArrayList<String>();
        if (nrbf != null) {
            exceptions = (List<String>) ParseUtils.parseArraysAsList(nrbf);
        }
        boolean exceptionOnRollback = false;
        if (eorb != null) {
            exceptionOnRollback = new Boolean(eorb).booleanValue();
        }
        TransactionalMethod tm = new TransactionalMethod(method, propagation, timeout, exceptions, exceptionOnRollback, this);
        m_methods.add(tm);
        this.getInstanceManager().register(meta, tm);
    }
}
Also used : FieldMetadata(org.apache.felix.ipojo.parser.FieldMetadata) Element(org.apache.felix.ipojo.metadata.Element) ArrayList(java.util.ArrayList) Callback(org.apache.felix.ipojo.util.Callback) ConfigurationException(org.apache.felix.ipojo.ConfigurationException) MethodMetadata(org.apache.felix.ipojo.parser.MethodMetadata)

Aggregations

MethodMetadata (org.apache.felix.ipojo.parser.MethodMetadata)13 Element (org.apache.felix.ipojo.metadata.Element)10 ConfigurationException (org.apache.felix.ipojo.ConfigurationException)6 PojoMetadata (org.apache.felix.ipojo.parser.PojoMetadata)6 FieldMetadata (org.apache.felix.ipojo.parser.FieldMetadata)5 Callback (org.apache.felix.ipojo.util.Callback)5 BundleContext (org.osgi.framework.BundleContext)4 PropertyDescription (org.apache.felix.ipojo.architecture.PropertyDescription)2 Attribute (org.apache.felix.ipojo.metadata.Attribute)2 Property (org.apache.felix.ipojo.util.Property)2 Filter (org.osgi.framework.Filter)2 Event (org.osgi.service.event.Event)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Member (java.lang.reflect.Member)1 ArrayList (java.util.ArrayList)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutorService (java.util.concurrent.ExecutorService)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 MBeanException (javax.management.MBeanException)1 ReflectionException (javax.management.ReflectionException)1