⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 objectmbean.java

📁 mina是以Java实现的一个开源的网络程序框架
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at *  *      http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.mina.integration.jmx;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.beans.PropertyEditor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.SocketAddress;import java.util.ArrayList;import java.util.Collection;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ThreadPoolExecutor;import javax.management.Attribute;import javax.management.AttributeChangeNotification;import javax.management.AttributeList;import javax.management.AttributeNotFoundException;import javax.management.InstanceNotFoundException;import javax.management.ListenerNotFoundException;import javax.management.MBeanException;import javax.management.MBeanInfo;import javax.management.MBeanNotificationInfo;import javax.management.MBeanParameterInfo;import javax.management.MBeanRegistration;import javax.management.MBeanServer;import javax.management.Notification;import javax.management.NotificationFilter;import javax.management.NotificationListener;import javax.management.ObjectName;import javax.management.ReflectionException;import javax.management.RuntimeOperationsException;import javax.management.modelmbean.InvalidTargetObjectTypeException;import javax.management.modelmbean.ModelMBean;import javax.management.modelmbean.ModelMBeanAttributeInfo;import javax.management.modelmbean.ModelMBeanConstructorInfo;import javax.management.modelmbean.ModelMBeanInfo;import javax.management.modelmbean.ModelMBeanInfoSupport;import javax.management.modelmbean.ModelMBeanNotificationInfo;import javax.management.modelmbean.ModelMBeanOperationInfo;import ognl.ExpressionSyntaxException;import ognl.InappropriateExpressionException;import ognl.NoSuchPropertyException;import ognl.Ognl;import ognl.OgnlContext;import ognl.OgnlException;import ognl.OgnlRuntime;import ognl.TypeConverter;import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;import org.apache.mina.core.filterchain.IoFilter;import org.apache.mina.core.filterchain.IoFilterChain;import org.apache.mina.core.filterchain.IoFilterChainBuilder;import org.apache.mina.core.service.IoAcceptor;import org.apache.mina.core.service.IoHandler;import org.apache.mina.core.service.IoService;import org.apache.mina.core.service.TransportMetadata;import org.apache.mina.core.session.IoSession;import org.apache.mina.core.session.IoSessionDataStructureFactory;import org.apache.mina.filter.executor.ExecutorFilter;import org.apache.mina.integration.beans.CollectionEditor;import org.apache.mina.integration.beans.ListEditor;import org.apache.mina.integration.beans.MapEditor;import org.apache.mina.integration.beans.PropertyEditorFactory;import org.apache.mina.integration.beans.SetEditor;import org.apache.mina.integration.ognl.IoFilterPropertyAccessor;import org.apache.mina.integration.ognl.IoServicePropertyAccessor;import org.apache.mina.integration.ognl.IoSessionPropertyAccessor;import org.apache.mina.integration.ognl.PropertyTypeConverter;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * A {@link ModelMBean} wrapper implementation for a POJO. *  * @author The Apache MINA Project (dev@mina.apache.org) * @version $Rev: 755515 $, $Date: 2009-03-18 10:02:54 +0100 (Wed, 18 Mar 2009) $ *  * @param <T> the type of the managed object */public class ObjectMBean<T> implements ModelMBean, MBeanRegistration {    private static final Map<ObjectName, Object> sources =        new ConcurrentHashMap<ObjectName, Object>();        public static Object getSource(ObjectName oname) {        return sources.get(oname);    }        static {        OgnlRuntime.setPropertyAccessor(IoService.class, new IoServicePropertyAccessor());        OgnlRuntime.setPropertyAccessor(IoSession.class, new IoSessionPropertyAccessor());        OgnlRuntime.setPropertyAccessor(IoFilter.class, new IoFilterPropertyAccessor());    }        protected final Logger logger = LoggerFactory.getLogger(getClass());    private final T source;    private final TransportMetadata transportMetadata;    private final MBeanInfo info;    private final Map<String, PropertyDescriptor> propertyDescriptors =        new HashMap<String, PropertyDescriptor>();    private final TypeConverter typeConverter = new OgnlTypeConverter();    private volatile MBeanServer server;    private volatile ObjectName name;    /**     * Creates a new instance with the specified POJO.     */    public ObjectMBean(T source) {        if (source == null) {            throw new NullPointerException("source");        }                this.source = source;                if (source instanceof IoService) {            transportMetadata = ((IoService) source).getTransportMetadata();        } else if (source instanceof IoSession) {            transportMetadata = ((IoSession) source).getTransportMetadata();        } else {            transportMetadata = null;        }                this.info = createModelMBeanInfo(source);    }        public final Object getAttribute(String fqan) throws AttributeNotFoundException,            MBeanException, ReflectionException {        try {            return convertValue(source.getClass(), fqan, getAttribute0(fqan), false);        } catch (AttributeNotFoundException e) {        } catch (Throwable e) {            throwMBeanException(e);        }        // Check if the attribute exist, if not throw an exception        PropertyDescriptor pdesc = propertyDescriptors.get(fqan);        if (pdesc == null) {            throwMBeanException(new IllegalArgumentException(                    "Unknown attribute: " + fqan));        }                try {            Object parent = getParent(fqan);            boolean writable = isWritable(source.getClass(), pdesc);                        return convertValue(                    parent.getClass(), getLeafAttributeName(fqan),                    getAttribute(source, fqan, pdesc.getPropertyType()),                    writable);        } catch (Throwable e) {            throwMBeanException(e);        }                throw new IllegalStateException();    }        public final void setAttribute(Attribute attribute)            throws AttributeNotFoundException, MBeanException,            ReflectionException {        String aname = attribute.getName();        Object avalue = attribute.getValue();                try {            setAttribute0(aname, avalue);        } catch (AttributeNotFoundException e) {        } catch (Throwable e) {            throwMBeanException(e);        }                PropertyDescriptor pdesc = propertyDescriptors.get(aname);        if (pdesc == null) {            throwMBeanException(new IllegalArgumentException(                    "Unknown attribute: " + aname));        }                try {            PropertyEditor e = getPropertyEditor(                    getParent(aname).getClass(),                    pdesc.getName(), pdesc.getPropertyType());            e.setAsText((String) avalue);            OgnlContext ctx = (OgnlContext) Ognl.createDefaultContext(source);            ctx.setTypeConverter(typeConverter);            Ognl.setValue(aname, ctx, source, e.getValue());        } catch (Throwable e) {            throwMBeanException(e);        }    }        public final Object invoke(String name, Object params[], String signature[])            throws MBeanException, ReflectionException {            // Handle synthetic operations first.        if (name.equals("unregisterMBean")) {            try {                server.unregisterMBean(this.name);                return null;            } catch (InstanceNotFoundException e) {                throwMBeanException(e);            }        }                try {            return convertValue(                    null, null, invoke0(name, params, signature), false);        } catch (NoSuchMethodException e) {        } catch (Throwable e) {            throwMBeanException(e);        }                // And then try reflection.        Class<?>[] paramTypes = new Class[signature.length];        for (int i = 0; i < paramTypes.length; i ++) {            try {                paramTypes[i] = getAttributeClass(signature[i]);            } catch (ClassNotFoundException e) {                throwMBeanException(e);            }                        PropertyEditor e = getPropertyEditor(                    source.getClass(), "p" + i, paramTypes[i]);            if (e == null) {                throwMBeanException(new RuntimeException("Conversion failure: " + params[i]));            }                        e.setValue(params[i]);            params[i] = e.getAsText();        }                try {            // Find the right method.            for (Method m: source.getClass().getMethods()) {                if (!m.getName().equalsIgnoreCase(name)) {                    continue;                }                Class<?>[] methodParamTypes = m.getParameterTypes();                if (methodParamTypes.length != params.length) {                    continue;                }                                Object[] convertedParams = new Object[params.length];                for (int i = 0; i < params.length; i ++) {                    if (Iterable.class.isAssignableFrom(methodParamTypes[i])) {                        // Generics are not supported.                        convertedParams = null;                        break;                    }                    PropertyEditor e = getPropertyEditor(source.getClass(), "p" + i, methodParamTypes[i]);                    if (e == null) {                        convertedParams = null;                        break;                    }                    e.setAsText((String) params[i]);                    convertedParams[i] = e.getValue();                }                if (convertedParams == null) {                    continue;                }                                return convertValue(                        m.getReturnType(), "returnValue",                        m.invoke(source, convertedParams), false);            }                        // No methods matched.            throw new IllegalArgumentException("Failed to find a matching operation: " + name);        } catch (Throwable e) {            throwMBeanException(e);        }                throw new IllegalStateException();    }    public final T getSource() {        return source;    }        public final MBeanServer getServer() {        return server;    }        public final ObjectName getName() {        return name;    }    public final MBeanInfo getMBeanInfo() {        return info;    }    public final AttributeList getAttributes(String names[]) {        AttributeList answer = new AttributeList();        for (int i = 0; i < names.length; i++) {            try {                answer.add(new Attribute(names[i], getAttribute(names[i])));            } catch (Exception e) {                // Ignore.            }        }        return answer;    }    public final AttributeList setAttributes(AttributeList attributes) {        // Prepare and return our response, eating all exceptions        String names[] = new String[attributes.size()];        int n = 0;        Iterator<Object> items = attributes.iterator();        while (items.hasNext()) {            Attribute item = (Attribute) items.next();            names[n++] = item.getName();            try {                setAttribute(item);            } catch (Exception e) {                ; // Ignore all exceptions            }        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -