Java 类com.codahale.metrics.SharedMetricRegistries 实例源码

项目:okapi    文件:DropwizardHelper.java   
public static void config(String graphiteHost, int port, TimeUnit tu,
        int period, VertxOptions vopt, String hostName) {
  final String registryName = "okapi";
  MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);

  DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions();
  metricsOpt.setEnabled(true).setRegistryName(registryName);
  vopt.setMetricsOptions(metricsOpt);
  Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, port));
  final String prefix = "folio.okapi." + hostName ;
  GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
          .prefixedWith(prefix)
          .build(graphite);
  reporter.start(period, tu);

  logger.info("Metrics remote:" + graphiteHost + ":"
          + port + " this:" + prefix);
}
项目:uploader    文件:S3ProgressListener.java   
/**
 * Constructor
 *
 * @param key
 *            S3 key
 * @param start
 *            Start time in nanoseconds
 * @param count
 *            Number of events in the upload
 * @param size
 *            Size of the upload
 */
public S3ProgressListener(@Nonnull final String key, final long start,
        final int count, final int size) {
    this.key = Objects.requireNonNull(key);
    this.start = start;
    this.count = count;
    this.size = size;

    final MetricRegistry registry = SharedMetricRegistries.getDefault();
    this.uploadTime = registry
            .timer(name(S3ProgressListener.class, "upload-time"));
    this.successCounter = registry
            .counter(name(S3ProgressListener.class, "upload-success"));
    this.failedCounter = registry
            .counter(name(S3ProgressListener.class, "upload-failed"));
}
项目:kafka-dropwizard-reporter    文件:DropwizardReporterTest.java   
@Test
public void testMetricChange() throws Exception {
    Metrics metrics = new Metrics();
    DropwizardReporter reporter = new DropwizardReporter();
    reporter.configure(new HashMap<String, Object>());
    metrics.addReporter(reporter);
    Sensor sensor = metrics.sensor("kafka.requests");
    sensor.add(new MetricName("pack.bean1.avg", "grp1"), new Avg());

    Map<String, Gauge> gauges = SharedMetricRegistries.getOrCreate("default").getGauges();
    String expectedName = "org.apache.kafka.common.metrics.grp1.pack.bean1.avg";
    Assert.assertEquals(1, gauges.size());
    Assert.assertEquals(expectedName, gauges.keySet().toArray()[0]);

    sensor.record(2.1);
    sensor.record(2.2);
    sensor.record(2.6);
    Assert.assertEquals(2.3, (Double)gauges.get(expectedName).getValue(), 0.001);
}
项目:flux    文件:EventSchedulerService.java   
@Inject
public EventSchedulerService(EventSchedulerDao eventSchedulerDao, EventSchedulerRegistry eventSchedulerRegistry,
                             @Named("eventScheduler.batchRead.intervalms") Integer batchReadInterval,
                             @Named("eventScheduler.batchRead.batchSize") Integer batchSize,
                             ObjectMapper objectMapper) {
    this.eventSchedulerDao = eventSchedulerDao;
    this.eventSchedulerRegistry = eventSchedulerRegistry;
    this.batchReadInterval = batchReadInterval;
    this.batchSize = batchSize;
    this.objectMapper = objectMapper;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // remove the task from scheduler on cancel
    executor.setRemoveOnCancelPolicy(true);
    scheduledExecutorService =
            new InstrumentedScheduledExecutorService(Executors.unconfigurableScheduledExecutorService(executor),
                    SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledExectorSvcName);
}
项目:flux    文件:RedriverService.java   
@Inject
public RedriverService(MessageManagerService messageService,
                       RedriverRegistry redriverRegistry,
                       @Named("redriver.batchRead.intervalms") Integer batchReadInterval,
                       @Named("redriver.batchRead.batchSize") Integer batchSize) {
    this.redriverRegistry = redriverRegistry;
    this.batchReadInterval = batchReadInterval;
    this.batchSize = batchSize;
    this.messageService = messageService;
    asyncRedriveService = Executors.newFixedThreadPool(10);

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // remove the task from scheduler on cancel
    executor.setRemoveOnCancelPolicy(true);
    scheduledExecutorService =
            new InstrumentedScheduledExecutorService(Executors.unconfigurableScheduledExecutorService(executor),
                    SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledExectorSvcName);
}
项目:runrightfast-vertx    文件:RunRightFastVertxApplicationTest.java   
@Test
public void test_eventBus_GetVerticleDeployments() throws InterruptedException, ExecutionException, TimeoutException {
    log.info("test_eventBus_GetVerticleDeployments");
    final Vertx vertx = vertxService.getVertx();

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture<GetVerticleDeployments.Response> future = new CompletableFuture<>();
    final String address = EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments");
    vertx.eventBus().send(
            address,
            GetVerticleDeployments.Request.newBuilder().build(),
            new DeliveryOptions().setSendTimeout(2000L),
            responseHandler(future, GetVerticleDeployments.Response.class)
    );
    final GetVerticleDeployments.Response result = future.get(2000L, TimeUnit.MILLISECONDS);
    assertThat(result.getDeploymentsCount(), is(2));

    final MetricRegistry metricRegistryTestVerticle1 = SharedMetricRegistries.getOrCreate(TestVerticle.VERTICLE_ID.toString());
    assertThat(metricRegistryTestVerticle1.getCounters().get(RunRightFastVerticleMetrics.Counters.INSTANCE_STARTED.metricName).getCount(), is(1L));

    final MetricRegistry metricRegistryTestVerticle2 = SharedMetricRegistries.getOrCreate(TestVerticle2.VERTICLE_ID.toString());
    assertThat(metricRegistryTestVerticle2.getCounters().get(RunRightFastVerticleMetrics.Counters.INSTANCE_STARTED.metricName).getCount(), is(5L));
}
项目:runrightfast-vertx    文件:RunRightFastVertxApplicationTest.java   
@Test
public void test_eventBus_GetVerticleDeployments_usingProtobufMessageProducer() throws InterruptedException, ExecutionException, TimeoutException {
    log.info("test_eventBus_GetVerticleDeployments");
    final Vertx vertx = vertxService.getVertx();

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture future = new CompletableFuture();
    final String address = EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments");

    final ProtobufMessageProducer producer = new ProtobufMessageProducer(
            vertx.eventBus(),
            address,
            getVerticleDeploymentsResponseCodec,
            SharedMetricRegistries.getOrCreate(getClass().getSimpleName())
    );
    producer.send(
            GetVerticleDeployments.Request.newBuilder().build(),
            new DeliveryOptions().setSendTimeout(2000L),
            responseHandler(future, GetVerticleDeployments.Response.class)
    );
    final Object result = future.get(2000L, TimeUnit.MILLISECONDS);
}
项目:bamboo    文件:BaseWarcDomainManager.java   
@VisibleForTesting
@SuppressWarnings("unused")
public static void forTestSetMetricsRegistryName(String metricsRegistryName) {
  if (imStarted) {
    throw new IllegalStateException("Unit tests only!!!");
  }
  MetricRegistry metrics = SharedMetricRegistries.getOrCreate(metricsRegistryName);
  bambooReadTimer = new Timer();
  metrics.register("bambooReadTimer", bambooReadTimer);
  bambooParseTimer = new Timer();
  metrics.register("bambooParseTimer", bambooParseTimer);
  warcDocCountHistogram = new Histogram(new UniformReservoir());
  metrics.register("warcDocCountHistogram", warcDocCountHistogram);
  warcSizeHistogram = new Histogram(new UniformReservoir());
  metrics.register("warcSizeHistogram", warcSizeHistogram);
}
项目:vertx-dropwizard-metrics    文件:VertxMetricsImpl.java   
@Override
public void close() {
  if (shutdown) {
    RegistryHelper.shutdown(registry);
    if (options.getRegistryName() != null) {
      SharedMetricRegistries.remove(options.getRegistryName());
    }
  }
  List<HttpClientReporter> reporters;
  synchronized (this) {
    reporters = new ArrayList<>(clientReporters.values());
  }
  for (HttpClientReporter reporter : reporters) {
    reporter.close();
  }
  if (doneHandler != null) {
    doneHandler.handle(null);
  }
}
项目:werval    文件:MetricsPlugin.java   
@Override
public void onPassivate( Application application )
{
    requestTimers.values().forEach( t -> t.stop() );
    requestTimers = null;
    reporters.forEach(
        r ->
        {
            if( r instanceof ScheduledReporter )
            {
                ( (ScheduledReporter) r ).stop();
            }
            else if( r instanceof JmxReporter )
            {
                ( (JmxReporter) r ).stop();
            }
        }
    );
    reporters = null;
    api = null;
    eventRegistration.unregister();
    eventRegistration = null;
    SharedMetricRegistries.clear();
    SharedHealthCheckRegistries.clear();
}
项目:metrics-sql    文件:DriverTest.java   
@Test
public void testConnectionLife() throws SQLException {
    // Act
    Connection connection = DriverManager.getConnection(URL + ";metrics_registry=life", H2DbUtil.USERNAME, H2DbUtil.PASSWORD);
    Statement statement = connection.createStatement();
    H2DbUtil.close(statement, connection);
    // Assert
    assertNotNull(connection);
    assertTrue(Proxy.isProxyClass(connection.getClass()));
    MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate("life");
    Timer lifeTimer = metricRegistry.timer("java.sql.Connection");
    assertNotNull(lifeTimer);
    assertThat(lifeTimer.getCount(), equalTo(1L));
    Timer getTimer = metricRegistry.timer("java.sql.Connection.get");
    assertNotNull(getTimer);
    assertThat(getTimer.getCount(), equalTo(1L));
}
项目:metrics-aspectj    文件:MeteredMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredMethodsOnceWithoutThrowing() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    Runnable runnableThatDoesNoThrowExceptions = new Runnable() {
        @Override
        public void run() {
        }
    };

    // Call the metered methods and assert they haven't been marked
    instance.illegalArgumentExceptionMeteredMethod(runnableThatDoesNoThrowExceptions);
    instance.exceptionMeteredMethod(runnableThatDoesNoThrowExceptions);
    assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
}
项目:metrics-aspectj    文件:MeteredMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredMethodOnceWithThrowingExpectedException() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    final RuntimeException exception = new IllegalArgumentException("message");
    Runnable runnableThatThrowsIllegalArgumentException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        instance.illegalArgumentExceptionMeteredMethod(runnableThatThrowsIllegalArgumentException);
    } catch (RuntimeException cause) {
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(1L)));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(0L)));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
项目:metrics-aspectj    文件:MeteredMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredMethodOnceWithThrowingNonExpectedException() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it hasn't been marked and that the original exception has been rethrown
    try {
        instance.illegalArgumentExceptionMeteredMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
项目:metrics-aspectj    文件:MeteredMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredMethodOnceWithThrowingInstanceOfExpectedException() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        instance.exceptionMeteredMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(0L)));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(1L)));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
项目:metrics-aspectj    文件:MeteredStaticMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredStaticMethodsOnceWithoutThrowing() {
    Runnable runnableThatDoesNoThrowExceptions = new Runnable() {
        @Override
        public void run() {
        }
    };

    // Call the metered methods and assert they haven't been marked
    MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatDoesNoThrowExceptions);
    MeteredStaticMethodWithExceptions.exceptionMeteredStaticMethod(runnableThatDoesNoThrowExceptions);

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
}
项目:metrics-aspectj    文件:MeteredStaticMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingExpectedException() {
    final RuntimeException exception = new IllegalArgumentException("message");
    Runnable runnableThatThrowsIllegalArgumentException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatThrowsIllegalArgumentException);
    } catch (RuntimeException cause) {
        assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
        assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].incrementAndGet())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
