Create {@code HibernateMetrics} and bind to the specified meter registry.

@param registry meter registry to use
@param sessionFactory session factory to use
@param sessionFactoryName session factory name as a tag value
@param tags additional tags
506414
public static void monitor(MeterRegistry registry, SessionFactory sessionFactory, String sessionFactoryName, Iterable<Tag> tags) {
        new HibernateMetrics(sessionFactory, sessionFactoryName, tags).bindTo(registry);
    }
403272
public static void registerStandardMXBeans(Registry registry) {
    for (MemoryPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(MemoryPoolMXBean.class)) {
      registry.register(new MemoryPoolMeter(registry, mbean));
    }

    for (BufferPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
      registry.register(new BufferPoolMeter(registry, mbean));
    }
  }
321344
static void checkMetricAndTags(final String metric,
      final Map<String, String> tags) {
    if (tags.size() <= 0) {
      throw new IllegalArgumentException("Need at least one tag (metric="
          + metric + ", tags=" + tags + ')');
    } else if (tags.size() > Const.MAX_NUM_TAGS()) {
      throw new IllegalArgumentException("Too many tags: " + tags.size()
          + " maximum allowed: " + Const.MAX_NUM_TAGS() + ", tags: " + tags);
    }

    Tags.validateString("metric name", metric);
    for (final Map.Entry<String, String> tag : tags.entrySet()) {
      Tags.validateString("tag name with value [" + tag.getValue() + "]", 
          tag.getKey());
      Tags.validateString("tag value with key [" + tag.getKey() + "]", 
          tag.getValue());
    }
  }
756676
public MetricRegistry registerMetrics(final MetricRegistry registry) {
      registry.register(MetricRegistry.name(ConnectionPool.class, name), metrics);
      return registry;
   }
