All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sun.jbi.management.config.RuntimeConfiguration Maven / Gradle / Ivy

Go to download

JBI Runtime Management components, providing installation, deployment, and other JMX interfaces for remote management consoles.

There is a newer version: 2.4.3
Show newest version
/*
 * BEGIN_HEADER - DO NOT EDIT
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://open-esb.dev.java.net/public/CDDLv1.0.html.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * HEADER in each file and include the License file at
 * https://open-esb.dev.java.net/public/CDDLv1.0.html.
 * If applicable add the following below this CDDL HEADER,
 * with the fields enclosed by brackets "[]" replaced with
 * your own identifying information: Portions Copyright
 * [year] [name of copyright owner]
 */

/*
 * @(#)RuntimeConfiguration.java
 * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
 *
 * END_HEADER - DO NOT EDIT
 */
package com.sun.jbi.management.config;

import com.sun.jbi.EnvironmentContext;
import com.sun.jbi.StringTranslator;
import com.sun.jbi.platform.PlatformContext;
import com.sun.jbi.management.ConfigurationCategory;
import com.sun.jbi.management.LocalStringKeys;
import com.sun.jbi.management.message.MessageBuilder;
import com.sun.jbi.management.system.ManagementContext;
import com.sun.jbi.management.system.ManagementException;
import com.sun.jbi.management.registry.GenericQuery;
import com.sun.jbi.management.registry.Updater;
import com.sun.jbi.management.registry.xml.RegistryDocument;
import com.sun.jbi.management.util.StringHelper;


import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.Descriptor;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.ObjectName;
import javax.management.ReflectionException;

// Notification classes
import javax.management.NotificationListener;
import javax.management.NotificationFilter;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanNotificationInfo;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanServerConnection;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanConstructorInfo;
import javax.management.modelmbean.ModelMBeanNotificationInfo;
import javax.management.modelmbean.ModelMBeanOperationInfo;

/**
 * This is the basic RuntimeConfiguration MBean. It is a dynamic model MBean.
 * 
 * @author Sun Microsystems, Inc.
 */