项目:metrics-aspectj    文件:MeteredStaticMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingNonExpectedException() {
    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it hasn't been marked and that the original exception has been rethrown
    try {
        MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
        assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
项目:metrics-aspectj    文件:MeteredStaticMethodWithExceptionsTest.java   
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingInstanceOfExpectedException() {
    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        MeteredStaticMethodWithExceptions.exceptionMeteredStaticMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
        assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].incrementAndGet())));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
项目:metrics-aspectj    文件:MultipleMetricsStaticMethodTest.java   
@Test
public void callMetricsStaticMethodsOnce() {
    // Call the monitored method and assert all the metrics have been created and marked
    MultipleMetricsStaticMethod.metricsMethod();

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);

    assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(absoluteMetricNames())));

    // Make sure that the metrics have been called
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("exception")).getCount(), is(equalTo(0L)));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("meter")).getCount(), is(equalTo(1L)));
    assertThat("Timer count is incorrect", registry.getTimers().get(absoluteMetricName("timer")).getCount(), is(equalTo(1L)));
    assertThat("Gauge value is incorrect", registry.getGauges().get(absoluteMetricName("gauge")).getValue(), hasToString((equalTo("value"))));
}
项目:metrics-aspectj    文件:GaugeMethodWithVisibilityModifiersTest.java   
@Test
public void callGaugesAfterSetterCalls() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Gauges are not registered correctly", registry.getGauges().keySet(), is(equalTo(absoluteMetricNames())));

    long value = Math.round(Math.random() * Long.MAX_VALUE);
    // Call the setter methods
    instance.setPublicGauge(value);
    instance.setPackagePrivateGauge(value);
    instance.setProtectedGauge(value);
    method("setPrivateGauge").withParameterTypes(long.class).in(instance).invoke(value);

    // And assert the gauges are up-to-date
    assertThat("Gauge values are incorrect", registry.getGauges().values(), everyItem(Matchers.<Gauge>hasProperty("value", equalTo(value))));
}
项目:metrics-aspectj    文件:JavaxElMetricStrategy.java   
@Override
public MetricRegistry resolveMetricRegistry(String registry) {
    Matcher matcher = EL_PATTERN.matcher(registry);
    if (matcher.matches()) {
        Object evaluation = processor.eval(matcher.group(1));
        if (evaluation instanceof String)
            return SharedMetricRegistries.getOrCreate((String) evaluation);
        else if (evaluation instanceof MetricRegistry)
            return (MetricRegistry) evaluation;
        else
            throw new IllegalStateException("Unable to resolve metrics registry from expression [" + registry + "]");
    } else if (!matcher.find()) {
        return SharedMetricRegistries.getOrCreate(registry);
    } else {
        return SharedMetricRegistries.getOrCreate(evaluateCompositeExpression(matcher));
    }
}
项目:stagemonitor    文件:MDCSpanEventListenerTest.java   
@Before
public void setUp() throws Exception {
    Stagemonitor.reset();
    SharedMetricRegistries.clear();
    this.corePlugin = mock(CorePlugin.class);
    when(corePlugin.isStagemonitorActive()).thenReturn(true);

    final MockTracer tracer = new MockTracer(new ThreadLocalScopeManager(), new B3Propagator());

    TracingPlugin tracingPlugin = mock(TracingPlugin.class);
    when(tracingPlugin.getTracer()).thenReturn(tracer);

    mdcSpanInterceptor = new MDCSpanEventListener(corePlugin, tracingPlugin);
    spanWrapper = new SpanWrapper(tracer.buildSpan("operation name").start(),"operation name",
            1, 1, Collections.emptyList(), new ConcurrentHashMap<>());
}
项目:flume-release-1.7.0    文件:MorphlineHandlerImpl.java   
@Override
public void configure(Context context) {
  String morphlineFile = context.getString(MORPHLINE_FILE_PARAM);
  String morphlineId = context.getString(MORPHLINE_ID_PARAM);
  if (morphlineFile == null || morphlineFile.trim().length() == 0) {
    throw new MorphlineCompilationException("Missing parameter: " + MORPHLINE_FILE_PARAM, null);
  }
  morphlineFileAndId = morphlineFile + "@" + morphlineId;

  if (morphlineContext == null) {
    FaultTolerance faultTolerance = new FaultTolerance(
        context.getBoolean(FaultTolerance.IS_PRODUCTION_MODE, false), 
        context.getBoolean(FaultTolerance.IS_IGNORING_RECOVERABLE_EXCEPTIONS, false),
        context.getString(FaultTolerance.RECOVERABLE_EXCEPTION_CLASSES));

    morphlineContext = new MorphlineContext.Builder()
      .setExceptionHandler(faultTolerance)
      .setMetricRegistry(SharedMetricRegistries.getOrCreate(morphlineFileAndId))
      .build();
  }

  Config override = ConfigFactory.parseMap(
      context.getSubProperties(MORPHLINE_VARIABLE_PARAM + "."));
  morphline = new Compiler().compile(
      new File(morphlineFile), morphlineId, morphlineContext, finalChild, override);

  this.mappingTimer = morphlineContext.getMetricRegistry().timer(
      MetricRegistry.name("morphline.app", Metrics.ELAPSED_TIME));
  this.numRecords = morphlineContext.getMetricRegistry().meter(
      MetricRegistry.name("morphline.app", Metrics.NUM_RECORDS));
  this.numFailedRecords = morphlineContext.getMetricRegistry().meter(
      MetricRegistry.name("morphline.app", "numFailedRecords"));
  this.numExceptionRecords = morphlineContext.getMetricRegistry().meter(
      MetricRegistry.name("morphline.app", "numExceptionRecords"));
}
项目:graphiak    文件:MetricHandler.java   
/**
 * Constructor
 *
 * @param store
 *            Metric store
 */
