Search in sources :

Example 1 with PojoMetadata

use of org.apache.felix.ipojo.parser.PojoMetadata 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 PojoMetadata

use of org.apache.felix.ipojo.parser.PojoMetadata 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 PojoMetadata

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

the class MBeanHandler method configure.

/**
 * Constructs the structure JmxConfigFieldMap and the Dynamic Mbean.
 *
 * @param metadata the component metadata
 * @param dict the instance configuration
 */
public void configure(Element metadata, Dictionary dict) {
    PojoMetadata manipulation = getPojoMetadata();
    m_instanceManager = getInstanceManager();
    m_jmxConfigFieldMap = new JmxConfigFieldMap();
    // Build the hashmap
    Element[] mbeans = metadata.getElements(JMX_CONFIG_ELT, m_namespace);
    if (mbeans == null || mbeans.length == 0) {
        mbeans = metadata.getElements(JMX_CONFIG_ALT_ELT, m_namespace);
    }
    if (mbeans.length != 1) {
        error("A component must have exactly one " + JMX_CONFIG_ELT + " or " + JMX_CONFIG_ALT_ELT + " element.");
        error("The JMX handler configuration is ignored.");
        return;
    }
    Element mbean = mbeans[0];
    // retrieve kind of MBeanServer to use
    m_usesMOSGi = Boolean.parseBoolean(mbean.getAttribute(JMX_USES_MOSGI_ELT));
    // retrieve object name
    m_completeObjNameElt = mbean.getAttribute(JMX_OBJ_NAME_ELT);
    m_domainElt = mbean.getAttribute(JMX_OBJ_NAME_DOMAIN_ELT);
    m_objNameWODomainElt = mbean.getAttribute(JMX_OBJ_NAME_WO_DOMAIN_ELT);
    // test if Pojo is interested in registration callbacks
    m_registerCallbacks = manipulation.isInterfaceImplemented(MBeanRegistration.class.getName());
    if (m_registerCallbacks) {
        // don't need to check that methods exist, the pojo implements
        // MBeanRegistration interface
        String[] preRegisterParams = { MBeanServer.class.getName(), ObjectName.class.getName() };
        m_preRegisterMeth = manipulation.getMethod(PRE_REGISTER_METH_NAME, preRegisterParams);
        String[] postRegisterParams = { Boolean.class.getName() };
        m_postRegisterMeth = manipulation.getMethod(POST_REGISTER_METH_NAME, postRegisterParams);
        m_preDeregisterMeth = manipulation.getMethod(PRE_DEREGISTER_METH_NAME, new String[0]);
        m_postDeregisterMeth = manipulation.getMethod(POST_DEREGISTER_METH_NAME, new String[0]);
    }
    // set property
    Element[] attributes = mbean.getElements(JMX_PROPERTY_ELT, m_namespace);
    Element[] attributesAlt = mbean.getElements(JMX_PROPERTY_ELT_ALT, m_namespace);
    List<Element> listOfAttributes = new ArrayList<Element>();
    if (attributes != null) {
        listOfAttributes.addAll(Arrays.asList(attributes));
    }
    if (attributesAlt != null) {
        listOfAttributes.addAll(Arrays.asList(attributesAlt));
    }
    Element[] attributesOld = mbeans[0].getElements(JMX_PROPERTY_ELT);
    if (attributesOld != null) {
        warn("The JMX property element should use the '" + m_namespace + "' namespace.");
        listOfAttributes.addAll(Arrays.asList(attributesOld));
    }
    for (Element attribute : listOfAttributes) {
        boolean notif = false;
        String rights;
        String name;
        String field = attribute.getAttribute(JMX_FIELD_ELT);
        if (attribute.containsAttribute(JMX_NAME_ELT)) {
            name = attribute.getAttribute(JMX_NAME_ELT);
        } else {
            name = field;
        }
        if (attribute.containsAttribute(JMX_RIGHTS_ELT)) {
            rights = attribute.getAttribute(JMX_RIGHTS_ELT);
        } else {
            rights = "r";
        }
        PropertyField property = new PropertyField(name, field, rights, getTypeFromAttributeField(field, manipulation));
        if (attribute.containsAttribute(JMX_NOTIFICATION_ELT)) {
            notif = Boolean.parseBoolean(attribute.getAttribute(JMX_NOTIFICATION_ELT));
        }
        property.setNotifiable(notif);
        if (notif) {
            // add the new notifiable property in structure
            NotificationField notification = new NotificationField(name, this.getClass().getName() + "." + field, null);
            m_jmxConfigFieldMap.addNotificationFromName(name, notification);
        }
        m_jmxConfigFieldMap.addPropertyFromName(name, property);
        getInstanceManager().register(manipulation.getField(field), this);
        info("property exposed:" + name + " " + field + ":" + getTypeFromAttributeField(field, manipulation) + " " + rights + ", Notif=" + notif);
    }
    // set methods
    Element[] methods = mbean.getElements(JMX_METHOD_ELT, m_namespace);
    Element[] methodsAlt = mbean.getElements(JMX_METHOD_ELT_ALT, m_namespace);
    List<Element> listOfMethods = new ArrayList<Element>();
    if (methods != null) {
        listOfMethods.addAll(Arrays.asList(methods));
    }
    if (methodsAlt != null) {
        listOfMethods.addAll(Arrays.asList(methodsAlt));
    }
    Element[] methodsOld = mbeans[0].getElements(JMX_PROPERTY_ELT);
    if (methodsOld != null) {
        warn("The JMX method element should use the '" + m_namespace + "' namespace.");
        listOfMethods.addAll(Arrays.asList(methodsOld));
    }
    for (Element method : listOfMethods) {
        String name = method.getAttribute(JMX_NAME_ELT);
        if (name == null) {
            name = method.getAttribute("method");
        }
        String description = null;
        if (method.containsAttribute(JMX_DESCRIPTION_ELT)) {
            description = method.getAttribute(JMX_DESCRIPTION_ELT);
        }
        MethodField[] meth = getMethodsFromName(name, manipulation, description);
        for (int j = 0; j < meth.length; j++) {
            m_jmxConfigFieldMap.addMethodFromName(name, meth[j]);
            info("method exposed:" + meth[j].getReturnType() + " " + name);
        }
    }
}
Also used : Element(org.apache.felix.ipojo.metadata.Element) ObjectName(javax.management.ObjectName) PojoMetadata(org.apache.felix.ipojo.parser.PojoMetadata) MBeanServer(javax.management.MBeanServer)

