Creates Jmx MBean for monitorables with operations and attributes.
333936
@Override
	public DynamicMBean createFor(List<?> monitorables, MBeanSettings setting, boolean enableRefresh) {
		checkNotNull(monitorables);
		checkArgument(monitorables.size() > 0, "Size of list of monitorables should be greater than 0");
		checkArgument(monitorables.stream().noneMatch(Objects::isNull), "Monitorable can not be null");
		checkArgument(CollectionUtils.allItemsHaveSameType(monitorables), "Monitorables should be of the same type");

		Object firstMBean = monitorables.get(0);
		Class<?> mbeanClass = firstMBean.getClass();

		boolean isRefreshEnabled = enableRefresh;

		List<MBeanWrapper> mbeanWrappers = new ArrayList<>(monitorables.size());
		if (ConcurrentJmxMBean.class.isAssignableFrom(mbeanClass)) {
			checkArgument(monitorables.size() == 1, "ConcurrentJmxMBeans cannot be used in pool. " +
					"Only EventloopJmxMBeans can be used in pool");
			isRefreshEnabled = false;
			mbeanWrappers.add(new ConcurrentJmxMBeanWrapper((ConcurrentJmxMBean) monitorables.get(0)));
		} else if (EventloopJmxMBean.class.isAssignableFrom(mbeanClass)) {
			for (Object monitorable : monitorables) {
				mbeanWrappers.add(new EventloopJmxMBeanWrapper((EventloopJmxMBean) monitorable));
			}
		} else {
			throw new IllegalArgumentException("MBeans should implement either ConcurrentJmxMBean " +
					"or EventloopJmxMBean interface");
		}

		AttributeNodeForPojo rootNode = createAttributesTree(mbeanClass, setting.getCustomTypes());
		rootNode.hideNullPojos(monitorables);

		for (String included : setting.getIncludedOptionals()) {
			rootNode.setVisible(included);
		}

		// TODO(vmykhalko): check in JmxRegistry that modifiers are applied only once in case of workers and pool registartion
		for (String attrName : setting.getModifiers().keySet()) {
			AttributeModifier<?> modifier = setting.getModifiers().get(attrName);
			try {
				rootNode.applyModifier(attrName, modifier, monitorables);
			} catch (ClassCastException e) {
				//noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException - doesn't ignore
				throw new IllegalArgumentException("Cannot apply modifier \"" + modifier.getClass().getName() +
						"\" for attribute \"" + attrName + "\": " + e.toString());
			}
		}

		MBeanInfo mBeanInfo = createMBeanInfo(rootNode, mbeanClass);
		Map<OperationKey, Method> opkeyToMethod = fetchOpkeyToMethod(mbeanClass);

		DynamicMBeanAggregator mbean = new DynamicMBeanAggregator(mBeanInfo, mbeanWrappers, rootNode, opkeyToMethod);

		// TODO(vmykhalko): maybe try to get all attributes and log warn message in case of exception? (to prevent potential errors during viewing jmx stats using jconsole)
//		tryGetAllAttributes(mbean);

		if (isRefreshEnabled) {
			handleJmxRefreshables(mbeanWrappers, rootNode);
		}
		return mbean;
	}
1297359
private JMXConnector createConnector(JmxRequest pJmxReq) throws IOException {
        ProxyTargetConfig targetConfig = pJmxReq.getTargetConfig();
        if (targetConfig == null) {
            throw new IllegalArgumentException("No proxy configuration in request " + pJmxReq);
        }
        String urlS = targetConfig.getUrl();
        if (!acceptTargetUrl(urlS)) {
            throw new SecurityException(String.format("Target URL %s is not allowed by configuration", urlS));
        }

        JMXServiceURL url = new JMXServiceURL(urlS);

        Map<String,Object> env = prepareEnv(targetConfig.getEnv());
        return JMXConnectorFactory.newJMXConnector(url,env);
    }
1186863
private ObjectName registerMXBean(MBeanServer pServer, Object pObject, Class pManagementInterface, String pName) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
        ObjectName objectName = new ObjectName(pName);
        final StandardMBean mxBean = new StandardMBean(pObject, pManagementInterface, true /* MXBean */);
        pServer.registerMBean(mxBean, objectName);
        System.out.println("Registered MXBean " + objectName);
        return objectName;
    }
240124
def create(self, **kwargs):
        """"""
        if 'monitor' in kwargs:
            value = self._format_monitor_parameter(kwargs['monitor'])
            kwargs['monitor'] = value
        return super(Pool, self)._create(**kwargs)
556450
private void createCountersManager() {
        UnsafeBuffer counterLabelsBuffer = monitorFileWriter.createGatewayCounterLabelsBuffer();
        UnsafeBuffer counterValuesBuffer = monitorFileWriter.createGatewayCounterValuesBuffer();

        countersManager = new CountersManager(counterLabelsBuffer, counterValuesBuffer);
    }