public MetricHandler(@Nonnull final MetricStore store) {
    this.store = Objects.requireNonNull(store);

    final MetricRegistry registry = SharedMetricRegistries
            .getOrCreate("default");
    this.metricMeter = registry
            .meter(MetricRegistry.name(MetricHandler.class, "metric-rate"));
}
项目:graphiak    文件:MetricStore.java   
/**
 * Constructor
 *
 * @param client
 *            Riak client
 */
public MetricStore(@Nonnull final RiakClient client) {
    this.client = Objects.requireNonNull(client);

    final MetricRegistry registry = SharedMetricRegistries
            .getOrCreate("default");
    this.queryTimer = registry
            .timer(MetricRegistry.name(MetricStore.class, "query"));
    this.storeTimer = registry
            .timer(MetricRegistry.name(MetricStore.class, "store"));
    this.deleteTimer = registry
            .timer(MetricRegistry.name(MetricStore.class, "delete"));
}
项目:Mastering-Mesos    文件:GuicePropertyFilteringMessageBodyWriter.java   
private MetricRegistry getMetricRegistry() {
  MetricRegistry registry = environment.metrics();

  if (registry == null) {
    LOG.warn("No environment metrics found!");
    registry = SharedMetricRegistries.getOrCreate("com.hubspot");
  }

  return registry;
}
项目:okapi    文件:MetricsTest.java   
@Before
public void setUp(TestContext context) {
  String graphiteHost = System.getProperty("graphiteHost");

  final String registryName = "okapi";
  MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);

  // Note the setEnabled (true or false)
  DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions().
          setEnabled(false).setRegistryName(registryName);

  vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(metricsOpt));

  reporter1 = ConsoleReporter.forRegistry(registry).build();
  reporter1.start(1, TimeUnit.SECONDS);

  if (graphiteHost != null) {
    Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, 2003));
    reporter2 = GraphiteReporter.forRegistry(registry)
            .prefixedWith("okapiserver")
            .build(graphite);
    reporter2.start(1, TimeUnit.MILLISECONDS);
  }

  DeploymentOptions opt = new DeploymentOptions()
    .setConfig(new JsonObject().put("port", Integer.toString(port)));


  vertx.deployVerticle(MainVerticle.class.getName(),
          opt, context.asyncAssertSuccess());
  httpClient = vertx.createHttpClient();
}
项目:hono    文件:MetricConfig.java   
@Bean
@ConditionalOnProperty(prefix = "hono.metric", name = "vertx", havingValue = "true")
public MetricsOptions vertxMetricsOptions() {
    LOG.info("metrics - vertx activated");
    SharedMetricRegistries.add(HONO, metricRegistry);
    SharedMetricRegistries.setDefault(HONO, metricRegistry);
    return new DropwizardMetricsOptions().setEnabled(true).setRegistryName(HONO)
            .setBaseName(prefix + ".vertx").setJmxEnabled(true);
}
项目:uploader    文件:BatchHandler.java   
/**
 * Constructor
 *
 * @param maxUploadBytes
 *            Maximum size of AWS S3 file to upload
 */