public class RuntimeConfiguration 
    extends  javax.management.modelmbean.RequiredModelMBean
    implements javax.management.NotificationEmitter, com.sun.jbi.util.Constants
{
    
    /** Message Builder */
    protected static MessageBuilder            sMsgBuilder;
        
    /** Context information */
    protected      PlatformContext           mPlatformCtx;
    private static EnvironmentContext        sEnvCtx;
    private        ManagementContext         mMgtCtx;    
    private static StringTranslator          sTranslator;
    private static Logger                    sLog;
    protected      ConfigurationCategory     mCategory;
    protected      String                    mTarget;
    private static boolean                   isGlobalAttribSetInited;
    
    // -- Listeners interested in notifications from this MBean
    protected            List mListeners;
    protected static     MBeanNotificationInfo[]   sNotificationInfo = null;
        
    /** Primitive types to their class object mapping */
    protected static HashMap sTypeMap;
   
    private static String MASKED_ATTRIB_VALUE = "*******";

    /** notification sequence number */
    private long mSeqNumber = 0;
    
    static 
    {
        initPrimitiveTypeMap();
        initNotificationInfos();
    }
    
    /** Creates a new RuntimeConfiguration MBean.
     *  @param mbeanInfo metadata returned by the 'real' MBean in the 
     *   target instance.
     *  @param mbeanName name of this MBean registered in the DAS.
     */
    public RuntimeConfiguration(ModelMBeanInfo mbeanInfo, ConfigurationCategory category,
        String target)
        throws Exception
    {
       
        super(mbeanInfo);
        sMsgBuilder = new MessageBuilder(getTranslator());
        mCategory = category;
        mTarget = ( target == null ? getPlatformContext().getTargetName() : target );
    }
    
    /*---------------------------------------------------------------------------------*\
     *                   Dynamic MBean Attribute getters/setters                       *
    \*---------------------------------------------------------------------------------*/
    
    /**
     * Obtain the value of a specific attribute of the Dynamic MBean.
     *
     * @param attribute The name of the attribute to be retrieved
     * @return The value of the attribute retrieved.
     * @exception AttributeNotFoundException
     * @exception MBeanException  Wraps a java.lang.Exception 
     *           thrown by the MBean's getter.
     * @exception ReflectionException  Wraps a java.lang.Exception
     *            thrown while trying to invoke the getter.
     * @see #setAttribute
     */
    public Object getAttribute(String attribute) 
        throws AttributeNotFoundException, MBeanException, ReflectionException 
    {
        Object regValue = null;
        
        /**
         * We get the com.sun.jbi log level from the platform, this is not
         * a very clean solution, but is the only solution. The "com.sun.jbi" 
         * logger is not persisted in the JBI runtime, it is the platforms 
         * responsibility right now.  ~ Nikita
         */
        if ( attribute.equalsIgnoreCase(getPlatformContext().JBI_LOGGER_NAME))
        {
            return getJbiLogLevel();
        }
        
        /**
         * If the framework is ready ( i.e. JAXB initialized ) get the attribute from
         * the JAXB model
         *
         * If framework not ready then get the attribute from the registry using DOM/XPath
         *
         * If the attribute is not defined in the registry ( for target or global domain config )
         * the return the default value of the attribute, the domain setting has not been 
         * updated and is identical to the default
         */
        try
        {
            String strValue = null;
            if ( getEnvironmentContext().isFrameworkReady(false))
            {
                // Initialization complete can use registry
                strValue = getRegistry().getGenericQuery().getAttribute(mTarget, mCategory, attribute);
            }
            else
            {
                // Get the attribute from the registry using DOM
                RegistryDocument regDoc = new RegistryDocument(
                    getEnvironmentContext().getReadOnlyRegistry());

                strValue = regDoc.getConfigurationAttribute(mTarget, mCategory, attribute);
            }
            
            ModelMBeanAttributeInfo attribInfo = getAttributeInfo(attribute);
            
            if ( isPassword(attribute) )
            {
                // No need to decrypt and return clear text. Mask the value
                regValue =  MASKED_ATTRIB_VALUE;
            }
            else if ( attribInfo != null && strValue != null )
            {
                regValue = (Object) StringHelper.convertStringToType( attribInfo.getType(), strValue );
            }
            
            
            if ( regValue == null )
            {
                // Get the factory default value
                if ( attribInfo != null )
                {
                    Descriptor descr = attribInfo.getDescriptor();
                    regValue = descr.getFieldValue("default");
                }
            }
            
            /** 
             * If we are getting a runtime logger and target is a cluster 
             * or "domain" and it's value is DEFAULT
             * get the actual runtime value i.e. get the com.sun.jbi logger
             * from the platform.
             *
             * For standalone/clustered servers we get the actual logger
             * level, from the instance MBean so this is not required.  
             */
            if ( mCategory.equals(ConfigurationCategory.Logger ) )
            {
                if ( LOG_LEVEL_DEFAULT.equals(regValue) &&
                     !getPlatformContext().isStandaloneServer(mTarget) &&
                     !getPlatformContext().isClusteredServer(mTarget)  )
                {
                    
                    regValue = getJbiLogLevel();
                }
            }
           
        }
        catch (Exception ex)
        {
            javax.jbi.JBIException jbiEx;
            try
            {
                 jbiEx = new javax.jbi.JBIException(
                        sMsgBuilder.buildExceptionMessage("getAttribute", ex));
            }
            catch ( ManagementException mex )
            {
                jbiEx = new javax.jbi.JBIException(ex.getMessage());
            }
            throw new MBeanException(jbiEx);
        }
        
        if ( regValue == null )
        {
            throw new AttributeNotFoundException(attribute);
        }
        else
        {
            return regValue;
        }
    }
    
    /**
     * Sets the values of several attributes of the Dynamic MBean.
     * 
     * @param attributes A list of attributes: The identification of the
     *        attributes to be set and  the values they are to be set to.
     * @return The list of attributes that were set, with their new values.
     * @see #getAttributes
     */
    public AttributeList setAttributes(AttributeList attributes) 
    {
        AttributeList updatedAttributes = new AttributeList();
        
        for (Object attribute : attributes) {
            Attribute attr = (Attribute) attribute;
            try
            {
                setAttribute(attr);
                updatedAttributes.add(attr);
            }
            catch ( Exception ex )
            {
                // Log exception that attribute name could not be set
                String errMsg = getTranslator().getString(
                        LocalStringKeys.CS_SET_ATTRIBUTE_FAILED, attr.getName(), 
                        attr.getValue(), ex.getMessage());
                getLogger().warning(errMsg);
                continue;
            }
        }
        return updatedAttributes;
    }
    
    
    /**
     * Get the values of several attributes of the Dynamic MBean.
     * 
     * @param attributeNames A list of the attributes to be retrieved.
     * @return The list of attributes retrieved.
     * @see #setAttributes
     */
    public AttributeList getAttributes(String[] attributeNames) 
    {
        AttributeList list = new AttributeList();
        
        for (String attrName : attributeNames)
        {
            try
            {
                Object attrValue = getAttribute(attrName);
                list.add( new Attribute(attrName, attrValue) );
            }
            catch ( Exception ex )
            {
                // Log the exception that attrName could not be retrieved
                String errMsg = getTranslator().getString(
                    LocalStringKeys.CS_GET_ATTRIBUTE_FAILED, attrName, ex.getMessage());
                getLogger().fine(errMsg);
                continue;
            }
        }
        
        return list;
    }
    
    /**
     * Allows an action to be invoked on the Dynamic MBean.
     * 
     * @param actionName The name of the action to be invoked.
     * @param params An array containing the parameters to be set when the 
     *        action is invoked.
     * @param signature An array containing the signature of the action. The 
     *        class objects will be loaded through the same class loader as the
     *        one used for loading the MBean on which the action is invoked.
     * @return The object returned by the action, which represents the result of
     *         invoking the action on the MBean specified.
     * @exception MBeanException  Wraps a java.lang.Exception thrown
     *            by the MBean's invoked method.
     * @exception ReflectionException  Wraps a java.lang.Exception 
     *            thrown while trying to invoke the method
     */
    public Object invoke(String actionName, Object[] params, String[] signature) 
        throws MBeanException, ReflectionException 
    {
        if ( actionName.equals("persist") )
        {
            try
            {
                this.persist();
            }
            catch(Exception ex)
            {
                javax.jbi.JBIException jbiEx;
                try
                {
                    jbiEx = new javax.jbi.JBIException(sMsgBuilder.buildExceptionMessage("invoke", ex));
                }
                catch(ManagementException mex)
                {
                   jbiEx = new  javax.jbi.JBIException(ex.getMessage());
                }
                        
                throw new MBeanException(jbiEx);
            }
            return new Object();
        }
        else
            if ( actionName.equals("deleteOverride") )
            {
                try
                {
                    if ( params.length < 1 || signature.length < 1 )
                    {
                        throw new Exception("Insufficient parameters");
                    }
                    
                    if ( !(params[0] instanceof java.lang.String) )
                    {
                        throw new Exception("Incorrect type " 
                            + params[0].getClass().getName());
                    }
                    
                    if ( params.length > 0 )
                    {
                        this.deleteOverride( (String) params[0]);
                    }
                }
                catch(Exception ex)
                {
                    javax.jbi.JBIException jbiEx;
                    try
                    {
                        jbiEx = new javax.jbi.JBIException(
                            sMsgBuilder.buildExceptionMessage("deleteOverride", ex));
                    }
                    catch ( ManagementException mex )
                    {
                        jbiEx = new javax.jbi.JBIException(ex.getMessage());
                    }
                    throw new MBeanException(jbiEx);
                }
                // ??
                return new Object();
            }
            else
            {
                throw new UnsupportedOperationException("invoke");
            }
    }
    
    /**
     *
     */
    public static ModelMBeanInfo createMBeanInfo(ModelMBeanAttributeInfo[] attributeInfos)
        throws Exception
    {
        // -- Introspect each and every attribute info
        //    (a) Check if all required fields are present in descriptor
        checkMBeanAttributeInfos(attributeInfos);
        ModelMBeanInfo mbeanInfo = null;

        ModelMBeanConstructorInfo[]  constructorInfos   = new ModelMBeanConstructorInfo[0];    
        ModelMBeanOperationInfo[]    operationInfos     = new ModelMBeanOperationInfo[0];
        
        MBeanNotificationInfo[] mbeanNotInfos = initNotificationInfos();
        ModelMBeanNotificationInfo[]  notificationInfos 
                    = new ModelMBeanNotificationInfo[mbeanNotInfos.length];
        
        int i = 0;
        for ( MBeanNotificationInfo mbeanNotInfo : mbeanNotInfos )
        {
            notificationInfos[i] = new ModelMBeanNotificationInfo(
                    mbeanNotInfo.getNotifTypes(),
                    mbeanNotInfo.getName(),
                    mbeanNotInfo.getDescription());
            i++;
        }

        mbeanInfo = new ModelMBeanInfoSupport(
            "com.sun.jbi.management.facade.RuntimeConfigurationMBean.class", 
            "Runtime Configuration MBean",
            attributeInfos, 
            constructorInfos, 
            operationInfos, 
            notificationInfos);
        return mbeanInfo;
    }
    
    /*---------------------------------------------------------------------------------*\
     *                   Protected operations                                          *
    \*---------------------------------------------------------------------------------*/
    
    /**
     * This operations checks :
     *
     *  (a) If an attribute with the same identification exists in the current configuration
     *  (b) If the type of the value passed matches the expected value.
     *
     * @param     attribute - the attribute to be validated
     * @exception AttributeNotFoundException if attribute with the same identification
     *            is not present in the configuration set.
     * @exception InvalidAttributeValueException if the type of the attribute is different
     *            from what is expected.
     */
    protected void checkIsValidAttribute(Attribute attribute)
        throws javax.management.AttributeNotFoundException, 
            javax.management.InvalidAttributeValueException, 
            javax.management.MBeanException
    {
        String attrName  = attribute.getName();
        Object attrValue = attribute.getValue();
   
        String type = getMatchingAttribute(attrName);
        if ( type != null )
        {
            if ( attrValue != null )
            {
                if ( !( type.equals(attrValue.getClass().getName()) ) )
                {
                    String errMsg = getTranslator().getString(
                        LocalStringKeys.CS_INVALID_ATTRIBUTE_VALUE, attrName, 
                            type, attrValue.getClass().getName());
                    throw new InvalidAttributeValueException(errMsg);
                }
            }
        }
        else
        {
                throw new AttributeNotFoundException(attrName);
        }
        
        // -- Check if can be updated
        checkIsWritable(attrName);
        
        // -- If there is a min value set, check value is above that
        checkLowerLimit(attrName, attrValue);
        
        // -- If there is a min value set, check value is below that
        checkUpperLimit(attrName, attrValue);
        
        // -- If there is a enum value set, check value is above that
        checkEnumRange(attrName, attrValue);
        
    }
    
    /**
     * @name - the identification of the attribute to look for
     * @return the type of the attribute from the MBeanAttributeInfo's for this MBean 
     *         if one with the same name exists. If a match is not found a null value is 
     *         returned.
     */
    protected String getMatchingAttribute(String name)
    {
        MBeanInfo mbeanInfo = this.getMBeanInfo();
        MBeanAttributeInfo[] attribInfos = mbeanInfo.getAttributes();
        String type = null;
        
        for ( MBeanAttributeInfo attribInfo : attribInfos )
        {
            if ( attribInfo.getName().equals(name) )
            {
                type = attribInfo.getType();
                
                if ( sTypeMap.containsKey(type) )
                {
                    type = (String) sTypeMap.get(type);
                }
            }
        }
        return type;
    }
    
     /**
      * @return the management string translator
      */
     protected static StringTranslator getTranslator()
     {
        if ( sTranslator == null )
        {
            com.sun.jbi.EnvironmentContext envCtx = com.sun.jbi.util.EnvironmentAccess.getContext();
            sTranslator = envCtx.getStringTranslator("com.sun.jbi.management");
        }
        return sTranslator;
     }
     
     /**
      * @return the management logger.
      */
     protected static Logger getLogger()
     {
         if ( sLog  == null )
         {
             sLog = Logger.getLogger("com.sun.jbi.management");
         }
         return sLog;
     }    
     
     /**
      * @return the management context
      */
     protected ManagementContext getManagementContext()
     {
         if ( mMgtCtx == null )
         {
             mMgtCtx = new ManagementContext(getEnvironmentContext());
         }
         return mMgtCtx;
     }
     
     /**
      * @return the platform context
      */
     protected PlatformContext getPlatformContext()
     {
         if ( mPlatformCtx == null )
         {
             mPlatformCtx = getEnvironmentContext().getPlatformContext();
         }
         return mPlatformCtx;
     }
     
     /**
      * @return the EnvironmentContext
      */
     protected static EnvironmentContext getEnvironmentContext()
     {
         if ( sEnvCtx == null )
         {
             sEnvCtx = com.sun.jbi.util.EnvironmentAccess.getContext();
         }
         return sEnvCtx;
     }
     
     /**
      * Persist the factory defaults to the registry for the global configuration.
      * This operation is invoked before any updates to the global/domain configuration,
      * so global configuration is equivalent to the factory defaults.
      *
      * This operation is invoked only on the domain facade MBean and the Global Configuration
      * MBean 
      */
     protected void persist()
        throws Exception
     {
        com.sun.jbi.management.registry.Registry registry = getRegistry();
        if ( registry != null )
        {
            Updater updater = registry.getUpdater();

            ModelMBeanAttributeInfo[] attribInfos = (ModelMBeanAttributeInfo[]) this.getMBeanInfo().getAttributes();

            for ( ModelMBeanAttributeInfo attribInfo : attribInfos )
            {
                javax.management.Descriptor descr = attribInfo.getDescriptor();
                
                String value = descr.getFieldValue("default").toString();
                String persistAttrValue = value;
                if ( isPassword(attribInfo.getName()) )
                {
                    com.sun.jbi.security.KeyStoreUtil 
                                ksUtil = getPlatformContext().getKeyStoreUtil();
                    persistAttrValue = ksUtil.encrypt(value);
                }
                updater.setAttribute("domain", mCategory, attribInfo.getName(), 
                    persistAttrValue);
            }
        }
     }
     
     /**
      * This operation is called when a configuration attribute is to use the
      * global configuration, the overriden attribute needs to be deleted from the
      * target configiration 
      *
      * @param attrName - attribute to be deleted
      */
     protected void deleteOverride(String attrName)
        throws Exception
     {
         
     }
         
    /**
     * @param attribName - identification of the attribute
     * @return the ModelMBeanAttributeInfo for the specified attribute
     */
    protected ModelMBeanAttributeInfo getAttributeInfo(String attribute)
        throws javax.management.MBeanException
    {
        ModelMBeanInfo  mbeanInfo = (ModelMBeanInfo) this.getMBeanInfo();
        ModelMBeanAttributeInfo attribInfo = null;
        if ( mbeanInfo != null )
        {
            attribInfo = mbeanInfo.getAttribute(attribute);
        }
        return attribInfo;
    }
    
    /**
     * Get a handle to the registry
     *
     * @return the persisted registry instance
     */
    protected com.sun.jbi.management.registry.Registry getRegistry()
    {
        return (com.sun.jbi.management.registry.Registry) getEnvironmentContext().getRegistry();
    }
    
    
    /**
     * Persist the domain configuration if required.
     */
    protected void persistDomainConfig()
        throws MBeanException
    {
        try
        {
            // If the registry configs element is empty then add the domain configuration
            GenericQuery query = getRegistry().getGenericQuery();
            
            ObjectName configMBeanFilter = new ObjectName(
                "com.sun.jbi:Target=domain,ServiceName=ConfigurationService,*");
            
            if ( !(getEnvironmentContext().getPlatformContext().isAdminServer()) )
            {
                configMBeanFilter = new ObjectName(
                    "com.sun.jbi:JbiName=domain,ServiceName=ConfigurationService,*");
            }

            if ( !query.isGlobalConfigurationDefined() )
            {
                // Invoke persist() on domain configuration MBeans for all categories
                MBeanServerConnection mbns = getPlatformContext().getMBeanServerConnection(
                    getEnvironmentContext().getPlatformContext().getInstanceName());

                java.util.Set nameSet = mbns.queryNames(configMBeanFilter, null);

                ObjectName[] domainConfigMBeans =  nameSet.toArray(new ObjectName[nameSet.size()]);

                for ( ObjectName domainConfigMBean : domainConfigMBeans )
                {
                    mbns.invoke(domainConfigMBean, "persist", new Object[]{}, new String[]{});
                }
            }
        }
        catch ( Exception ex )
        {
            String errMsg = getTranslator().getString(
                LocalStringKeys.JBI_ADMIN_GLOBAL_CFG_PERSIST_FAILED,
                mCategory.toString(), ex.getMessage());
            javax.jbi.JBIException jbiEx = new javax.jbi.JBIException(errMsg);
            throw new MBeanException(jbiEx, errMsg);
        }
    }
    
    /**
     * @return true if the attribute is a password field, false otherwise
     */
    protected boolean isPassword(String attrName)
    {
        boolean isPassword = false;
        ModelMBeanAttributeInfo attribInfo = null;
        
        try
        {
            attribInfo = getAttributeInfo(attrName);
        }
        catch ( javax.management.MBeanException ex )
        {
            sLog.log(java.util.logging.Level.FINE, 
                    "Failed to get Attribute Info for " + attrName , ex );
        }
        
        if ( attribInfo != null )
        {
            javax.management.Descriptor descr = attribInfo.getDescriptor();
            Boolean isPwd = (Boolean) descr.getFieldValue(
                    DescriptorSupport.RequiredFieldName.IS_PASSWORD.getFieldName());
            
            isPassword = isPwd;
        }
        
        return isPassword;
    }

    /**
     * @return the listeners list
     */
    protected List getListeners()
    {
        if ( mListeners == null )
        {
            mListeners = new java.util.ArrayList();
        }
        return mListeners;
    }
    
         
    /**
     * Send the notification to all interested listeners
     *
     * @param attribute the attribute being updated.
     */
    protected void notifyListenersOfAttributeChange(Attribute attribute)
        throws Exception
     {
        getLogger().log(Level.FINE, "Notifying listeners of attribute change {0}", attribute.toString());
          
        //  Notify all listeners of the attribute change
        AttributeChangeNotification attribChangeNotif = new
                AttributeChangeNotification(
                this,
                mSeqNumber++,
                System.currentTimeMillis(),
                getTranslator().getString(LocalStringKeys.ATTRIBUTE_CHANGE_NOTIF_MSG),
                attribute.getName(),
                getAttributeInfo(attribute.getName()).getType(),
                getAttribute(attribute.getName()),
                attribute.getValue());
        
        for ( NotificationListenerInfo listener : getListeners() )
        {
            NotificationFilter filter = listener.getNotificationFilter();
            
            boolean sendNotif = true;
            if ( filter != null )
            {
                if ( !filter.isNotificationEnabled(attribChangeNotif))
                {
                    getLogger().log(Level.FINE, "Notification not enabled in listener {0}", attribute.toString());
                    sendNotif = false;
                }
            }
            
            if ( sendNotif )
            {
                getLogger().log(Level.FINE, "Notifying a listener of attribute change {0}", attribute.toString());
                listener.getNotificationListener().handleNotification(attribChangeNotif, 
                            listener.getHandback());
            }
        }
        
     }
         
    /*---------------------------------------------------------------------------------*\
     *                Notification Emitter  operations                                 *
    \*---------------------------------------------------------------------------------*/
    
    /**
     *    Adds a listener to this MBean.
     *
     *
     *   @param listener 
     *           The listener object which will handle the notifications
     *           emitted by the broadcaster.
     *   @param filter 
     *           The filter object. If filter is null, no filtering will be 
     *           performed before handling notifications.
     *   @param handback 
     *           An opaque object to be sent back to the listener when a 
     *           notification is emitted. This object cannot be used by the 
     *           Notification broadcaster object. It should be resent unchanged 
     *           with the notification to the listener. 
     *   @throws IllegalArgumentException - Listener parameter is null.
     */
    public void addNotificationListener(NotificationListener listener,
            NotificationFilter filter, Object handback) throws IllegalArgumentException
    {
        
        if ( listener == null )
        {
            throw new IllegalArgumentException();
        }
        
        getListeners().add(
                 new NotificationListenerInfo(listener, filter, handback));
    }
    
    /**
     *
     */
    public void removeNotificationListener(NotificationListener listener)
                                throws javax.management.ListenerNotFoundException
    {
        List listeners = getListeners();
        List listenersToRemove = new ArrayList();
        for ( NotificationListenerInfo listenerInfo : listeners )
        {
            if ( listenerInfo.getNotificationListener().equals(listener) )
            {
                listenersToRemove.add(listenerInfo);
            }
        }
        
        if ( listenersToRemove.isEmpty())
        {
            throw new javax.management.ListenerNotFoundException();
        }
        
        listeners.removeAll(listenersToRemove);
        

    }
    
    /**
     * Remove a specific listener from the set. One that matches the 
     * filter and handback
     */
    public void removeNotificationListener(NotificationListener listener,
                                NotificationFilter filter,
                                Object handback)
                                throws javax.management.ListenerNotFoundException
    {
        List listeners = getListeners();
        
        List listenersToRemove = new ArrayList();
        for ( NotificationListenerInfo listenerInfo : listeners )
        {
            if ( listenerInfo.getNotificationListener().equals(listener) )
            {
                boolean filterMatches  = false;
                boolean handbackMatches = false;
                if ( filter == null ) 
                {
                    filterMatches =
                            ((listenerInfo.getNotificationFilter() == null) ? true : false);
                }
                else
                {
                    filterMatches = 
                        filter.equals(listenerInfo.getNotificationFilter());
                }
                
                
                if ( handback == null ) 
                {
                    handbackMatches =
                            ((listenerInfo.getHandback() == null) ? true : false);
                }
                else
                {
                    handbackMatches = 
                        handback.equals(listenerInfo.getHandback());
                }
                
                if ( filterMatches && handbackMatches )
                {
                    listenersToRemove.add(listenerInfo);
                }
            }
        }
        
        if ( listenersToRemove.isEmpty())
        {
            throw new javax.management.ListenerNotFoundException();
        }
        
        listeners.removeAll(listenersToRemove);
    }
    
    /**
     *
     */
    public MBeanNotificationInfo[] getNotificationInfo()
    {
        return initNotificationInfos();
    }
    
    /*---------------------------------------------------------------------------------*\
     *                      Private operations                                         *
    \*---------------------------------------------------------------------------------*/
    
    private static MBeanNotificationInfo[]  initNotificationInfos()
    {
        if ( sNotificationInfo == null )
        {
            sNotificationInfo = new MBeanNotificationInfo[1];
            
            sNotificationInfo[0] = new 
                     MBeanNotificationInfo(
                        new String[]{AttributeChangeNotification.ATTRIBUTE_CHANGE},
                        "javax.management.AttributeChangeNotification",
                        getTranslator().getString(LocalStringKeys.ATTRIBUTE_CHANGE_NOTIF_MSG));
        }
        return sNotificationInfo;
    }
    /**
     * Initialize the data structure which maps primitive types to their wrapper classes
     */
    private static void initPrimitiveTypeMap() 
    {
       sTypeMap = new HashMap();
       sTypeMap.put("int"    ,"java.lang.Integer");
       sTypeMap.put("float"  ,"java.lang.Float");
       sTypeMap.put("long"   ,"java.lang.Long");
       sTypeMap.put("double" ,"java.lang.Double");
       sTypeMap.put("byte"   ,"java.lang.Byte");
       sTypeMap.put("char"   ,"java.lang.Character");
       sTypeMap.put("boolean","java.lang.Boolean");
       sTypeMap.put("short"  ,"java.lang.Short");
    }
    
    
    /**
     * Checks the descriptopr of each and every MBeanArributeInfo. 
     * 
     * @exception ManagementException if the descriptor is null or invalid.
     */
    private static void checkMBeanAttributeInfos(ModelMBeanAttributeInfo[] mbeanAttrInfos)
        throws ManagementException
    {
        for ( ModelMBeanAttributeInfo attribInfo : mbeanAttrInfos )
        {
            Descriptor descr = attribInfo.getDescriptor();
            
            if ( descr == null )
            {
                String[] params = new String[]{attribInfo.getName()};
                String errMsg = getTranslator().getString(
                    LocalStringKeys.CS_ATTRIBUTE_DESCR_NULL,
                    params);   
                throw new ManagementException(sMsgBuilder.buildFrameworkMessage(
                    "checkMBeanAttributeInfos", MessageBuilder.TaskResult.FAILED, 
                    MessageBuilder.MessageType.ERROR,
                    MessageBuilder.getMessageString(errMsg), 
                    params,
                    MessageBuilder.getMessageToken(errMsg)));
            }
            
            if ( !descr.isValid() )
            {
                String[] params = new String[]{attribInfo.getName()};
                String errMsg = getTranslator().getString(
                    LocalStringKeys.CS_ATTRIBUTE_DESCR_INVALID,
                    params);   
                throw new ManagementException(sMsgBuilder.buildFrameworkMessage(
                    "checkMBeanAttributeInfos", MessageBuilder.TaskResult.FAILED, 
                    MessageBuilder.MessageType.ERROR,
                    MessageBuilder.getMessageString(errMsg), 
                    params,
                    MessageBuilder.getMessageToken(errMsg)));
            }
        }
    }  
    
    
    /**
     * @return true if the configuration MBean allows attributes of type to be 
     *         null.
     */
    private boolean canValueBeNull(String type)
    {
        boolean canBeNull = false;
        
        if ( "java.util.logging.Level".equals(type))
        {
            canBeNull = true;
        }
        
        return canBeNull;
    }
    
    /**
     * @return the "com.sun.jbi" log level as String.
     */
    private String getJbiLogLevel()
    {
        java.util.logging.Level level = getPlatformContext().getJbiLogLevel(mTarget);

        if ( level != null )
        {
            return level.toString();
        }
        else
        {
            // Get the domain logger if that is null too return INFO
            level = getPlatformContext().getJbiLogLevel("domain");

            if ( level != null )
            {
                return level.toString();
            }
            else
            {
                return java.util.logging.Level.INFO.toString();
            }
        }
    }
    
    /**
     * Check if the value of the attribute is greater than the minimum value.
     *
     * @param attrName - attribute name
     * @param attrValue - attribute value
     * @throws javax.management.InvalidAttributeValueException if attribute 
     * value less than minimum value
     */
    private void checkLowerLimit(String attrName, Object attrValue)
        throws javax.management.InvalidAttributeValueException,
            javax.management.MBeanException
    {
        ModelMBeanAttributeInfo attribInfo = getAttributeInfo(attrName);
        
        javax.management.Descriptor descr = attribInfo.getDescriptor();
                
        Object minValue =  descr.getFieldValue(
                DescriptorSupport.OptionalFieldName.MIN_VALUE.getFieldName());
        
        if ( minValue != null )
        {
            Object minValueObj = null;
            
            try
            {
                    
                minValueObj = StringHelper.convertStringToType(attribInfo.getType(), minValue.toString());
            }
            catch ( Exception ex)
            {
                String[] params = { minValue.toString(),  attribInfo.getType().toString(), ex.toString()};
                String errMsg = getTranslator().getString(LocalStringKeys.JBI_ADMIN_FAILED_MIN_VALUE_CONVERSION, params);
                String jbiMsg = errMsg;
                try
                {
                    jbiMsg = sMsgBuilder.buildFrameworkMessage(
                        "checkLowerLimit", MessageBuilder.TaskResult.FAILED, 
                        MessageBuilder.MessageType.ERROR,
                        MessageBuilder.getMessageString(errMsg), 
                        params,
                        MessageBuilder.getMessageToken(errMsg));
                }
                catch ( ManagementException mex ) {};
                
                throw new  javax.management.InvalidAttributeValueException(jbiMsg);
            }
            
            if ( minValueObj != null )
            {
                if ( (minValueObj instanceof Comparable) && (attrValue instanceof Comparable) )
                {
                    Comparable comparable = (Comparable) minValueObj;

                    int comparison = comparable.compareTo(attrValue);
                    
                    if ( comparison > 0 )
                    {
                        String[] params = { attrName, attrValue == null ? "null" : attrValue.toString(), minValueObj.toString()};
                        String errMsg = getTranslator().getString(LocalStringKeys.JBI_ADMIN_CONFIG_PARAM_LESS_THAN_MIN_VALUE, params);
                        String jbiMsg = errMsg;
                        
                        try
                        {
                        jbiMsg = sMsgBuilder.buildFrameworkMessage(
                            "checkLowerLimit", MessageBuilder.TaskResult.FAILED, 
                            MessageBuilder.MessageType.ERROR,
                            MessageBuilder.getMessageString(errMsg), 
                            params,
                            MessageBuilder.getMessageToken(errMsg));
                        }
                        catch ( ManagementException mex ) {};
                        
                        throw new  javax.management.InvalidAttributeValueException(jbiMsg);
                    }
                }
            }
        }
    }
        
    /**
     * Check if the value of the attribute is less than the maximum value.
     *
     * @param attrName - attribute name
     * @param attrValue - attribute value
     * @throws javax.management.InvalidAttributeValueException if attribute 
     * value is more than the maximum value
     */
    private void checkUpperLimit(String attrName, Object attrValue)
        throws javax.management.InvalidAttributeValueException,
            javax.management.MBeanException
    {
        ModelMBeanAttributeInfo attribInfo = getAttributeInfo(attrName);
        
        javax.management.Descriptor descr = attribInfo.getDescriptor();
        
        Object maxValue =  descr.getFieldValue(
                DescriptorSupport.OptionalFieldName.MAX_VALUE.getFieldName());
        
        if ( maxValue != null )
        {
            Object maxValueObj = null;
            
            try
            {
                    
                maxValueObj = StringHelper.convertStringToType(attribInfo.getType(), maxValue.toString());
            }
            catch ( Exception ex)
            {
                String[] params = { maxValue.toString(),  attribInfo.getType().toString(), ex.toString()};
                String errMsg = getTranslator().getString(LocalStringKeys.JBI_ADMIN_FAILED_MAX_VALUE_CONVERSION, params);
                String jbiMsg = errMsg;
                
                try
                {   sMsgBuilder.buildFrameworkMessage(
                        "checkUpperLimit", MessageBuilder.TaskResult.FAILED, 
                        MessageBuilder.MessageType.ERROR,
                        MessageBuilder.getMessageString(errMsg), 
                        params,
                        MessageBuilder.getMessageToken(errMsg));
                }
                catch ( ManagementException mex ) {};
                throw new  javax.management.InvalidAttributeValueException(jbiMsg);
            }
           
            if ( maxValueObj != null )
            {
                if ( (maxValueObj instanceof Comparable) && (attrValue instanceof Comparable) )
                {
                    Comparable comparable = (Comparable) maxValueObj;
                    int comparison = comparable.compareTo(attrValue);
                    
                    if ( comparison < 0 )
                    {
                        String[] params = { attrName, attrValue == null ? "null" : attrValue.toString() , maxValueObj.toString()};
                        String errMsg = sTranslator.getString(LocalStringKeys.JBI_ADMIN_CONFIG_PARAM_MORE_THAN_MAX_VALUE, params);
                        String jbiMsg = errMsg;
                        
                        try
                        {
                            jbiMsg = sMsgBuilder.buildFrameworkMessage(
                                "checkUpperLimit", MessageBuilder.TaskResult.FAILED, 
                                MessageBuilder.MessageType.ERROR,
                                MessageBuilder.getMessageString(errMsg), 
                                params,
                                MessageBuilder.getMessageToken(errMsg));   
                        }
                        catch ( ManagementException mex ) {};
                        
                        throw new  javax.management.InvalidAttributeValueException(jbiMsg);
                    }
                }
            }
            
        }
    }
        
    /**
     * Check if the value of the attribute is in the enumerated range.
     *
     * @param attrName - attribute name
     * @param attrValue - attribute value
     * @throws javax.management.InvalidAttributeValueException if attribute 
     * value is not in the specified enumeration
     */
    private void checkEnumRange(String attrName, Object attrValue)
        throws javax.management.InvalidAttributeValueException,
            javax.management.MBeanException
    {
        ModelMBeanAttributeInfo attribInfo = getAttributeInfo(attrName);
        
        javax.management.Descriptor descr = attribInfo.getDescriptor();
           
        String enumValue = (String) descr.getFieldValue(
                DescriptorSupport.OptionalFieldName.ENUM_VALUE.getFieldName());        
    
        if ( enumValue != null )
        {
            String[] values = convertEnumValuetoArray(enumValue);
            
            boolean found = false;
            for (String value : values )
            {
                if ( value.equals(attrValue) )
                {
                    found = true;
                }
            }
            
            if ( !found )
            {
                String[] params = { attrName, attrValue == null ? "null" : attrValue.toString(), enumValue};
                String errMsg = sTranslator.getString(LocalStringKeys.JBI_ADMIN_CONFIG_PARAM_OUT_OF_RANGE, params);
                String jbiMsg = errMsg;
                
                try
                {
                    jbiMsg = sMsgBuilder.buildFrameworkMessage(
                            
                        "checkEnumRange", MessageBuilder.TaskResult.FAILED, 
                        MessageBuilder.MessageType.ERROR,
                        MessageBuilder.getMessageString(errMsg), 
                        params,
                        MessageBuilder.getMessageToken(errMsg));
                }
                catch ( ManagementException mex ) {};
                throw new  javax.management.InvalidAttributeValueException(jbiMsg);
            }
        }
        
    }
    
    /**
     * Check if the attribute value can be updated.
     *
     * @param attrName - attribute name
     * @param attrValue - attribute value
     * @throws javax.management.InvalidAttributeValueException if attribute 
     * value is read-only
     */
    private void checkIsWritable(String attrName)
        throws javax.management.InvalidAttributeValueException,
            javax.management.MBeanException
    {
        ModelMBeanAttributeInfo attribInfo = getAttributeInfo(attrName);
        
        if ( !attribInfo.isWritable())
        {
            String[] params = { attrName };
            String errMsg = sTranslator.getString(LocalStringKeys.JBI_ADMIN_CONFIG_READ_ONLY_ATTRIBUTE, params);
            String jbiMsg = errMsg;
            
            try
            {
                jbiMsg = sMsgBuilder.buildFrameworkMessage(
            
                    "checkIsWritable", MessageBuilder.TaskResult.FAILED, 
                    MessageBuilder.MessageType.ERROR,
                    MessageBuilder.getMessageString(errMsg), 
                    params,
                    MessageBuilder.getMessageToken(errMsg));
            }
            catch ( ManagementException mex ) {};
            throw new  javax.management.InvalidAttributeValueException(jbiMsg);    
        }
    }
    
    /**
     * Convert the enum values string {value1, value2, ..} to a String array
     *
     * @param enumVlaue - enumeration range string {value1, value2, ..}
     * @return a String array that has all the values
     */
    private String[] convertEnumValuetoArray(String enumValue)
    {
        ArrayList values = new ArrayList();
        if ( enumValue != null )
        {
            enumValue = enumValue.trim();
            
            int start = enumValue.indexOf("{") + 1;
            int end = enumValue.indexOf("}");
            
            String csl = enumValue.substring(start, end);
            
            java.util.StringTokenizer strTok = new java.util.StringTokenizer(csl, ",");
            
            while ( strTok.hasMoreTokens() )
            {
                values.add(strTok.nextToken().trim());
            }
        }
        
        return values.toArray(new String[values.size()]);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy