src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
JCacheMetrics extends CacheMeterBinder { @Override protected long hitCount() { return lookupStatistic("CacheHits"); } JCacheMetrics(Cache<?, ?> cache, Iterable<Tag> tags); static C monitor(MeterRegistry registry, C cache, String... tags); static C monitor(MeterRegistry registry, C cache, Iterable<Tag> tags); }
@Test void returnHitCount() { assertThat(metrics.hitCount()).isEqualTo(expectedAttributeValue); } @Test void defaultValueWhenNoMBeanAttributeFound() throws MalformedObjectNameException { metrics.objectName = new ObjectName("javax.cache:type=CacheInformation"); assertThat(metrics.hitCount()).isEqualTo(0L); } @Test void ...
JCacheMetrics extends CacheMeterBinder { @Override protected long putCount() { return lookupStatistic("CachePuts"); } JCacheMetrics(Cache<?, ?> cache, Iterable<Tag> tags); static C monitor(MeterRegistry registry, C cache, String... tags); static C monitor(MeterRegistry registry, C cache, Iterable<Tag> tags); }
@Test void returnPutCount() { assertThat(metrics.putCount()).isEqualTo(expectedAttributeValue); }
JCacheMetrics extends CacheMeterBinder { @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { if (objectName != null) { Gauge.builder("cache.removals", objectName, objectName -> lookupStatistic("CacheRemovals")) .tags(getTagsWithCacheName()) .description("Cache removals") .register(regis...
@Test void doNotReportMetricWhenObjectNameNotInitialized() throws MalformedObjectNameException { when(cache.getCacheManager()).thenReturn(null); metrics = new JCacheMetrics(cache, expectedTag); MeterRegistry registry = new SimpleMeterRegistry(); metrics.bindImplementationSpecificMetrics(registry); assertThat(registry.f...
TimedHandler extends HandlerWrapper implements Graceful { @Override public Future<Void> shutdown() { return shutdown.shutdown(); } TimedHandler(MeterRegistry registry, Iterable<Tag> tags); TimedHandler(MeterRegistry registry, Iterable<Tag> tags, HttpServletRequestTagsProvider tagsProvider); @Override void handle(Strin...
@Test void testAsyncRequestWithShutdown() throws Exception { long delay = 500; CountDownLatch serverLatch = new CountDownLatch(1); timedHandler.setHandler(new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { AsyncContext asy...
JettySslHandshakeMetrics implements SslHandshakeListener { @Override public void handshakeFailed(Event event, Throwable failure) { handshakesFailed.increment(); } JettySslHandshakeMetrics(MeterRegistry registry); JettySslHandshakeMetrics(MeterRegistry registry, Iterable<Tag> tags); @Override void handshakeSucceeded(Ev...
@Test void handshakeFailed() { SslHandshakeListener.Event event = new SslHandshakeListener.Event(engine); sslHandshakeMetrics.handshakeFailed(event, new javax.net.ssl.SSLHandshakeException("")); assertThat(registry.get("jetty.ssl.handshakes") .tags("id", "0", "protocol", "unknown", "ciphersuite", "unknown", "result", "...
JettySslHandshakeMetrics implements SslHandshakeListener { @Override public void handshakeSucceeded(Event event) { SSLSession session = event.getSSLEngine().getSession(); Counter.builder(METER_NAME) .baseUnit(BaseUnits.EVENTS) .description(DESCRIPTION) .tag(TAG_RESULT, "succeeded") .tag(TAG_PROTOCOL, session.getProtoco...
@Test void handshakeSucceeded() { SslHandshakeListener.Event event = new SslHandshakeListener.Event(engine); when(session.getProtocol()).thenReturn("TLSv1.3"); when(session.getCipherSuite()).thenReturn("RSA_XYZZY"); sslHandshakeMetrics.handshakeSucceeded(event); assertThat(registry.get("jetty.ssl.handshakes") .tags("id...
HibernateMetrics implements MeterBinder { public static void monitor(MeterRegistry registry, SessionFactory sessionFactory, String sessionFactoryName, String... tags) { monitor(registry, sessionFactory, sessionFactoryName, Tags.of(tags)); } HibernateMetrics(SessionFactory sessionFactory, String sessionFactoryName, Iter...
@SuppressWarnings("deprecation") @Test void deprecatedMonitorShouldExposeMetricsWhenStatsEnabled() { HibernateMetrics.monitor(registry, entityManagerFactory, "entityManagerFactory"); assertThatMonitorShouldExposeMetricsWhenStatsEnabled(); } @Test void monitorShouldExposeMetricsWhenStatsEnabled() { HibernateMetrics.moni...
PushMeterRegistry extends MeterRegistry { @Deprecated public final void start() { start(Executors.defaultThreadFactory()); } protected PushMeterRegistry(PushRegistryConfig config, Clock clock); @Deprecated final void start(); void start(ThreadFactory threadFactory); void stop(); @Override void close(); }
@Test void whenUncaughtExceptionInPublish_taskStillScheduled() throws InterruptedException { pushMeterRegistry.start(threadFactory); assertThat(latch.await(500,TimeUnit.MILLISECONDS)) .as("publish should continue to be scheduled even if an uncaught exception is thrown") .isTrue(); }
PushMeterRegistry extends MeterRegistry { @Override public void close() { if (config.enabled()) { publishSafely(); } stop(); super.close(); } protected PushMeterRegistry(PushRegistryConfig config, Clock clock); @Deprecated final void start(); void start(ThreadFactory threadFactory); void stop(); @Override void close()...
@Test void whenUncaughtExceptionInPublish_closeRegistrySuccessful() { assertThatCode(() -> pushMeterRegistry.close()).doesNotThrowAnyException(); }
StepFunctionTimer implements FunctionTimer { public double totalTime(TimeUnit unit) { accumulateCountAndTotal(); return TimeUtils.convert(countTotal.poll2(), baseTimeUnit(), unit); } StepFunctionTimer(Id id, Clock clock, long stepMillis, T obj, ToLongFunction<T> countFunction, ToDoubleFunct...
@Test void totalTimeWhenStateObjectChangedToNullShouldWorkWithChangedTimeUnit() { MockClock clock = new MockClock(); StepFunctionTimer<Object> functionTimer = new StepFunctionTimer<>( mock(Meter.Id.class), clock, 1000L, new Object(), (o) -> 1L, (o) -> 1d, TimeUnit.SECONDS, TimeUnit.SECONDS ); clock.add(Duration.ofSecon...
StepFunctionTimer implements FunctionTimer { public double count() { accumulateCountAndTotal(); return countTotal.poll1(); } StepFunctionTimer(Id id, Clock clock, long stepMillis, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit, ...
@SuppressWarnings("ConstantConditions") @Issue("#1814") @Test void meanShouldWorkIfTotalNotCalled() { Queue<Long> counts = new LinkedList<>(); counts.add(2L); counts.add(5L); counts.add(10L); Queue<Double> totalTimes = new LinkedList<>(); totalTimes.add(150.0); totalTimes.add(300.0); totalTimes.add(1000.0); Duration st...
StepValue { public V poll() { rollCount(clock.wallTime()); return previous; } StepValue(final Clock clock, final long stepMillis); V poll(); }
@Test void poll() { final AtomicLong aLong = new AtomicLong(42); final long stepTime = 60; final StepValue<Long> stepValue = new StepValue<Long>(clock, stepTime) { @Override public Supplier<Long> valueSupplier() { return () -> aLong.getAndSet(0); } @Override public Long noValue() { return 0L; } }; assertThat(stepValue....
AppOpticsMeterRegistry extends StepMeterRegistry { Optional<String> writeGauge(Gauge gauge) { double value = gauge.value(); if (!Double.isFinite(value)) { return Optional.empty(); } return Optional.of(write(gauge.getId(), "gauge", Fields.Value.tag(), decimal(value))); } @SuppressWarnings("deprecation") AppOpticsMeterR...
@Test void writeGauge() { meterRegistry.gauge("my.gauge", 1d); Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge).isPresent()).isTrue(); } @Test void writeGaugeShouldDropNanValue() { meterRegistry.gauge("my.gauge", Double.NaN); Gauge gauge = meterRegistry.find("my.gauge").g...
StepFunctionCounter extends AbstractMeter implements FunctionCounter { @Override public double count() { T obj2 = ref.get(); if (obj2 != null) { double prevLast = last; last = f.applyAsDouble(obj2); count.getCurrent().add(last - prevLast); } return count.poll(); } StepFunctionCounter(Id id, Clock clock, long stepMillis...
@Test void count() { AtomicInteger n = new AtomicInteger(1); FunctionCounter counter = registry.more().counter("my.counter", Tags.empty(), n); assertThat(counter).isInstanceOf(StepFunctionCounter.class); assertThat(counter.count()).isEqualTo(0); clock.add(config.step()); assertThat(counter.count()).isEqualTo(1); }
MultiGauge { private MultiGauge(MeterRegistry registry, Meter.Id commonId) { this.registry = registry; this.commonId = commonId; } private MultiGauge(MeterRegistry registry, Meter.Id commonId); static Builder builder(String name); void register(Iterable<Row<?>> rows); @SuppressWarnings("unchecked") void register(Itera...
@Test void multiGauge() { colorGauges.register(Stream.of(RED, GREEN).map(c -> c.toRow(1.0)).collect(toList())); assertThat(registry.get("colors").gauges().stream().map(g -> g.getId().getTag("color"))) .containsExactlyInAnyOrder("red", "green"); colorGauges.register(Stream.of(RED, BLUE).map(c -> c.toRow(1.0)).collect(to...
MultiGauge { public void register(Iterable<Row<?>> rows) { register(rows, false); } private MultiGauge(MeterRegistry registry, Meter.Id commonId); static Builder builder(String name); void register(Iterable<Row<?>> rows); @SuppressWarnings("unchecked") void register(Iterable<Row<?>> rows, boolean overwrite); }
@Test void overwriteFunctionDefinitions() { List<Color> colors = Arrays.asList(RED, GREEN, BLUE); colorGauges.register(colors.stream().map(c -> c.toRow(1.0)).collect(toList())); colorGauges.register(colors.stream().map(c -> c.toRow(2.0)).collect(toList()), true); for (Color color : colors) { assertThat(registry.get("co...
FixedBoundaryVictoriaMetricsHistogram implements Histogram { public static String getRangeTagValue(double value) { IdxOffset idxOffset = getBucketIdxAndOffset(value); return VMRANGES[getRangeIndex(idxOffset.bucketIdx, idxOffset.offset)]; } FixedBoundaryVictoriaMetricsHistogram(); @Override void recordLong(long value); ...
@Test void checkUpperBoundLookup() { try (FixedBoundaryVictoriaMetricsHistogram histogram = new FixedBoundaryVictoriaMetricsHistogram()) { assertThat(histogram.getRangeTagValue(0.0d)).isEqualTo("0...0"); assertThat(histogram.getRangeTagValue(1e-9d)).isEqualTo("0...1.0e-9"); assertThat(histogram.getRangeTagValue(Double....
DistributionStatisticConfig implements Mergeable<DistributionStatisticConfig> { @Override public DistributionStatisticConfig merge(DistributionStatisticConfig parent) { return DistributionStatisticConfig.builder() .percentilesHistogram(this.percentileHistogram == null ? parent.percentileHistogram : this.percentileHisto...
@Test void merge() { DistributionStatisticConfig c1 = DistributionStatisticConfig.builder().percentiles(0.95).build(); DistributionStatisticConfig c2 = DistributionStatisticConfig.builder().percentiles(0.90).build(); DistributionStatisticConfig merged = c2.merge(c1).merge(DistributionStatisticConfig.DEFAULT); assertTha...
HistogramGauges { public static HistogramGauges register(HistogramSupport meter, MeterRegistry registry, Function<ValueAtPercentile, String> percentileName, Function<ValueAtPercentile, Iterable<Tag>> percentileTags, Function<ValueAtPercentile, Double> percentileValue, Function<CountAtBucket, String> bucketName, Functio...
@Test void meterFiltersAreOnlyAppliedOnceToHistogramsAndPercentiles() { MeterRegistry registry = new SimpleMeterRegistry(); registry.config().meterFilter(new MeterFilter() { @Override public Meter.Id map(Meter.Id id) { return id.withName("MYPREFIX." + id.getName()); } }); Timer.builder("my.timer") .serviceLevelObjectiv...
TimeWindowPercentileHistogram extends AbstractTimeWindowHistogram<DoubleRecorder, DoubleHistogram> { @Override void recordDouble(DoubleRecorder bucket, double value) { bucket.recordValue(value); } TimeWindowPercentileHistogram(Clock clock, DistributionStatisticConfig distributionStatisticConfig, ...
@Test void histogramsAreCumulative() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), DistributionStatisticConfig.builder() .serviceLevelObjectives(3.0, 6, 7) .build() .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(3); assertThat(histogra...
TimeWindowPercentileHistogram extends AbstractTimeWindowHistogram<DoubleRecorder, DoubleHistogram> { @Override void recordLong(DoubleRecorder bucket, long value) { bucket.recordValue(value); } TimeWindowPercentileHistogram(Clock clock, DistributionStatisticConfig distributionStatisticConfig, ...
@Test void percentiles() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), DistributionStatisticConfig.builder() .percentiles(0.5, 0.9, 0.95) .minimumExpectedValue(millisToUnit(1, TimeUnit.NANOSECONDS)) .maximumExpectedValue(secondsToUnit(30, TimeUnit.NANOSECONDS)) .bui...
TimeWindowFixedBoundaryHistogram extends AbstractTimeWindowHistogram<TimeWindowFixedBoundaryHistogram.FixedBoundaryHistogram, Void> { @Override final void recordDouble(FixedBoundaryHistogram bucket, double value) { recordLong(bucket, (long) Math.ceil(value)); } TimeWindowFixedBoundaryHistogram(Clock clock, Distribution...
@Test void histogramsAreCumulative() { try (TimeWindowFixedBoundaryHistogram histogram = new TimeWindowFixedBoundaryHistogram(new MockClock(), DistributionStatisticConfig.builder() .serviceLevelObjectives(3.0, 6, 7) .bufferLength(1) .build() .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(...
CountedAspect { private Counter.Builder counter(ProceedingJoinPoint pjp, Counted counted) { Counter.Builder builder = Counter.builder(counted.value()).tags(tagsBasedOnJoinPoint.apply(pjp)); String description = counted.description(); if (!description.isEmpty()) { builder.description(description); } return builder; } Co...
@Test void countedWithoutSuccessfulMetrics() { countedService.succeedWithoutMetrics(); assertThatThrownBy(() -> meterRegistry.get("metric.none").counter()) .isInstanceOf(MeterNotFoundException.class); } @Test void countedWithSuccessfulMetrics() { countedService.succeedWithMetrics(); Counter counter = meterRegistry.get(...
DefaultJerseyTagsProvider implements JerseyTagsProvider { @Override public Iterable<Tag> httpRequestTags(RequestEvent event) { ContainerResponse response = event.getContainerResponse(); return Tags.of(JerseyTags.method(event.getContainerRequest()), JerseyTags.uri(event), JerseyTags.exception(event), JerseyTags.status(r...
@Test public void testRootPath() { assertThat(tagsProvider.httpRequestTags(event(200, null, "/", (String[]) null))) .containsExactlyInAnyOrder(tagsFrom("root", 200, null, "SUCCESS")); } @Test public void templatedPathsAreReturned() { assertThat(tagsProvider.httpRequestTags(event(200, null, "/", "/", "/hello/{name}"))) ...
DefaultJerseyTagsProvider implements JerseyTagsProvider { @Override public Iterable<Tag> httpLongRequestTags(RequestEvent event) { return Tags.of(JerseyTags.method(event.getContainerRequest()), JerseyTags.uri(event)); } @Override Iterable<Tag> httpRequestTags(RequestEvent event); @Override Iterable<Tag> httpLongReques...
@Test public void longRequestTags() { assertThat(tagsProvider.httpLongRequestTags(event(0, null, "/app", (String[]) null))) .containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/app")); }
AppOpticsMeterRegistry extends StepMeterRegistry { Optional<String> writeTimeGauge(TimeGauge timeGauge) { double value = timeGauge.value(getBaseTimeUnit()); if (!Double.isFinite(value)) { return Optional.empty(); } return Optional.of(write(timeGauge.getId(), "timeGauge", Fields.Value.tag(), decimal(value))); } @Suppres...
@Test void writeTimeGauge() { AtomicReference<Double> obj = new AtomicReference<>(1d); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeTimeGauge(timeGauge).isPre...
AppOpticsMeterRegistry extends StepMeterRegistry { Optional<String> writeFunctionCounter(FunctionCounter counter) { double count = counter.count(); if (Double.isFinite(count) && count > 0) { return Optional.of(write(counter.getId(), "functionCounter", Fields.Value.tag(), decimal(count))); } return Optional.empty(); } @...
@Test void writeFunctionCounter() { FunctionCounter counter = FunctionCounter.builder("myCounter", 1d, Number::doubleValue).register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isTrue(); }
AppOpticsMeterRegistry extends StepMeterRegistry { @Override protected void publish() { try { String bodyMeasurementsPrefix = getBodyMeasurementsPrefix(); for (List<Meter> batch : MeterPartition.partition(this, config.batchSize())) { final List<String> meters = batch.stream() .map(meter -> meter.match( this::writeGauge...
@Test void emptyMetersDoNoPosting() { meterRegistry.publish(); verifyNoMoreInteractions(mockSender); }
AppOpticsMeterRegistry extends StepMeterRegistry { String getBodyMeasurementsPrefix() { long stepSeconds = config.step().getSeconds(); long wallTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(clock.wallTime()); if (config.floorTimes()) { wallTimeInSeconds -= wallTimeInSeconds % stepSeconds; } return String.format(BODY_...
@Test void defaultValueDoesNoFlooring() { clock.add(Duration.ofSeconds(63)); assertThat(meterRegistry.getBodyMeasurementsPrefix()).isEqualTo( String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 63)); } @Test void flooringRoundsToNearestStep() { meterRegistry = new AppOpticsMeterRegistry(configWithFlooring, c...
AtlasMeterRegistry extends MeterRegistry { @Override public void close() { stop(); super.close(); } AtlasMeterRegistry(AtlasConfig config, Clock clock); AtlasMeterRegistry(AtlasConfig config); void start(); void stop(); @Override void close(); Registry getSpectatorRegistry(); }
@Issue("#484") @Test void publishOneLastTimeOnClose(@WiremockResolver.Wiremock WireMockServer server) { AtlasConfig config = new AtlasConfig() { @Nullable @Override public String get(String k) { return null; } @Override public String uri() { return server.baseUrl() + "/api/v1/publish"; } }; server.stubFor(any(anyUrl())...
AtlasMeterRegistry extends MeterRegistry { public Registry getSpectatorRegistry() { return registry; } AtlasMeterRegistry(AtlasConfig config, Clock clock); AtlasMeterRegistry(AtlasConfig config); void start(); void stop(); @Override void close(); Registry getSpectatorRegistry(); }
@Issue("#2094") @Test void functionCounter() { AtomicLong count = new AtomicLong(); MockClock clock = new MockClock(); AtlasMeterRegistry registry = new AtlasMeterRegistry(new AtlasConfig() { @Nullable @Override public String get(String k) { return null; } @Override public Duration step() { return Duration.ofMinutes(1)...
AtlasNamingConvention implements NamingConvention { @Override public String tagKey(String key) { if (key.equals("name")) { key = "name.tag"; } else if (key.equals("statistic")) { key = "statistic.tag"; } return NamingConvention.camelCase.tagKey(key); } @Override String name(String name, Meter.Type type, @Nullable Stri...
@Issue("#544") @Test void replaceNameTag() { assertThat(namingConvention.tagKey("name")).isEqualTo("nameTag"); } @Test void replaceStatisticTag() { assertThat(namingConvention.tagKey("statistic")).isEqualTo("statisticTag"); }
SpectatorTimer extends AbstractTimer { @Override public double max(TimeUnit unit) { for (Measurement measurement : timer.measure()) { if (stream(measurement.id().tags().spliterator(), false) .anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) { return TimeUtils.secondsToUnit...
@Test void timerMax() { AtlasConfig atlasConfig = new AtlasConfig() { @Override public String get(String k) { return null; } @Override public Duration lwcStep() { return step(); } }; AtlasMeterRegistry registry = new AtlasMeterRegistry(atlasConfig, new MockClock()); Timer timer = registry.timer("timer"); timer.record(1...
DynatraceMeterRegistry extends StepMeterRegistry { void putCustomMetric(final DynatraceMetricDefinition customMetric) { try { httpClient.put(customMetricEndpointTemplate + customMetric.getMetricId() + "?api-token=" + config.apiToken()) .withJsonContent(customMetric.asJson()) .send() .onSuccess(response -> { logger.debu...
@Test void putCustomMetricOnSuccessShouldAddMetricIdToCreatedCustomMetrics() throws NoSuchFieldException, IllegalAccessException { Field createdCustomMetricsField = DynatraceMeterRegistry.class.getDeclaredField("createdCustomMetrics"); createdCustomMetricsField.setAccessible(true); @SuppressWarnings("unchecked") Set<St...
DynatraceMeterRegistry extends StepMeterRegistry { Stream<DynatraceCustomMetric> writeMeter(Meter meter) { final long wallTime = clock.wallTime(); return StreamSupport.stream(meter.measure().spliterator(), false) .map(Measurement::getValue) .filter(Double::isFinite) .map(value -> createCustomMetric(meter.getId(), wallT...
@Test void writeMeterWithGauge() { meterRegistry.gauge("my.gauge", 1d); Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeMeter(gauge)).hasSize(1); } @Test void writeMeterWithGaugeShouldDropNanValue() { meterRegistry.gauge("my.gauge", Double.NaN); Gauge gauge = meterRegistry.find("my.g...
DynatraceMeterRegistry extends StepMeterRegistry { List<DynatraceBatchedPayload> createPostMessages(String type, String group, List<DynatraceTimeSeries> timeSeries) { final String header = "{\"type\":\"" + type + '\"' + (StringUtils.isNotBlank(group) ? ",\"group\":\"" + group + '\"' : "") + ",\"series\":["; final Strin...
@Test void whenAllTsTooLargeEmptyMessageListReturned() { List<DynatraceBatchedPayload> messages = meterRegistry.createPostMessages("my.type", null, Collections.singletonList(createTimeSeriesWithDimensions(10_000))); assertThat(messages).isEmpty(); } @Test void splitsWhenExactlyExceedingMaxByComma() { List<DynatraceBatc...
DynatraceMetricDefinition { String asJson() { String displayName = description == null ? metricId : StringEscapeUtils.escapeJson(description); String body = "{\"displayName\":\"" + StringUtils.truncate(displayName, MAX_DISPLAY_NAME) + "\""; if (StringUtils.isNotBlank(group)) body += ",\"group\":\"" + StringUtils.trunca...
@Test void usesMetricIdAsDescriptionWhenDescriptionIsNotAvailable() { final DynatraceMetricDefinition metric = new DynatraceMetricDefinition("custom:test.metric", null, null, null, technologyTypes, null); assertThat(metric.asJson()).isEqualTo("{\"displayName\":\"custom:test.metric\",\"types\":[\"java\"]}"); } @Test voi...
DynatraceNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return "custom:" + sanitizeName(delegate.name(name, type, baseUnit)); } DynatraceNamingConvention(NamingConvention delegate); DynatraceNamingConvention(); @Override String nam...
@Test void nameStartsWithCustomAndColon() { assertThat(convention.name("mymetric", Meter.Type.COUNTER, null)).isEqualTo("custom:mymetric"); } @Test void nameShouldAllowAlphanumericUnderscoreAndDash() { assertThat(convention.name("my.name1", Meter.Type.COUNTER, null)).isEqualTo("custom:my.name1"); assertThat(convention....
DynatraceNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return KEY_CLEANUP_PATTERN.matcher(delegate.tagKey(key)).replaceAll("_"); } DynatraceNamingConvention(NamingConvention delegate); DynatraceNamingConvention(); @Override String name(String name, Meter.Type type, @Nullab...
@Test void tagKeysAreSanitized() { assertThat(convention.tagKey("{tagTag0}.-")).isEqualTo("_tagTag0_.-"); }
DynatraceTimeSeries { String asJson() { String body = "{\"timeseriesId\":\"" + metricId + "\"" + ",\"dataPoints\":[[" + time + "," + DoubleFormat.wholeOrDecimal(value) + "]]"; if (dimensions != null && !dimensions.isEmpty()) { body += ",\"dimensions\":{" + dimensions.entrySet().stream() .map(t -> "\"" + t.getKey() + "\...
@Test void addsDimensionsValuesWhenAvailable() { final Map<String, String> dimensions = new HashMap<>(); dimensions.put("first", "one"); dimensions.put("second", "two"); final DynatraceTimeSeries timeSeries = new DynatraceTimeSeries("custom:test.metric", 12345, 1, dimensions); assertThat(timeSeries.asJson()).isEqualTo(...
PrometheusRenameFilter implements MeterFilter { @Override public Meter.Id map(Meter.Id id) { String convertedName = MICROMETER_TO_PROMETHEUS_NAMES.get(id.getName()); return convertedName == null ? id : id.withName(convertedName); } @Override Meter.Id map(Meter.Id id); }
@Test void doesNotChangeUnrelatedMeter() { Meter.Id original = Gauge.builder("system.cpu.count", () -> 1.0).register(registry).getId(); Meter.Id actual = filter.map(original); assertThat(actual).isEqualTo(original); } @Test void doesChangeApplicableMeter() { Meter.Id original = Gauge.builder("process.files.open", () ->...
PrometheusMeterRegistry extends MeterRegistry { public PrometheusMeterRegistry throwExceptionOnRegistrationFailure() { config().onMeterRegistrationFailed((id, reason) -> { throw new IllegalArgumentException(reason); }); return this; } PrometheusMeterRegistry(PrometheusConfig config); PrometheusMeterRegistry(Prometheus...
@Test void meterRegistrationFailedListenerCalledOnSameNameDifferentTags() throws InterruptedException { CountDownLatch failedLatch = new CountDownLatch(1); registry.config().onMeterRegistrationFailed((id, reason) -> failedLatch.countDown()); registry.counter("my.counter"); registry.counter("my.counter", "k", "v").incre...
PrometheusMeterRegistry extends MeterRegistry { public CollectorRegistry getPrometheusRegistry() { return registry; } PrometheusMeterRegistry(PrometheusConfig config); PrometheusMeterRegistry(PrometheusConfig config, CollectorRegistry registry, Clock clock); String scrape(); void scrape(Writer writer); @Override Count...
@Issue("#27") @DisplayName("custom distribution summaries respect varying tags") @Test void customSummaries() { Arrays.asList("v1", "v2").forEach(v -> { registry.summary("s", "k", v).record(1.0); assertThat(registry.getPrometheusRegistry().getSampleValue("s_count", new String[]{"k"}, new String[]{v})) .describedAs("dis...
CacheController { public ClientConnection getConnection(String deviceName){ synchronized (clientCache) { List<ClientConnection> clientConnections = clientCache.get(deviceName); if (clientConnections != null && !clientConnections.isEmpty()){ for (ClientConnection c : clientConnections){ if (!isConnectionExpired(c)){ ret...
@Test public void whenSearchForUnkownGetsNull(){ assertThat(ctl.getConnection("192.168.2.1")).isNull(); }
DeviceManager implements RadarListener { @Override public void deviceEntered(NetworkDevice device) { if (device == null ) return; String deviceHost = connectionManagerControlCenter.getHost(device.getNetworkDeviceName()); for (UpNetworkInterface networkInterface : this.currentDevice.getNetworks()) { String currentDevice...
@Test public void AfterListingIfProxyingIsEnabledRegisterIt() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn( new Response().addParameter("device", new UpDevice("A") .addNetworkInterface("A", "T").toString())); JSONObject driverList = new ...
DeviceManager implements RadarListener { @Override public void deviceLeft(NetworkDevice device) { if (device == null || device.getNetworkDeviceName() == null || device.getNetworkDeviceType() == null) return; logger.info("Device "+device.getNetworkDeviceName()+" of type "+device.getNetworkDeviceType()+" leaving."); Stri...
@Test public void doNothingWhenLeftingAnUnkownDevice() throws Exception { NetworkDevice leavingGuy = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); assertEquals(1, dao.list().size()); UpDriver driver = new UpDriver("DD"); driver.addService("s"); driverDao .insert(new DriverModel("id1", driver, currentDevice.getName())); ...
ReflectionServiceCaller { public Response callServiceOnDriver(Call serviceCall, Object instanceDriver, CallContext messageContext) throws DriverManagerException{ if (instanceDriver != null){ try { Method serviceMethod = findMethod(serviceCall, instanceDriver); if (serviceMethod != null) { logger.info("Calling service (...
@Test(expected=DriverManagerException.class) public void shouldFailOnAnNullDriver() throws Exception{ caller.callServiceOnDriver(null, null, null); } @Test(expected=DriverManagerException.class) public void shouldFailOnAnNonExistantServiceMethod() throws Exception{ caller.callServiceOnDriver(new Call(null, "nonExistant...
Notify extends Message { public static Notify fromJSON(JSONObject json) throws JSONException { Notify e = new Notify(); Message.fromJSON(e, json); e.setEventKey(json.optString("eventKey",null)); e.setDriver(json.optString("driver",null)); e.setInstanceId(json.optString("instanceId",null)); if(json.has("parameters")){ e...
@Test public void fromJSON() throws JSONException{ assertThat(dummyNotify()).isEqualTo(Notify.fromJSON(dummyJSON())); } @Test public void fromJSONWithEmpty() throws JSONException{ assertThat(new Notify()).isEqualTo(Notify.fromJSON(new JSONObject())); }
DriverDao { public void insert(DriverModel driver) { DriverModel found = retrieve(driver.id(), driver.device()); if (found != null){ removeFromMap(found); } insertOnMap(driver); } DriverDao(InitialProperties bundle); void insert(DriverModel driver); List<DriverModel> list(); List<DriverModel> list(String name); List<Dr...
@Ignore @Test(expected=Exception.class) public void mustNotAcceptTwoDriversWithTheSameIdAndSameDevice(){ dao.insert(createDriver("a", "a")); dao.insert(createDriver("a", "a")); }
DriverManager { public Response handleServiceCall(Call serviceCall, CallContext messageContext) throws DriverManagerException{ DriverModel model = null; if (serviceCall.getInstanceId() != null ){ model = driverDao.retrieve(serviceCall.getInstanceId(),currentDevice.getName()); if (model == null){ logger.severe("No Insta...
@Test(expected=DriverManagerException.class) public void shouldFailCallingServiceOnDriverUsingAnInvalidInstanceId() throws DriverManagerException, InterfaceValidationException, DriverNotFoundException{ manager.handleServiceCall(new Call("driver","service","id"), null); } @Test(expected=DriverManagerException.class) pub...
DriverManager { public List<UosDriver> listDrivers(){ List<DriverModel> list = driverDao.list(null,currentDevice.getName()); if (list.isEmpty()) return new ArrayList<UosDriver>(); List<UosDriver> ret = new ArrayList<UosDriver>(); for (DriverModel m : list){ ret.add(instances.get(m.rowid())); } return ret; } DriverManag...
@Test public void shouldListNullWhenNothingWasDeployed() throws Exception{ assertThat(manager.listDrivers()).isEmpty(); }
DriverManager { public void initDrivers(Gateway gateway, InitialProperties properties){ try { if (driverDao.list("uos.DeviceDriver").isEmpty()){ DeviceDriver deviceDriver = new DeviceDriver(); deployDriver(deviceDriver.getDriver(), deviceDriver); } } catch (Exception e) { throw new RuntimeException(e); } Iterator<Strin...
@Test public void shouldDoNothingWithoutDriversToInit() throws DriverManagerException, InterfaceValidationException{ manager.initDrivers(null, null); }
DriverManager { public void tearDown(){ for (DriverModel d : driverDao.list()){ undeployDriver(d.id()); } dCount = 0; } DriverManager(UpDevice currentDevice, DriverDao driverDao, DeviceDao deviceDao, ReflectionServiceCaller serviceCaller); Response handleServiceCall(Call serviceCall, CallContext messageContext); void ...
@Test public void shouldDoNothingWithoutDriversToTearDown() throws DriverManagerException, InterfaceValidationException{ manager.tearDown(); }
DriverData { public boolean equals(Object obj) { if (obj != null && obj instanceof DriverData){ DriverData temp = (DriverData)obj; if (temp.driver != null && temp.device != null && temp.instanceID != null){ return temp.driver.equals(this.driver) && temp.device.equals(this.device) && temp.instanceID.equals(this.instance...
@Test public void notEqualsNull(){ assertFalse(new DriverData(null,null,null).equals(null)); } @Test public void notEqualsOtherThings(){ assertFalse(new DriverData(null,null,null).equals(new Object())); } @Test public void notEqualsWithDifferentDriver(){ DriverData thiz = new DriverData(new UpDriver("a"),null,null); Dr...
ApplicationManager { public void add(UosApplication app) { add(app, assignAName(app, null)); } ApplicationManager(InitialProperties properties, Gateway gateway, ConnectionManagerControlCenter connectionManagerControlCenter); void add(UosApplication app); void add(UosApplication app, String id); void startApplication...
@Test public void addingAnApplicationDoesNothingToIt(){ DummyApp app = new DummyApp(); manager.add(app); assertThat(app.inited).isFalse(); assertThat(app.started).isFalse(); assertThat(app.stoped).isFalse(); assertThat(app.finished).isFalse(); }
ApplicationManager { public void deploy(UosApplication app) { deploy(app, null); } ApplicationManager(InitialProperties properties, Gateway gateway, ConnectionManagerControlCenter connectionManagerControlCenter); void add(UosApplication app); void add(UosApplication app, String id); void startApplications(); void de...
@Test public void deployDoesInitsAndStarts() throws InterruptedException{ final DummyApp app = new DummyApp(); manager.deploy(app); waitToStart(app); assertThat(app.inited).isTrue(); assertThat(app.started).isTrue(); assertThat(app.stoped).isFalse(); assertThat(app.finished).isFalse(); }
EventManager implements NotifyHandler { public void register(UosEventListener listener, UpDevice device, String driver, String instanceId, String eventKey, Map<String,Object> parameters) throws NotifyException{ String eventIdentifier = getEventIdentifier(device, driver, instanceId, eventKey); logger.fine("Registering l...
@Test public void registeringDelegatesToMessageEngine() throws Exception{ UpDevice device = new UpDevice("the_device"); manager.register(listener, device, "driver", "id", "key", null); verify(engine).callService(eq(device), call.capture()); assertThat(call.getAllValues()).hasSize(1); assertThat(call.getValue().getServi...
MessageHandler { public Response callService(UpDevice device,Call serviceCall) throws MessageEngineException{ if ( device == null || serviceCall == null || serviceCall.getDriver() == null || serviceCall.getDriver().isEmpty() || serviceCall.getService() == null || serviceCall.getService().isEmpty()){ throw new IllegalAr...
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectANullCall() throws Exception{ handler.callService(mock(UpDevice.class),null); } @Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectANullDevice() throws Exception{ handler.callService(null,new Call("d", "s"...
EventManager implements NotifyHandler { public void notify(Notify notify, UpDevice device) throws NotifyException{ try { if(device == null){ handleNofify(notify, device); }else{ messageEngine.notify(notify, device); } } catch (MessageEngineException e) { throw new NotifyException(e); } } EventManager(MessageEngine mess...
@Test public void notifyDelegatesToMessageEngine() throws Exception{ UpDevice device = new UpDevice("the_device"); Notify notify = new Notify("a"); manager.notify(notify, device); verify(engine).notify(eq(notify),eq(device)); }
EventManager implements NotifyHandler { public void unregister(UosEventListener listener, UpDevice device, String driver, String instanceId, String eventKey) throws NotifyException{ List<ListenerInfo> listeners = findListeners( device, driver, instanceId, eventKey); if (listeners == null){ return; } NotifyException exc...
@Test public void dontFailWehnUnregisteringWithoutRegistering() throws Exception{ manager.unregister( listener, new UpDevice("the_device"), "driver", "id", "key"); }
SmartSpaceGateway implements Gateway { public Response callService(UpDevice device, String serviceName, String driverName, String instanceId, String securityType, Map<String, Object> parameters) throws ServiceCallException { return adaptabilityEngine.callService(device, serviceName, driverName, instanceId, securityType...
@Test public void callServiceDelegatesToAdaptabilityEngine() throws Exception{ UpDevice target = new UpDevice("a"); Call call = new Call("d", "s"); gateway.callService(target, call); verify(engine).callService(target, call); } @Test public void callServiceWithMultipleParamsAlsoDelegatesToAdaptabilityEngine() throws Exc...
SmartSpaceGateway implements Gateway { public void register(UosEventListener listener, UpDevice device, String driver, String eventKey) throws NotifyException { register(listener, device, driver, null,eventKey); } void init(AdaptabilityEngine adaptabilityEngine, UpDevice currentDevice, SecurityManager securityManag...
@Test public void registerForEventDelegatesToAdaptabilityEngine() throws Exception{ UpDevice target = new UpDevice("a"); UosEventListener listener = new EventListener(); gateway.register(listener,target, "d", "e"); verify(engine).register(listener, target, "d", null, "e",null); } @Test public void registerForEventWithM...
SmartSpaceGateway implements Gateway { public void notify(Notify notify, UpDevice device) throws NotifyException { adaptabilityEngine.notify(notify, device); } void init(AdaptabilityEngine adaptabilityEngine, UpDevice currentDevice, SecurityManager securityManager, ConnectivityManager connectivityManager, Dev...
@Test public void sendEventNotifyDelegatesToAdaptabilityEngine() throws Exception{ UpDevice target = new UpDevice("a"); Notify event = new Notify("d", "s"); gateway.notify(event, target); verify(engine).notify(event, target); }
SmartSpaceGateway implements Gateway { public void unregister(UosEventListener listener) throws NotifyException { adaptabilityEngine.unregister(listener); } void init(AdaptabilityEngine adaptabilityEngine, UpDevice currentDevice, SecurityManager securityManager, ConnectivityManager connectivityManager, Device...
@Test public void unregisterForEventDelegatesToAdaptabilityEngine() throws Exception{ UosEventListener listener = new EventListener(); gateway.unregister(listener); verify(engine).unregister(listener); } @Test public void unregisterForEventWithMultipleParamsAlsoDelegatesToAdaptabilityEngine() throws Exception{ UosEvent...
SmartSpaceGateway implements Gateway { public List<DriverData> listDrivers(String driverName) { return driverManager.listDrivers(driverName, null); } void init(AdaptabilityEngine adaptabilityEngine, UpDevice currentDevice, SecurityManager securityManager, ConnectivityManager connectivityManager, DeviceManager...
@Test public void listDriversDelegatesToDriverManagerConsideringAllDevices(){ List<DriverData> data = new ArrayList<DriverData>(); when(driverManager.listDrivers("d", null)).thenReturn(data); assertThat(gateway.listDrivers("d")).isSameAs(data); verify(driverManager).listDrivers("d", null); }
SmartSpaceGateway implements Gateway { public List<UpDevice> listDevices() { return deviceManager.listDevices(); } void init(AdaptabilityEngine adaptabilityEngine, UpDevice currentDevice, SecurityManager securityManager, ConnectivityManager connectivityManager, DeviceManager deviceManager, DriverManager drive...
@Test public void listDevicesDelegatesToDeviceManager(){ List<UpDevice> data = new ArrayList<UpDevice>(); when(deviceManager.listDevices()).thenReturn(data); assertThat(gateway.listDevices()).isSameAs(data); verify(deviceManager).listDevices(); }
DeviceDriver implements UosDriver { @Override public UpDriver getDriver() { return driver; } DeviceDriver(); @Override UpDriver getDriver(); @Override void init(Gateway gateway, InitialProperties properties, String instanceId); @Override void destroy(); @Override List<UpDriver> getParent(); @SuppressWarnings("unchecked...
@Test public void declareTheInterfaceProperly(){ assertThat(instance.getDriver().getName()).isEqualTo("uos.DeviceDriver"); } @Test public void declareListDriver(){ assertThat(instance.getDriver().getServices()) .contains( new UpService("listDrivers") .addParameter("driverName", UpService.ParameterType.OPTIONAL) ); } @T...
Notify extends Message { @Override public boolean equals(Object obj) { if (obj == null){ return false; } if (!( obj instanceof Notify)){ return false; } Notify temp = (Notify) obj; if(!compare(this.eventKey,temp.eventKey)) return false; if(!compare(this.driver,temp.driver)) return false; if(!compare(this.instanceId,tem...
@Test public void equalsNull() { assertFalse(new Notify().equals(null)); } @Test public void notEquals(){ assertFalse(new Notify().equals("something")); } @Test public void notEqualsToOtherThing(){ assertFalse(new Notify("e1").equals(new Notify("e2"))); assertFalse(new Notify("e","d1").equals(new Notify("e","d2"))); as...
MessageHandler { public void notifyEvent(Notify notify, UpDevice device) throws MessageEngineException{ if ( device == null || notify == null || notify.getDriver() == null || notify.getDriver().isEmpty() || notify.getEventKey() == null || notify.getEventKey().isEmpty()){ throw new IllegalArgumentException("Either the D...
@Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectANullEvent() throws Exception{ handler.notifyEvent(null,mock(UpDevice.class)); } @Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectANullDevice() throws Exception{ handler.notifyEvent(new Notify("d", "s"),...
UpDriver { @Override public boolean equals(Object obj) { if (obj == null || ! (obj instanceof UpDriver) ) return false; UpDriver d = (UpDriver) obj; if(!compare(this.name,d.name)) return false; if(!compare(this.services,d.services)) return false; if(!compare(this.events,d.events)) return false; return true; } UpDriver(...
@Test public void equalsNull() { assertFalse(new UpDriver(null).equals(null)); } @Test public void notEquals(){ assertFalse(new UpDriver("oneThing").equals(new UpDriver("otherThing"))); } @Test public void notEqualsToOtherThing(){ assertFalse(new UpDriver("oneThing").equals("otherThing")); } @Test public void notEquals...
UpDriver { @Override public int hashCode() { if(name != null){ return name.hashCode(); } return super.hashCode(); } UpDriver(); UpDriver(String name); String getName(); void setName(String name); List<UpService> getServices(); void setServices(List<UpService> services); UpService addService(UpService service); UpServi...
@Test public void hash(){ UpDriver driver1 = new UpDriver("driver"); UpDriver driver2 = new UpDriver("driver"); UpDriver driver3 = new UpDriver("notdriver"); assertThat(driver2.hashCode()).isEqualTo(driver1.hashCode()); assertThat(driver3.hashCode()).isNotEqualTo(driver1.hashCode()); }
UpDriver { public JSONObject toJSON() throws JSONException { JSONObject json = new JSONObject(); json.put("name", this.getName()); addServices(json, "services", this.services); addServices(json, "events", this.events); addStrings(json, "equivalent_drivers", equivalentDrivers); return json; } UpDriver(); UpDriver(Strin...
@Test public void toJson() throws JSONException{ assertThat(dummyDriver().toJSON().toMap()) .isEqualTo(dummyJSONDriver().toMap()); } @Test public void toJsonForEmtyData() throws JSONException{ UpDriver driver = new UpDriver(); JSONObject json = new JSONObject(); json.put("name", (String)null); assertThat(driver.toJSON(...
UpDriver { public static UpDriver fromJSON(JSONObject json) throws JSONException { UpDriver d = new UpDriver(json.optString("name",null)); d.services = addServices(json, "services"); d.events = addServices(json, "events"); d.equivalentDrivers = addStrings(json, "equivalent_drivers"); return d; } UpDriver(); UpDriver(S...
@Test public void fromJson() throws JSONException{ JSONObject json = dummyJSONDriver(); assertThat(UpDriver.fromJSON(json)).isEqualTo(dummyDriver()); } @Test public void fromJsonForEmptyData() throws JSONException{ assertThat(UpDriver.fromJSON(new JSONObject())).isEqualTo(new UpDriver()); }
UpDevice { @Override public boolean equals(Object obj) { if (obj == null || ! (obj instanceof UpDevice) ){ return false; } UpDevice d = (UpDevice) obj; if(!compare(this.name,d.name)) return false; if(!compare(this.networks,d.networks)) return false; if(!compare(this.meta,d.meta)) return false; return true; } UpDevice()...
@Test public void equalsNull() { assertFalse(new UpDevice(null).equals(null)); } @Test public void notEquals(){ assertFalse(new UpDevice("d").equals("somthing")); } @Test public void notEqualsToOtherThing(){ assertFalse(new UpDevice("d").equals(new UpDevice("otherD"))); } @Test public void notEqualsWithNullName(){ asse...
UpDevice { @Override public int hashCode() { if(name != null){ return name.hashCode(); } return super.hashCode(); } UpDevice(); UpDevice(String name); UpDevice addNetworkInterface(String networkAdress, String networkType); String getName(); void setName(String name); List<UpNetworkInterface> getNetworks(); void setNet...
@Test public void hash(){ UpDevice d1 = new UpDevice("device"); UpDevice d2 = new UpDevice("device"); UpDevice d3 = new UpDevice("notdevice"); assertThat(d2.hashCode()).isEqualTo(d1.hashCode()); assertThat(d3.hashCode()).isNotEqualTo(d1.hashCode()); }
UpDevice { public JSONObject toJSON() throws JSONException { JSONObject json = new JSONObject(); json.put("name", this.name); addNetworks(json, "networks"); addMeta(json); return json; } UpDevice(); UpDevice(String name); UpDevice addNetworkInterface(String networkAdress, String networkType); String getName(); void se...
@Test public void toJson() throws JSONException{ UpDevice device = dummyDevice(); JSONObject json = dummyJSONDevice(); assertThat(device.toJSON().toMap()) .isEqualTo(json.toMap()); } @Test public void toJsonFromEmpty() throws JSONException{ assertThat(new UpDevice().toJSON().toMap()) .isEqualTo(new JSONObject().toMap()...
UpDevice { public static UpDevice fromJSON(JSONObject json) throws JSONException { UpDevice device = new UpDevice(); device.name = json.optString("name", null); device.networks = fromNetworks(json, "networks"); device.meta = fromMeta(json); return device; } UpDevice(); UpDevice(String name); UpDevice addNetworkInterfa...
@Test public void fromJSON() throws JSONException{ assertThat(UpDevice.fromJSON(dummyJSONDevice())) .isEqualTo(dummyDevice()); } @Test public void fromJSONString() throws JSONException{ JSONObject dummyJSONDevice = dummyJSONDevice(); JSONObject temp = new JSONObject(dummyJSONDevice.toMap()); assertThat(UpDevice.fromJSO...
MessageEngine implements MessageListener , UOSComponent { @Override public String handleIncomingMessage(String message,NetworkDevice clientDevice) throws NetworkException{ if (message == null || clientDevice == null) return null; try { JSONObject json = new JSONObject(message); Message.Type messageType = retrieveMessag...
@Test public void handleIncomingMessage_returnNullForNullMessage() throws Exception{ assertNull(engine.handleIncomingMessage(null, mock(NetworkDevice.class))); } @Test public void handleIncomingMessage_returnNullForNullDevice() throws Exception{ assertNull(engine.handleIncomingMessage("", null)); } @Test public void ha...
DeviceDao { public void save(UpDevice device) { if (device.getNetworks() != null){ for (UpNetworkInterface ni : device.getNetworks()){ interfaceMap.put(createInterfaceKey(ni), device); if(!networkTypeMap.containsKey(ni.getNetType())){ networkTypeMap.put(ni.getNetType(), new ArrayList<UpDevice>()); } networkTypeMap.get(...
@Ignore @Test(expected=Exception.class) public void should_not_save_a_device_with_the_same_name(){ dao.save(new UpDevice("my.device")); dao.save(new UpDevice("my.device")); }
DeviceManager implements RadarListener { public void registerDevice(UpDevice device) { deviceDao.save(device); } DeviceManager(UpDevice currentDevice, DeviceDao deviceDao, DriverDao driverDao, ConnectionManagerControlCenter connectionManagerControlCenter, ConnectivityManager connectivityManager, Gateway gatewa...
@Test public void shouldSaveWhenRegistering() { UpDevice toRegister = new UpDevice("aDevice").addNetworkInterface( "127.0.0.2", "Ethernet:TCP"); deviceManager.registerDevice(toRegister); List<UpDevice> devices = dao.list(null, null); assertNotNull(devices); assertEquals(2, devices.size()); assertTrue(devices.contains(t...
Notify extends Message { @Override public int hashCode() { int hash = 0; if (this.eventKey != null){ hash += this.eventKey.hashCode(); } if (this.driver != null){ hash += this.driver.hashCode(); } if (this.instanceId != null){ hash += this.instanceId.hashCode(); } return hash; } Notify(); Notify(String eventKey); Not...
@Test public void hash(){ Notify e1 = new Notify("e"); Notify e2 = new Notify("e"); Notify ed1 = new Notify("e","d"); Notify ed2 = new Notify("e","d"); Notify edid1 = new Notify("e","d","id"); Notify edid2 = new Notify("e","d","id"); Notify edid3 = new Notify("e","d","idx"); Notify edid4 = new Notify("e","dx","id"); No...
Notify extends Message { public JSONObject toJSON() throws JSONException { JSONObject json = super.toJSON(); json.put("eventKey",this.eventKey); json.put("driver",this.driver); json.put("instanceId",this.instanceId); if (this.parameters != null) json.put("parameters",this.parameters); return json; } Notify(); Notify(S...
@Test public void toJSON() throws JSONException{ assertThat(dummyJSON()).isEqualTo(dummyNotify().toJSON()); } @Test public void toJSONWithEmpty() throws JSONException{ JSONObject json = new JSONObject(){{ put("type", Message.Type.NOTIFY.name()); }}; assertThat(json).isEqualTo(new Notify().toJSON()); }
StringUtils { static boolean contains(char c, String what) { return what.indexOf(c) >= 0; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBu...
@Test public void testContains() { System.out.println("contains"); assertFalse(StringUtils.contains(' ', "")); assertTrue(StringUtils.contains('x', "xxxx")); assertTrue(StringUtils.contains('x', "xyz")); assertFalse(StringUtils.contains('x', "yyyyyyyyyyyy")); try { StringUtils.contains('x', null); fail( "nullpointer th...
StringUtils { public static String strip(StringBuilder s, String what) { int start = skip_char(s, what, 0); int end = skip_char_reverse(s, what, s.length() - 1); if (start > end) return s.substring(start); return s.substring(start, end + 1); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_s...
@Test public void testStrip_String_String() { System.out.println("strip"); try { StringUtils.strip( (String)null, "" ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } try { StringUtils.strip( (String)null, null ); fail( "nullpointer throws no exception"); } catch( NullPointerException ...
StringUtils { public static void set_defaultAutoLineLenght(int length) { defaultAutoLineLength = length; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String...
@Test public void testSet_defaultAutoLineLenght() { System.out.println("set_defaultAutoLineLenght"); StringUtils.set_defaultAutoLineLenght(10); assertEquals(10, StringUtils.get_defaultAutoLineLenght()); }
StringUtils { public static int get_defaultAutoLineLenght() { return defaultAutoLineLength; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(String...
@Test public void testGet_defaultAutoLineLenght() { System.out.println("get_defaultAutoLineLenght"); StringUtils.set_defaultAutoLineLenght(10); assertEquals(10, StringUtils.get_defaultAutoLineLenght()); }
StringUtils { public static String autoLineBreak(String what) { return autoLineBreak(what, defaultAutoLineLength); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); sta...
@Test public void testAutoLineBreak_StringBuilder_int() { System.out.println("autoLineBreak"); String res; res = StringUtils.autoLineBreak(new StringBuilder(testTextA),10); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA10, res); res = StringUtils.autoLineBreak(new StringBuilder(tes...
StringUtils { public static String formatDouble(double d, int rounding) { return formatDouble(Rounding.rndDouble(d, rounding)); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, S...
@Test public void testFormatDouble_double_int() { System.out.println("formatDouble"); assertEquals(String.format("%.3f", 12.234), StringUtils.formatDouble(12.2340000, 3) ); assertEquals(String.format("%.2f", 0.03), StringUtils.formatDouble(0.03, 3) ); assertEquals("12", StringUtils.formatDouble(12.0000, 3) ); } @Test p...
StringUtils { public static boolean isYes(String maybe_a_yes_value) { if (maybe_a_yes_value == null) { return false; } if (maybe_a_yes_value.equalsIgnoreCase("ja")) { return true; } if (maybe_a_yes_value.equalsIgnoreCase("yes")) { return true; } if (maybe_a_yes_value.equalsIgnoreCase("true")) { return true; } if (maybe...
@Test public void testIsYes() { System.out.println("isYes"); assertTrue(StringUtils.isYes("yes")); assertFalse(StringUtils.isYes("no")); assertTrue(StringUtils.isYes("X")); assertFalse(StringUtils.isYes(" ")); assertFalse(StringUtils.isYes(null)); assertFalse(StringUtils.isYes("0")); assertTrue(StringUtils.isYes("1"));...
StringUtils { @Deprecated public static String exceptionToString(Exception ex) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream s = new PrintStream(bos); ex.printStackTrace(s); s.flush(); return bos.toString(); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(Str...
@Test public void testExceptionToString() { System.out.println("exceptionToString"); try { int i = Integer.parseInt("asdfasdf"); } catch( NumberFormatException ex ) { String res = StringUtils.exceptionToString(ex); if( res.length() < 100 ) { System.out.println(res); fail( "something wrong with that exception to String ...
StringUtils { public static String skipLeadingLines(String sourceString, int lines) { if (lines <= 0) return sourceString; String truncatedString; int lbCounter = 0; int idx = 0; char[] arr = sourceString.toCharArray(); for (idx = 0; idx < arr.length; idx++) { if (lbCounter == lines) { break; } if (arr[idx] == '\n') { ...
@Test public void testSkipLeadingLines() { System.out.println("skipLeadingLines"); String testTest = "ONE\n" + "TWO\r\n" + "THREE\n" + "FOUR\n" + "\r\n" + "\r\n" + "FIVE\n"; assertEquals(testTest.substring(4), StringUtils.skipLeadingLines(testTest, 1)); assertEquals(testTest, StringUtils.skipLeadingLines(testTest, 0));...
StringUtils { static int skip_char(StringBuilder s, String what, int pos) { while (pos <= (s.length() - 1)) { char c; c = s.charAt(pos); if (contains(c, what)) { pos++; continue; } break; } return pos; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static ...
@Test public void testSkip_char() { System.out.println("skip_char"); assertEquals(12, StringUtils.skip_char(new StringBuilder( "das ist ein Text"), " ", 7)); assertEquals(2, StringUtils.skip_char(new StringBuilder( "das ist ein Text"), " ", 2)); assertEquals(4, StringUtils.skip_char(new StringBuilder( "das ist ein Text...
StringUtils { public static String byteArrayToString(byte[] data) { if (data == null) { return ""; } StringBuilder str = new StringBuilder(); for (int index = 0; index < data.length; index++) { str.append((char) (data[index])); } return str.toString(); } static int skip_spaces_reverse(StringBuilder s, int pos); static...
@Test public void testByteArrayToString() { System.out.println("byteArrayToString"); byte[] bytes = {72,97,108,108,111}; assertEquals("Hallo",StringUtils.byteArrayToString(bytes)); }
ParseJNLP { public Properties getProperties() { return properties; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }
@Test public void testGetProperties() throws ParserConfigurationException, IOException, SAXException { for( TestFile test : test_cases ) { System.out.println("getProperties for " + test.resource); ParseJNLP instance = new ParseJNLP(test.getFile()); Properties expResult = test.getProperties(); Properties result = instan...
ParseJNLP { public String getMainJar() { return mainJar; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }
@Test public void testGetMainJar() throws ParserConfigurationException, IOException, SAXException { for( TestFile test : test_cases ) { System.out.println("getMainJar for " + test.resource ); ParseJNLP instance = new ParseJNLP(test.getFile()); String expResult = test.getMainJar(); String result = instance.getMainJar();...
ParseJNLP { public List<String> getJars() { return jars; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }
@Test public void testGetJars() throws ParserConfigurationException, IOException, SAXException { for( TestFile test : test_cases ) { System.out.println("getJars for " + test.resource); ParseJNLP instance = new ParseJNLP(test.getFile()); List<String> expResult = test.getJars(); List<String> result = instance.getJars(); ...
ParseJNLP { public String getCodeBase() { return codeBase; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }
@Test public void testGetCodeBase() throws ParserConfigurationException, IOException, SAXException { for (TestFile test : test_cases) { System.out.println("getCodeBase for " + test.resource); ParseJNLP instance = new ParseJNLP(test.getFile()); String expResult = test.getCodeBase(); String result = instance.getCodeBase(...
BaseHolidays { public static LocalDate getEaster( int year ) { Easterformular easter_formular = new Easterformular(year); int day = easter_formular.easterday(); if( day <= 31 ) { return new LocalDate( year, 3, day ); } else { return new LocalDate( year, 4, day - 31 ); } } BaseHolidays( String CountryCode ); HolidayInfo...
@Test public void testGetEaster() { System.out.println("getEaster"); LocalDate[] dates = { new LocalDate(2008,3,23), new LocalDate(2009,4,12), new LocalDate(2010,4,4), new LocalDate(2011,4,24) }; for( LocalDate dm : dates ) { System.out.println("getEaster " + dm.getYear()); int year = dm.getYear(); LocalDate result = B...
BaseHolidays { public LocalDate getEuropeanSummerTimeBegin( int year ) { return getLastSundayOf( year, 3 ); } BaseHolidays( String CountryCode ); HolidayInfo create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name ...
@Test @Ignore("Not implemented") public void testGetEuropeanSummerTimeBegin() { System.out.println("getEuropeanSummerTimeBegin"); int year = 0; BaseHolidays instance = null; LocalDate expResult = null; LocalDate result = instance.getEuropeanSummerTimeBegin(year); assertEquals(expResult, result); fail("The test case is ...
BaseHolidays { public LocalDate getEuropeanSummerTimeEnd( int year ) { return getLastSundayOf( year, 10 ); } BaseHolidays( String CountryCode ); HolidayInfo create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name )...
@Test @Ignore("Not implemented") public void testGetEuropeanSummerTimeEnd() { System.out.println("getEuropeanSummerTimeEnd"); int year = 0; BaseHolidays instance = null; LocalDate expResult = null; LocalDate result = instance.getEuropeanSummerTimeEnd(year); assertEquals(expResult, result); fail("The test case is a prot...