public BatchHandler(final long maxUploadBytes) {
    this.maxUploadBytes = maxUploadBytes;

    final MetricRegistry registry = SharedMetricRegistries.getDefault();
    this.eventMeter = registry
            .meter(MetricRegistry.name(BatchHandler.class, "event-rate"));
}
项目:uploader    文件:UploadHandler.java   
/**
 * Constructor
 *
 * @param uploader
 *            AWS S3 uploader
 */
public UploadHandler(@Nonnull final Uploader uploader) {
    this.uploader = Objects.requireNonNull(uploader);

    final MetricRegistry registry = SharedMetricRegistries.getDefault();
    this.batchMeter = registry
            .meter(MetricRegistry.name(UploadHandler.class, "batch-rate"));
}
项目:uploader    文件:Uploader.java   
/**
 * Constructor
 *
 * @param configuration
 *            AWS configuration
 */
public Uploader(@Nonnull final AwsConfiguration configuration) {
    this.configuration = Objects.requireNonNull(configuration);

    final MetricRegistry registry = SharedMetricRegistries.getDefault();

    this.batchSize = registry.histogram(name(Uploader.class, "batch-size"));
    this.batchCount = registry
            .histogram(name(Uploader.class, "batch-count"));
}
项目:kafka-dropwizard-reporter    文件:DropwizardReporter.java   
@Override
public void init(List<KafkaMetric> list) {
    if (config == null) {
        throw new IllegalStateException("Must call configure() before calling init() on a reporter.");
    }
    String registryName = config.getString(DropwizardReporterConfig.REGISTRY_PROPERTY_NAME);
    this.registry = SharedMetricRegistries.getOrCreate(registryName);
    for (KafkaMetric kafkaMetric : list) {
        this.metricChange(kafkaMetric);
    }
}
项目:flux    文件:MessageManagerService.java   
@Inject
public MessageManagerService(MessageDao messageDao,
                             @Named("redriver.noOfPersistenceWorkers") int noOfPersistenceWorkers,
                             @Named("redriver.batchDelete.intervalms") Integer batchDeleteInterval,
                             @Named("redriver.batchDelete.batchSize") Integer batchSize) {
    this.messageDao = messageDao;
    this.batchDeleteInterval = batchDeleteInterval;
    this.batchSize = batchSize;
    this.messagesToDelete = new ConcurrentLinkedQueue<>();
    scheduledDeletionService =
        new InstrumentedScheduledExecutorService(Executors.newScheduledThreadPool(2), SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledDeletionSvcName);
    persistenceExecutorService =
        new InstrumentedExecutorService(Executors.newFixedThreadPool(noOfPersistenceWorkers), SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), taskRegisterSvcName);
}
项目:nexus-public    文件:NexusContextListener.java   
@Override
public void contextDestroyed(final ServletContextEvent event) {
  // event is ignored, apparently can also be null

  // remove our dynamic filter
  if (registration != null) {
    registration.unregister();
    registration = null;
  }

  // log uptime before triggering activity which may run into problems
  long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
  log.info("Uptime: {}", PeriodFormat.getDefault().print(new Period(uptime)));

  try {
    lifecycleManager.to(KERNEL);

    // dispose of JSR-250 components before logging goes
    injector.getInstance(BeanManager.class).unmanage();

    lifecycleManager.to(OFF);
  }
  catch (final Exception e) {
    log.error("Failed to stop nexus", e);
  }

  extender.doStop(); // stop tracking bundles

  if (servletContext != null) {
    servletContext = null;
  }

  injector = null;

  SharedMetricRegistries.remove("nexus");
}
项目:pipeline    文件:MessageProcessor.java   
/**
 * Constructor
 *
 * @param s3
 *            S3 Downloader
 * @param broadcaster
 *            SSE broadcaster
 */