Example 4 with PojoMetadata

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

the class PropertiesHandler method configure.

/**
 * This method is the first to be invoked.
 * This method aims to configure the handler. It receives the component type metadata and the instance
 * configuration. The method parses given metadata and registers fields to inject.
 *
 * Step 3 : when the instance configuration contains the properties.file property, it overrides the properties file location.
 *
 * @param metadata : component type metadata
 * @param configuration : instance description
 * @throws ConfigurationException : the configuration of the handler has failed.
 */
@SuppressWarnings("unchecked")
public void configure(Element metadata, Dictionary configuration) throws ConfigurationException {
    // Parse metadata to get <properties file="$file"/>
    // Get all elements to configure the handler
    Element[] elem = metadata.getElements("properties", NAMESPACE);
    switch(elem.length) {
        case 0:
            // It actually happen only if you force the handler to be plugged.
            throw new ConfigurationException("No properties found");
        case 1:
            // One 'properties' found, get attributes.
            m_file = elem[0].getAttribute("file");
            if (m_file == null) {
                // if file is null, throw a configuration error.
                throw new ConfigurationException("Malformed properties element : file attribute must be set");
            }
            break;
        default:
            // To simplify we handle only one properties element.
            throw new ConfigurationException("Only one properties element is supported");
    }
    // Look if the instance overrides file location :
    String instanceFile = (String) configuration.get("properties.file");
    if (instanceFile != null) {
        m_file = instanceFile;
    }
    // Load properties
    try {
        loadProperties();
    } catch (IOException e) {
        throw new ConfigurationException("Error when reading the " + m_file + " file : " + e.getMessage());
    }
    // Register fields
    // By convention, properties file entry are field name, so look for each property to get field list.
    // First get Pojo Metadata metadata :
    PojoMetadata pojoMeta = getPojoMetadata();
    Enumeration e = m_properties.keys();
    while (e.hasMoreElements()) {
        String field = (String) e.nextElement();
        FieldMetadata fm = pojoMeta.getField(field);
        if (fm == null) {
            // The field does not exist
            throw new ConfigurationException("The field " + field + " is declared in the properties file but does not exist in the pojo");
        }
        // Then check that the field is a String field
        if (!fm.getFieldType().equals(String.class.getName())) {
            throw new ConfigurationException("The field " + field + " exists in the pojo, but is not a String");
        }
        // All checks are ok, register the interceptor.
        getInstanceManager().register(fm, this);
    }
// Finally register the field to listen
}
Also used : Enumeration(java.util.Enumeration) FieldMetadata(org.apache.felix.ipojo.parser.FieldMetadata) ConfigurationException(org.apache.felix.ipojo.ConfigurationException) Element(org.apache.felix.ipojo.metadata.Element) PojoMetadata(org.apache.felix.ipojo.parser.PojoMetadata) IOException(java.io.IOException)