1337505
private void initMBean()  {
        try {
            registerMBean(this,getObjectName());
        } catch (InstanceAlreadyExistsException exp) {
            // This is no problem, since this MBeanServerHandlerMBean holds only global information
            // with no special state (so all instances of this MBean behave similar)
            // This exception can happen, when multiple servlets get registered within the same JVM
        } catch (MalformedObjectNameException e) {
            // Cannot happen, otherwise this is a bug. We should be always provide our own name in correct
            // form.
            throw new IllegalStateException("Internal Error: Own ObjectName " + getObjectName() + " is malformed",e);
        } catch (NotCompliantMBeanException e) {
            // Same here
            throw new IllegalStateException("Internal Error: " + this.getClass().getName() + " is not a compliant MBean",e);
        }
    }
254785
private Object createJavaxConnectionManagerProxy(Object javaxConnectionManager) {
		assert javaxConnectionManager != null;
		final InvocationHandler invocationHandler = new ConnectionManagerInvocationHandler(
				javaxConnectionManager);
		return createProxy(javaxConnectionManager, invocationHandler);
	}
127366
private static <T> Flowable<Notification<T>> createWithParameters(Connection con, String sql,
            Flowable<List<Object>> parameterGroups, List<ParameterPlaceholder> parameterPlaceholders,
            BiFunction<NamedCallableStatement, List<Object>, Single<T>> single) {
        Callable<NamedCallableStatement> resourceFactory = () -> Util.prepareCall(con, sql, parameterPlaceholders);
        final Function<NamedCallableStatement, Flowable<Notification<T>>> flowableFactory = //
                stmt -> parameterGroups //
                        .flatMap(parameters -> single.apply(stmt, parameters).toFlowable()) //
                        .materialize() //
                        .doOnComplete(() -> Util.commit(stmt.stmt)) //
                        .doOnError(e -> Util.rollback(stmt.stmt));
        Consumer<NamedCallableStatement> disposer = Util::closeCallableStatementAndConnection;
        return Flowable.using(resourceFactory, flowableFactory, disposer, true);
    }
509061
public void startServer() {
        if (!System.getProperties().containsKey(JMX_ENABLED_PROPERTY)) {
            this.logger.info(
                    "System Property '"
                            + JMX_ENABLED_PROPERTY
                            + "' is not set, skipping initialization.");
            return;
        }

        try {
            // Get the base rmi port
            final int portOne = this.getPortOne();

            // Get the second rmi port or calculate it
            final int portTwo = this.calculatePortTwo(portOne);

            // Create the RMI registry on the base port
            try {
                LocateRegistry.createRegistry(portOne);

                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Started RMI Registry on port " + portOne);
                }
            } catch (RemoteException re) {
                throw new IllegalStateException(
                        "Could not create RMI Registry on port " + portOne, re);
            }

            // Generate the JMX Service URL
            final JMXServiceURL jmxServiceUrl = this.getServiceUrl(portOne, portTwo);

            // Map for the JMX environment configuration
            final Map<String, Object> jmxEnv = this.getJmxServerEnvironment();

            // Create the MBean Server
            final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

            // Create the JMX Connector
            try {
                this.jmxConnectorServer =
                        JMXConnectorServerFactory.newJMXConnectorServer(
                                jmxServiceUrl, jmxEnv, mbeanServer);

                if (this.logger.isDebugEnabled()) {
                    this.logger.debug(
                            "Created JMXConnectorServer for JMXServiceURL='"
                                    + jmxServiceUrl
                                    + "', jmxEnv='"
                                    + jmxEnv
                                    + "' MBeanServer='"
                                    + mbeanServer
                                    + "'");
                }
            } catch (IOException ioe) {
                throw new IllegalStateException(
                        "Failed to create a new JMXConnectorServer for JMXServiceURL='"
                                + jmxServiceUrl
                                + "', jmxEnv='"
                                + jmxEnv
                                + "' MBeanServer='"
                                + mbeanServer
                                + "'",
                        ioe);
            }

            // Start the JMX Connector
            try {
                this.jmxConnectorServer.start();
                this.logger.info(
                        "Started JMXConnectorServer. Listening on '" + jmxServiceUrl + "'");
            } catch (IOException ioe) {
                throw new IllegalStateException("Failed to start the JMXConnectorServer", ioe);
            }
        } catch (RuntimeException re) {
            if (this.failOnException) {
                throw re;
            }

            this.logger.error("Failed to initialize the JMX Server", re);
        }
    }
1248885
public void start() throws Throwable
   {
      if (mbeanServer != null)
      {
         DynamicMBean dmb = JMX.createMBean(this, "JNDIViewer");
         objectName = new ObjectName(domain + ":name=JNDIViewer");

         mbeanServer.registerMBean(dmb, objectName);
      }
   }
60569
def createMonitor(self, callback=None, errback=None, **kwargs):
        
        import ns1.monitoring
        monitor = ns1.monitoring.Monitor(self.config)
        return monitor.create(callback=callback, errback=errback, **kwargs)