public MessageProcessor(@Nonnull final AmazonS3Downloader s3,
        @Nonnull final InstrumentedSseBroadcaster broadcaster) {
    this.s3 = Objects.requireNonNull(s3);
    this.broadcaster = Objects.requireNonNull(broadcaster);

    final MetricRegistry registry = SharedMetricRegistries
            .getOrCreate("default");
    this.recordCounts = registry
            .histogram(name(MessageProcessor.class, "record-counts"));
    this.eventCounts = registry
            .histogram(name(MessageProcessor.class, "event-counts"));
}
项目:pipeline    文件:AmazonSQSIterator.java   
/**
 * Constructor
 *
 * @param client
 *            SQS client
 * @param queueUrl
 *            Queue URL
 */
public AmazonSQSIterator(@Nonnull final AmazonSQS sqs,
        @Nonnull final String queueUrl) {

    this.sqs = Objects.requireNonNull(sqs);
    this.queueUrl = Objects.requireNonNull(queueUrl);

    final MetricRegistry registry = SharedMetricRegistries
            .getOrCreate("default");

    this.receiveRequests = registry
            .counter(name(AmazonSQSIterator.class, "receive-requests"));
    this.deleteRequests = registry
            .counter(name(AmazonSQSIterator.class, "delete-requests"));
    this.messageCounts = registry
            .histogram(name(AmazonSQSIterator.class, "message-counts"));

    registry.register(name(AmazonSQSIterator.class, "queued-messages"),
            new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return getNumMessages();
                }
            });

    this.request = new ReceiveMessageRequest(queueUrl)
            .withMaxNumberOfMessages(MAX_NUMBER_OF_MESSAGES)
            .withVisibilityTimeout(VISIBILITY_TIMEOUT_SECS)
            .withWaitTimeSeconds(WAIT_TIME_SECS);

    LOGGER.info("Using: {}", queueUrl);
}
项目:pipeline    文件:InstrumentedSseBroadcaster.java   
/**
 * Constructor
 */