Example 5 with PojoMetadata

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

the class ProvidedServiceHandlerTest method testServiceDetectionSuperSuperClass.

public void testServiceDetectionSuperSuperClass() throws ConfigurationException {
    String classname = "org.apache.felix.ipojo.handlers.providedservice.ComponentTestWithAnotherSuperClass";
    Element metadata = new Element("component", "");
    Element manipulation = new Element("manipulation", "");
    metadata.addAttribute(new Attribute("classname", classname));
    Element provides = new Element("provides", "");
    provides.addAttribute(new Attribute("specifications", "java.beans.FeatureDescriptor"));
    metadata.addElement(provides);
    metadata.addElement(manipulation);
    manipulation.addAttribute(new Attribute("classname", classname));
    manipulation.addAttribute(new Attribute("super", "java.beans.MethodDescriptor"));
    Mockito.when(factory.getPojoMetadata()).thenReturn(new PojoMetadata(metadata));
    Mockito.when(factory.getClassName()).thenReturn(classname);
    handler.initializeComponentFactory(desc, metadata);
    System.out.println(metadata);
}
Also used : Attribute(org.apache.felix.ipojo.metadata.Attribute) Element(org.apache.felix.ipojo.metadata.Element) PojoMetadata(org.apache.felix.ipojo.parser.PojoMetadata)

Aggregations

PojoMetadata (org.apache.felix.ipojo.parser.PojoMetadata)15 Element (org.apache.felix.ipojo.metadata.Element)14 ConfigurationException (org.apache.felix.ipojo.ConfigurationException)6 Attribute (org.apache.felix.ipojo.metadata.Attribute)6 MethodMetadata (org.apache.felix.ipojo.parser.MethodMetadata)6 FieldMetadata (org.apache.felix.ipojo.parser.FieldMetadata)5 PropertyDescription (org.apache.felix.ipojo.architecture.PropertyDescription)3 Filter (org.osgi.framework.Filter)2 Event (org.osgi.service.event.Event)2 IOException (java.io.IOException)1 Enumeration (java.util.Enumeration)1 MBeanServer (javax.management.MBeanServer)1 ObjectName (javax.management.ObjectName)1 Pojo (org.apache.felix.ipojo.Pojo)1 Callback (org.apache.felix.ipojo.util.Callback)1 BundleContext (org.osgi.framework.BundleContext)1 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)1