1138881
@Override
	public void register(Metric metric, String metricName, AbstractMetricGroup group) {
		synchronized (lock) {
			if (isShutdown()) {
				LOG.warn("Cannot register metric, because the MetricRegistry has already been shut down.");
			} else {
				if (reporters != null) {
					for (int i = 0; i < reporters.size(); i++) {
						MetricReporter reporter = reporters.get(i);
						try {
							if (reporter != null) {
								FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
								reporter.notifyOfAddedMetric(metric, metricName, front);
							}
						} catch (Exception e) {
							LOG.warn("Error while registering metric.", e);
						}
					}
				}
				try {
					if (queryService != null) {
						queryService.addMetric(metricName, metric, group);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
				try {
					if (metric instanceof View) {
						if (viewUpdater == null) {
							viewUpdater = new ViewUpdater(executor);
						}
						viewUpdater.notifyOfAddedView((View) metric);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
			}
		}
	}
612311
public void createTags(Reference reference, String... tags) {
		createTags(reference, Arrays.asList(tags));
	}
1212405
protected MetricRegistryImpl createMetricRegistry(Configuration config) {
		return new MetricRegistryImpl(
			MetricRegistryConfiguration.fromConfiguration(config),
			ReporterSetup.fromConfiguration(config));
	}
217747
public void readTags(InputStream tagsXML)
    {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try
        {
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(tagsXML, new TagsSaxHandler(this));
        }
        catch (ParserConfigurationException | SAXException | IOException ex)
        {
            throw new RuntimeException("Failed parsing the tags definition: " + ex.getMessage(), ex);
        }
    }
536712
private List<String> getTagsFromMetricGroup(MetricGroup metricGroup) {
		List<String> tags = new ArrayList<>();

		for (Map.Entry<String, String> entry: metricGroup.getAllVariables().entrySet()) {
			if (!entry.getKey().equals(HOST_VARIABLE)) {
				tags.add(getVariableName(entry.getKey()) + ":" + entry.getValue());
			}
		}

		return tags;
	}
120905
public void registerMetrics() {
        if (metricsAreRegistered) {
            return;
        }
        getMetricRegistry().register("jvm.attribute", new JvmAttributeGaugeSet());
        getMetricRegistry().register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory
                                                                               .getPlatformMBeanServer()));
        getMetricRegistry().register("jvm.classloader", new ClassLoadingGaugeSet());
        getMetricRegistry().register("jvm.filedescriptor", new FileDescriptorRatioGauge());
        getMetricRegistry().register("jvm.gc", new GarbageCollectorMetricSet());
        getMetricRegistry().register("jvm.memory", new MemoryUsageGaugeSet());
        getMetricRegistry().register("jvm.threads", new ThreadStatesGaugeSet());

        JmxReporter.forRegistry(metricRegistry).build().start();
        metricsAreRegistered = true;
    }
82532
public void registerBeans(BeanDefinitionRegistry registry) {
        finalizeDeferredProperties();

        if (registry instanceof GenericApplicationContext) {
            GenericApplicationContext ctx = (GenericApplicationContext) registry;
            ctx.setClassLoader(classLoader);
            ctx.getBeanFactory().setBeanClassLoader(classLoader);
        }

        springConfig.registerBeansWithRegistry(registry);
    }
1347815
private CreateTagsResponseType createTags(final List<String> resourcesSet,
            final Map<String, String> tagSet) {
        CreateTagsResponseType ret = new CreateTagsResponseType();
        ret.setRequestId(UUID.randomUUID().toString());
        mockTagsController.createTags(resourcesSet, tagSet);
        ret.setReturn(true);
        return ret;
    }
118127
@Bean
    @Nullable
    public Server armeriaServer(
            ArmeriaSettings armeriaSettings,
            Optional<MeterRegistry> meterRegistry,
            Optional<MeterIdPrefixFunctionFactory> meterIdPrefixFunctionFactory,
            Optional<List<HealthChecker>> healthCheckers,
            Optional<List<ArmeriaServerConfigurator>> armeriaServerConfigurators,
            Optional<List<ThriftServiceRegistrationBean>> thriftServiceRegistrationBeans,
            Optional<List<HttpServiceRegistrationBean>> httpServiceRegistrationBeans,
            Optional<List<AnnotatedServiceRegistrationBean>> annotatedServiceRegistrationBeans)
            throws InterruptedException {

        if (!armeriaServerConfigurators.isPresent() &&
            !thriftServiceRegistrationBeans.isPresent() &&
            !httpServiceRegistrationBeans.isPresent() &&
            !annotatedServiceRegistrationBeans.isPresent()) {
            // No services to register, no need to start up armeria server.
            return null;
        }

        final MeterIdPrefixFunctionFactory meterIdPrefixFuncFactory =
                armeriaSettings.isEnableMetrics() ? meterIdPrefixFunctionFactory.orElse(DEFAULT)
                                                  : null;

        final ServerBuilder server = new ServerBuilder();

        final List<Port> ports = armeriaSettings.getPorts();
        if (ports.isEmpty()) {
            server.port(new ServerPort(DEFAULT_PORT.getPort(), DEFAULT_PORT.getProtocols()));
        } else {
            configurePorts(server, ports);
        }

        configureThriftServices(server,
                                thriftServiceRegistrationBeans.orElseGet(Collections::emptyList),
                                meterIdPrefixFuncFactory,
                                armeriaSettings.getDocsPath());
        configureHttpServices(server,
                              httpServiceRegistrationBeans.orElseGet(Collections::emptyList),
                              meterIdPrefixFuncFactory);
        configureAnnotatedHttpServices(server,
                                       annotatedServiceRegistrationBeans.orElseGet(Collections::emptyList),
                                       meterIdPrefixFuncFactory);
        configureServerWithArmeriaSettings(server, armeriaSettings,
                                           meterRegistry.orElse(Metrics.globalRegistry),
                                           healthCheckers.orElseGet(Collections::emptyList));

        armeriaServerConfigurators.ifPresent(
                configurators -> configurators.forEach(
                        configurator -> configurator.configure(server)));

        final Server s = server.build();

        s.start().handle((result, t) -> {
            if (t != null) {
                throw new IllegalStateException("Armeria server failed to start", t);
            }
            return result;
        }).join();
        logger.info("Armeria server started at ports: {}", s.activePorts());
        return s;
    }
716612
public static PrometheusMeterRegistry newRegistry(CollectorRegistry registry, Clock clock) {
        final PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(
                PrometheusConfig.DEFAULT, requireNonNull(registry, "registry"), requireNonNull(clock, "clock"));
        meterRegistry.config().namingConvention(MoreNamingConventions.prometheus());
        meterRegistry.config().pauseDetector(new NoPauseDetector());
        return meterRegistry;
    }
894665
@Override
    public SessionFactory buildSessionFactory() throws HibernateException {

        // set the class loader to load Groovy classes

        // work around for HHH-2624
        SessionFactory sessionFactory;

        Object classLoaderObject = getProperties().get(AvailableSettings.CLASSLOADERS);
        ClassLoader appClassLoader;

        if(classLoaderObject instanceof ClassLoader) {
            appClassLoader = (ClassLoader) classLoaderObject;
        }
        else {
            appClassLoader = getClass().getClassLoader();
        }

        ConfigurationHelper.resolvePlaceHolders(getProperties());

        final GrailsDomainBinder domainBinder = new GrailsDomainBinder(
                dataSourceName,
                sessionFactoryBeanName,
                hibernateMappingContext
        );

        List<Class> annotatedClasses = new ArrayList<>();
        for (PersistentEntity persistentEntity : hibernateMappingContext.getPersistentEntities()) {
            Class javaClass = persistentEntity.getJavaClass();
            if(javaClass.isAnnotationPresent(Entity.class)) {
                annotatedClasses.add(javaClass);
            }
        }

        if(!additionalClasses.isEmpty()) {
            for (Class additionalClass : additionalClasses) {
                if(GormEntity.class.isAssignableFrom(additionalClass)) {
                    hibernateMappingContext.addPersistentEntity(additionalClass);
                }
            }
        }

        addAnnotatedClasses( annotatedClasses.toArray(new Class[annotatedClasses.size()]));

        ClassLoaderService classLoaderService = new ClassLoaderServiceImpl(appClassLoader) {
            @Override
            public <S> Collection<S> loadJavaServices(Class<S> serviceContract) {
                if(MetadataContributor.class.isAssignableFrom(serviceContract)) {
                    if(metadataContributor != null) {
                        return (Collection<S>) Arrays.asList(domainBinder, metadataContributor);
                    }
                    else {
                        return Collections.singletonList((S) domainBinder);
                    }
                }
                else {
                    return super.loadJavaServices(serviceContract);
                }
            }
        };
        EventListenerIntegrator eventListenerIntegrator = new EventListenerIntegrator(hibernateEventListeners, eventListeners);
        BootstrapServiceRegistry bootstrapServiceRegistry = createBootstrapServiceRegistryBuilder()
                                                                    .applyIntegrator(eventListenerIntegrator)
                                                                    .applyIntegrator(new MetadataIntegrator())
                                                                    .applyClassLoaderService(classLoaderService)
                                                                    .build();
        StrategySelector strategySelector = bootstrapServiceRegistry.getService(StrategySelector.class);

        strategySelector.registerStrategyImplementor(
                PropertyAccessStrategy.class, "traitProperty", TraitPropertyAccessStrategy.class
        );

        setSessionFactoryObserver(new SessionFactoryObserver() {
            private static final long serialVersionUID = 1;
            public void sessionFactoryCreated(SessionFactory factory) {}
            public void sessionFactoryClosed(SessionFactory factory) {
                if (serviceRegistry != null) {
                    ((ServiceRegistryImplementor)serviceRegistry).destroy();
                }
            }
        });

        StandardServiceRegistryBuilder standardServiceRegistryBuilder = createStandardServiceRegistryBuilder(bootstrapServiceRegistry)
                                                                                    .applySettings(getProperties());

        StandardServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();
        sessionFactory = super.buildSessionFactory(serviceRegistry);
        this.serviceRegistry = serviceRegistry;

        return sessionFactory;
    }
93139
public MeterIdPrefix appendWithTags(String suffix, Iterable<Tag> tags) {
        return new MeterIdPrefix(name(suffix), sortedImmutableTags(tags));
    }
158372
protected Map<String, BeanDefinition> registerModules(BindRegistry registry) {
    Stopwatch watch = new Stopwatch(true);
    List<String> modules = registry.getBeanNames(BindModule.class);
    Map<String, BeanDefinition> newBeanDefinitions = CollectUtils.newHashMap();
    for (String name : modules) {
      Class<?> beanClass = registry.getBeanType(name);
      BeanConfig config = null;
      try {
        config = ((BindModule) beanClass.newInstance()).getConfig();
      } catch (Exception e) {
        logger.error("class initialization error of  " + beanClass, e);
        continue;
      }
      List<BeanConfig.Definition> definitions = config.getDefinitions();
      for (BeanConfig.Definition definition : definitions) {
        String beanName = definition.beanName;
        if (registry.contains(beanName)) {
          logger.warn("Ingore exists bean definition {}", beanName);
        } else {
          BeanDefinition def = registerBean(definition, registry);
          newBeanDefinitions.put(beanName, def);
        }
      }
    }
    logger.info("Auto register {} beans in {}", newBeanDefinitions.size(), watch);
    return newBeanDefinitions;
  }