public InstrumentedSseBroadcaster() {
    super();
    final MetricRegistry registry = SharedMetricRegistries
            .getOrCreate("default");
    this.pingRate = registry
            .meter(name(SseBroadcaster.class, "broadcast", "ping-sends"));
    this.eventRate = registry
            .meter(name(SseBroadcaster.class, "broadcast", "event-sends"));
}
项目:bamboo    文件:IndexerWorker.java   
public IndexerWorker(Timer timer) {
  this.timer = timer;
  // TODO: Remove dqTimer. it has no long term usefulness. It is just being used during development
  // to keep an eye on thread backlogs (or the possibility thereof) around the solr.add() method at
  // various levels of scale.
  dqTimer = SharedMetricRegistries.getOrCreate("serverMetrics").timer("dqTimer");
  if (dqTimer == null) {
    dqTimer = new Timer();
    SharedMetricRegistries.getOrCreate("serverMetrics").register("dqTimer", dqTimer);
  }
}
项目:vertx-dropwizard-metrics    文件:MetricsExamples.java   
public void getRegistry() {
  VertxOptions options = new VertxOptions().setMetricsOptions(
      new DropwizardMetricsOptions().setEnabled(true).setRegistryName("my-registry")
  );
  Vertx vertx = Vertx.vertx(options);
  // Get the registry
  MetricRegistry registry = SharedMetricRegistries.getOrCreate("my-registry");
  // Do whatever you need with the registry
}