537412
private void initJmxExpose() {
		final String packageName = getClass().getName().substring(0,
				getClass().getName().length() - getClass().getSimpleName().length() - 1);
		String webapp = Parameters.getContextPath(Parameters.getServletContext());
		if (webapp.length() >= 1 && webapp.charAt(0) == '/') {
			webapp = webapp.substring(1, webapp.length());
		}
		final List<Counter> counters = collector.getCounters();
		final MBeanServer platformMBeanServer = MBeans.getPlatformMBeanServer();
		try {
			for (final Counter counter : counters) {
				if (!Parameters.isCounterHidden(counter.getName())) {
					final CounterRequestMXBean.CounterRequestMXBeanImpl mxBean = new CounterRequestMXBean.CounterRequestMXBeanImpl(
							counter);
					final ObjectName name = new ObjectName(
							packageName + ":type=CounterRequest,context=" + webapp + ",name="
									+ counter.getName());
					platformMBeanServer.registerMBean(mxBean, name);
					jmxNames.add(name);
				}
			}
			LOG.debug("JMX mbeans registered");
		} catch (final JMException e) {
			LOG.warn("failed to register JMX mbeans", e);
		}
	}
1203078
@Override
    public ObjectInstance registerMBean(Object object, ObjectName name)
            throws MBeanRegistrationException, NotCompliantMBeanException
    {
        while (true) {
            try {
                // try to register the mbean
                return mbeanServer.registerMBean(object, name);
            }
            catch (InstanceAlreadyExistsException ignored) {
            }

            try {
                // a mbean is already installed, try to return the already registered instance
                ObjectInstance objectInstance = mbeanServer.getObjectInstance(name);
                log.debug("%s already bound to %s", name, objectInstance);
                return objectInstance;
            }
            catch (InstanceNotFoundException ignored) {
                // the mbean was removed before we could get the reference
                // start the whole process over again
            }
        }
    }
782847
public static MonitorAndManagementSettings newInstance(URL settingsXml) throws IOException, JAXBException {
        InputStream istream = settingsXml.openStream();
        JAXBContext ctx = JAXBContext.newInstance(MonitorAndManagementSettings.class);
        return (MonitorAndManagementSettings) ctx.createUnmarshaller().unmarshal(istream);
    }
1008265
private MBeanParameterInfo[] buildOperationParameterInfo(Method method, JmxOperationInfo operationInfo) {
		Class<?>[] types = method.getParameterTypes();
		MBeanParameterInfo[] parameterInfos = new MBeanParameterInfo[types.length];
		String[] parameterNames = operationInfo.getParameterNames();
		String[] parameterDescriptions = operationInfo.getParameterDescriptions();
		for (int i = 0; i < types.length; i++) {
			String parameterName;
			if (parameterNames == null || i >= parameterNames.length) {
				parameterName = "p" + (i + 1);
			} else {
				parameterName = parameterNames[i];
			}
			String typeName = types[i].getName();
			String description;
			if (parameterDescriptions == null || i >= parameterDescriptions.length) {
				description = "parameter #" + (i + 1) + " of type: " + typeName;
			} else {
				description = parameterDescriptions[i];
			}
			parameterInfos[i] = new MBeanParameterInfo(parameterName, typeName, description);
		}
		return parameterInfos;
	}
742029
public static void register(final MBeanServer mbs, final Object obj)
        {
        final ObjectName mBeanName = JmxUtils.getObjectName(obj.getClass());
        try
            {
            mbs.registerMBean(obj, mBeanName);
            }
        catch (final InstanceAlreadyExistsException e)
            {
            LOG.error("Could not start JMX", e);
            }
        catch (final MBeanRegistrationException e)
            {
            LOG.error("Could not register", e);
            }
        catch (final NotCompliantMBeanException e)
            {
            LOG.error("MBean error", e);
            }
        }
588306
@Override
    public DynamicMBean getMBeanFor(Object object) throws IllegalStateException {
        JmxBean jmxBean = AnnotationUtils.getAnnotation(object.getClass(), JmxBean.class);
        if (jmxBean == null) {
            throw new IllegalArgumentException("Could not find annotation " + JmxBean.class + " on " + object.getClass());
        }
        try {
            ClassIntrospector classIntrospector = new ClassIntrospectorImpl(object.getClass());
            DynamicMBeanImpl mbean = new DynamicMBeanImpl(object);
            mbean.setmBeanInfo(getInfo(object, classIntrospector));
            Map<String, Method> getters = new HashMap<String, Method>();
            Map<String, Method> setters = new HashMap<String, Method>();
            resolveGettersAndSetters(classIntrospector, getters, setters);
            mbean.setGetters(getters);
            mbean.setSetters(setters);
            mbean.setOperations(getOperationsMap(classIntrospector));
            return mbean;
        } catch (Exception e) {
           throw new IllegalStateException("Could not create DynamicMBean for " + object, e);
        }
    }