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 defaultValueWhenObjectNameNotInitialized() throws MalformedObjectNameException { when(cache.getCacheManager()).thenReturn(null); metrics = new JCacheMetrics(cache, expectedTag); assertThat(metrics.hitCount()).isEqualTo(0L); } |
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(registry); } } 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 doNotReportMetricWhenObjectNameNotInitialized() throws MalformedObjectNameException { when(cache.getCacheManager()).thenReturn(null); metrics = new JCacheMetrics(cache, expectedTag); MeterRegistry registry = new SimpleMeterRegistry(); metrics.bindImplementationSpecificMetrics(registry); assertThat(registry.find("cache.removals").tags(expectedTag).functionCounter()).isNull(); } |
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(String path, Request baseRequest, HttpServletRequest request, HttpServletResponse response); @Override Future<Void> shutdown(); @Override boolean isShutdown(); } | @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 asyncContext = request.startAsync(); asyncContext.setTimeout(0); new Thread(() -> { try { Thread.sleep(delay); asyncContext.complete(); } catch (InterruptedException e) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); asyncContext.complete(); } }).start(); serverLatch.countDown(); } }); server.start(); String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n"; connector.executeRequest(request); assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); Future<Void> shutdown = timedHandler.shutdown(); assertFalse(shutdown.isDone()); Thread.sleep(delay / 2); assertFalse(shutdown.isDone()); Thread.sleep(delay); assertTrue(shutdown.isDone()); } |
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(Event event); @Override void handshakeFailed(Event event, Throwable failure); static void addToAllConnectors(Server server, MeterRegistry registry, Iterable<Tag> tags); static void addToAllConnectors(Server server, MeterRegistry registry); } | @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", "failed") .counter().count()).isEqualTo(1.0); } |
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.getProtocol()) .tag(TAG_CIPHER_SUITE, session.getCipherSuite()) .tags(tags) .register(registry) .increment(); } JettySslHandshakeMetrics(MeterRegistry registry); JettySslHandshakeMetrics(MeterRegistry registry, Iterable<Tag> tags); @Override void handshakeSucceeded(Event event); @Override void handshakeFailed(Event event, Throwable failure); static void addToAllConnectors(Server server, MeterRegistry registry, Iterable<Tag> tags); static void addToAllConnectors(Server server, MeterRegistry registry); } | @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", "0", "protocol", "TLSv1.3", "ciphersuite", "RSA_XYZZY", "result", "succeeded") .counter().count()).isEqualTo(1.0); } |
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, Iterable<Tag> tags); @Deprecated HibernateMetrics(EntityManagerFactory entityManagerFactory, String entityManagerFactoryName, Iterable<Tag> tags); static void monitor(MeterRegistry registry, SessionFactory sessionFactory, String sessionFactoryName, String... tags); static void monitor(MeterRegistry registry, SessionFactory sessionFactory, String sessionFactoryName, Iterable<Tag> tags); @Deprecated static void monitor(MeterRegistry registry, EntityManagerFactory entityManagerFactory, String entityManagerFactoryName, String... tags); @Deprecated static void monitor(MeterRegistry registry, EntityManagerFactory entityManagerFactory, String entityManagerFactoryName, Iterable<Tag> tags); @Override void bindTo(MeterRegistry registry); } | @SuppressWarnings("deprecation") @Test void deprecatedMonitorShouldExposeMetricsWhenStatsEnabled() { HibernateMetrics.monitor(registry, entityManagerFactory, "entityManagerFactory"); assertThatMonitorShouldExposeMetricsWhenStatsEnabled(); }
@Test void monitorShouldExposeMetricsWhenStatsEnabled() { HibernateMetrics.monitor(registry, sessionFactory, "sessionFactory"); assertThatMonitorShouldExposeMetricsWhenStatsEnabled(); }
@SuppressWarnings("deprecation") @Test void deprecatedMonitorShouldNotExposeMetricsWhenStatsNotEnabled() { EntityManagerFactory entityManagerFactory = createMockEntityManagerFactory(false); HibernateMetrics.monitor(registry, entityManagerFactory, "entityManagerFactory"); assertThat(registry.find("hibernate.sessions.open").functionCounter()).isNull(); }
@Test void monitorShouldNotExposeMetricsWhenStatsNotEnabled() { SessionFactory sessionFactory = createMockSessionFactory(false); HibernateMetrics.monitor(registry, sessionFactory, "sessionFactory"); assertThat(registry.find("hibernate.sessions.open").functionCounter()).isNull(); } |
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,
ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit, TimeUnit baseTimeUnit); double count(); double totalTime(TimeUnit unit); @Override Id getId(); @Override TimeUnit baseTimeUnit(); Type type(); } | @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.ofSeconds(1)); assertThat(functionTimer.totalTime(TimeUnit.SECONDS)).isEqualTo(1d); assertThat(functionTimer.totalTime(TimeUnit.MILLISECONDS)).isEqualTo(1000d); System.gc(); assertThat(functionTimer.totalTime(TimeUnit.MILLISECONDS)).isEqualTo(1000d); assertThat(functionTimer.totalTime(TimeUnit.SECONDS)).isEqualTo(1d); } |
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, TimeUnit baseTimeUnit); double count(); double totalTime(TimeUnit unit); @Override Id getId(); @Override TimeUnit baseTimeUnit(); Type type(); } | @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 stepDuration = Duration.ofMillis(10); MockClock clock = new MockClock(); StepFunctionTimer<Object> ft = new StepFunctionTimer<>( mock(Meter.Id.class), clock, stepDuration.toMillis(), new Object(), (o) -> counts.poll(), (o) -> totalTimes.poll(), TimeUnit.SECONDS, TimeUnit.SECONDS ); assertThat(ft.count()).isEqualTo(0.0); clock.add(stepDuration); assertThat(ft.mean(TimeUnit.SECONDS)).isEqualTo(300.0 / 5L); clock.add(stepDuration); assertThat(ft.mean(TimeUnit.SECONDS)).isEqualTo(700.0 / 5L); } |
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.poll()).isEqualTo(0L); clock.add(Duration.ofMillis(1)); assertThat(stepValue.poll()).isEqualTo(0L); clock.add(Duration.ofMillis(59)); assertThat(stepValue.poll()).isEqualTo(42L); clock.add(Duration.ofMillis(60)); assertThat(stepValue.poll()).isEqualTo(0L); clock.add(Duration.ofMillis(60)); assertThat(stepValue.poll()).isEqualTo(0L); aLong.set(24); assertThat(stepValue.poll()).isEqualTo(0L); clock.add(Duration.ofMillis(60)); assertThat(stepValue.poll()).isEqualTo(24L); } |
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") AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock); protected AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(AppOpticsConfig config); } | @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").gauge(); assertThat(meterRegistry.writeGauge(gauge).isPresent()).isFalse(); }
@Test void writeGaugeShouldDropInfiniteValues() { meterRegistry.gauge("my.gauge", Double.POSITIVE_INFINITY); Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge).isPresent()).isFalse(); meterRegistry.gauge("my.gauge", Double.NEGATIVE_INFINITY); gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge).isPresent()).isFalse(); } |
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, T obj, ToDoubleFunction<T> f); @Override double count(); } | @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(Iterable<Row<?>> rows, boolean overwrite); } | @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(toList())); assertThat(registry.get("colors").gauges().stream().map(g -> g.getId().getTag("color"))) .containsExactlyInAnyOrder("red", "blue"); } |
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("colors").tag("color", color.name).gauge().value()).isEqualTo(2); } }
@Test void dontOverwriteFunctionDefinitions() { 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())); for (Color color : colors) { assertThat(registry.get("colors").tag("color", color.name).gauge().value()).isEqualTo(1); } }
@Test void rowGaugesHoldStrongReferences() { colorGauges.register(Collections.singletonList(Row.of(Tags.of("color", "red"), () -> 1))); System.gc(); assertThat(registry.get("colors").tag("color", "red").gauge().value()).isEqualTo(1); } |
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); @Override void recordDouble(double value); static String getRangeTagValue(double value); @Override HistogramSnapshot takeSnapshot(long count, double total, double max); } | @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.POSITIVE_INFINITY)).isEqualTo("1.0e18...+Inf"); assertThat(histogram.getRangeTagValue(1e18d)).isEqualTo("9.5e17...1.0e18"); } } |
DistributionStatisticConfig implements Mergeable<DistributionStatisticConfig> { @Override public DistributionStatisticConfig merge(DistributionStatisticConfig parent) { return DistributionStatisticConfig.builder() .percentilesHistogram(this.percentileHistogram == null ? parent.percentileHistogram : this.percentileHistogram) .percentiles(this.percentiles == null ? parent.percentiles : this.percentiles) .serviceLevelObjectives(this.serviceLevelObjectives == null ? parent.serviceLevelObjectives : this.serviceLevelObjectives) .percentilePrecision(this.percentilePrecision == null ? parent.percentilePrecision : this.percentilePrecision) .minimumExpectedValue(this.minimumExpectedValue == null ? parent.minimumExpectedValue : this.minimumExpectedValue) .maximumExpectedValue(this.maximumExpectedValue == null ? parent.maximumExpectedValue : this.maximumExpectedValue) .expiry(this.expiry == null ? parent.expiry : this.expiry) .bufferLength(this.bufferLength == null ? parent.bufferLength : this.bufferLength) .build(); } static Builder builder(); @Override DistributionStatisticConfig merge(DistributionStatisticConfig parent); NavigableSet<Double> getHistogramBuckets(boolean supportsAggregablePercentiles); @Nullable Boolean isPercentileHistogram(); @Nullable double[] getPercentiles(); @Nullable Integer getPercentilePrecision(); @Deprecated @Nullable Double getMinimumExpectedValue(); @Nullable Double getMinimumExpectedValueAsDouble(); @Deprecated @Nullable Double getMaximumExpectedValue(); @Nullable Double getMaximumExpectedValueAsDouble(); @Nullable Duration getExpiry(); @Nullable Integer getBufferLength(); @Nullable @Deprecated double[] getSlaBoundaries(); @Nullable double[] getServiceLevelObjectiveBoundaries(); boolean isPublishingPercentiles(); boolean isPublishingHistogram(); static final DistributionStatisticConfig DEFAULT; static final DistributionStatisticConfig NONE; } | @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); assertThat(merged.getPercentiles()).containsExactly(0.90); assertThat(merged.getExpiry()).isEqualTo(Duration.ofMinutes(2)); } |
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, Function<CountAtBucket, Iterable<Tag>> bucketTags) { return new HistogramGauges(meter, registry, percentileName, percentileTags, percentileValue, bucketName, bucketTags); } private HistogramGauges(HistogramSupport meter, MeterRegistry registry,
Function<ValueAtPercentile, String> percentileName,
Function<ValueAtPercentile, Iterable<Tag>> percentileTags,
Function<ValueAtPercentile, Double> percentileValue,
Function<CountAtBucket, String> bucketName,
Function<CountAtBucket, Iterable<Tag>> bucketTags); static HistogramGauges registerWithCommonFormat(Timer timer, MeterRegistry registry); static HistogramGauges registerWithCommonFormat(LongTaskTimer ltt, MeterRegistry registry); static HistogramGauges registerWithCommonFormat(DistributionSummary summary, MeterRegistry registry); static HistogramGauges register(HistogramSupport meter, MeterRegistry registry,
Function<ValueAtPercentile, String> percentileName,
Function<ValueAtPercentile, Iterable<Tag>> percentileTags,
Function<ValueAtPercentile, Double> percentileValue,
Function<CountAtBucket, String> bucketName,
Function<CountAtBucket, Iterable<Tag>> bucketTags); } | @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") .serviceLevelObjectives(Duration.ofMillis(1)) .publishPercentiles(0.95) .register(registry); registry.get("MYPREFIX.my.timer.percentile").tag("phi", "0.95").gauge(); registry.get("MYPREFIX.my.timer.histogram").tag("le", "0.001").gauge(); } |
TimeWindowPercentileHistogram extends AbstractTimeWindowHistogram<DoubleRecorder, DoubleHistogram> { @Override void recordDouble(DoubleRecorder bucket, double value) { bucket.recordValue(value); } TimeWindowPercentileHistogram(Clock clock, DistributionStatisticConfig distributionStatisticConfig,
boolean supportsAggregablePercentiles); } | @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(histogram.takeSnapshot(0, 0, 0).histogramCounts()).containsExactly( new CountAtBucket(3.0, 1), new CountAtBucket(6.0, 1), new CountAtBucket(7.0, 1)); histogram.recordDouble(6); assertThat(histogram.takeSnapshot(0, 0, 0).histogramCounts()).containsExactly( new CountAtBucket(3.0, 1), new CountAtBucket(6.0, 2), new CountAtBucket(7.0, 2) ); } }
@Test void sampleValueAboveMaximumExpectedValue() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), DistributionStatisticConfig.builder() .serviceLevelObjectives(3.0) .maximumExpectedValue(2.0) .build() .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(3); assertThat(histogram.takeSnapshot(0, 0, 0).histogramCounts()).containsExactly(new CountAtBucket(3.0, 1)); } }
@Test void recordValuesThatExceedTheDynamicRange() { try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), DistributionStatisticConfig.builder() .serviceLevelObjectives(Double.POSITIVE_INFINITY) .build() .merge(DistributionStatisticConfig.DEFAULT), false)) { histogram.recordDouble(Double.MAX_VALUE); assertThat(histogram.takeSnapshot(0, 0, 0).histogramCounts()) .containsExactly(new CountAtBucket(Double.POSITIVE_INFINITY, 0)); } } |
TimeWindowPercentileHistogram extends AbstractTimeWindowHistogram<DoubleRecorder, DoubleHistogram> { @Override void recordLong(DoubleRecorder bucket, long value) { bucket.recordValue(value); } TimeWindowPercentileHistogram(Clock clock, DistributionStatisticConfig distributionStatisticConfig,
boolean supportsAggregablePercentiles); } | @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)) .build() .merge(DistributionStatisticConfig.DEFAULT), false)) { for (long i = 1; i <= 10; i++) { histogram.recordLong((long) millisToUnit(i, TimeUnit.NANOSECONDS)); } assertThat(histogram.takeSnapshot(0, 0, 0).percentileValues()) .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 5e6)) .anyMatch(p -> percentileValueIsApproximately(p, 0.9, 9e6)) .anyMatch(p -> percentileValueIsApproximately(p, 0.95, 10e6)); } }
@Test void percentilesChangeWithMoreRecentSamples() { DistributionStatisticConfig config = DistributionStatisticConfig.builder() .percentiles(0.5) .build() .merge(DistributionStatisticConfig.DEFAULT); try (TimeWindowPercentileHistogram histogram = new TimeWindowPercentileHistogram(new MockClock(), config, false)) { for (int i = 1; i <= 10; i++) { histogram.recordLong((long) millisToUnit(i, TimeUnit.NANOSECONDS)); } assertThat(histogram.takeSnapshot(0, 0, 0).percentileValues()) .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 5e6)); for (int i = 11; i <= 20; i++) { histogram.recordLong((long) millisToUnit(i, TimeUnit.NANOSECONDS)); } assertThat(histogram.takeSnapshot(0, 0, 0).percentileValues()) .anyMatch(p -> percentileValueIsApproximately(p, 0.5, 10e6)); } }
@Test void timeBasedSlidingWindow() { final DistributionStatisticConfig config = DistributionStatisticConfig.builder() .percentiles(0.0, 0.5, 0.75, 0.9, 0.99, 0.999, 1.0) .expiry(Duration.ofSeconds(4)) .bufferLength(4) .build() .merge(DistributionStatisticConfig.DEFAULT); MockClock clock = new MockClock(); clock.add(-1, TimeUnit.NANOSECONDS); assertThat(clock.wallTime()).isZero(); Histogram histogram = new TimeWindowPercentileHistogram(clock, config, false); histogram.recordLong(10); histogram.recordLong(20); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(9.0, 11.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(19.0, 21.0); clock.add(900, TimeUnit.MILLISECONDS); histogram.recordLong(30); histogram.recordLong(40); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(9.0, 11.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(38.0, 42.0); clock.add(99, TimeUnit.MILLISECONDS); histogram.recordLong(9); histogram.recordLong(60); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(8.0, 10.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(58.0, 62.0); clock.add(1, TimeUnit.MILLISECONDS); histogram.recordLong(12); histogram.recordLong(70); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(8.0, 10.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(68.0, 72.0); clock.add(1001, TimeUnit.MILLISECONDS); histogram.recordLong(13); histogram.recordLong(80); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(8.0, 10.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(75.0, 85.0); clock.add(1000, TimeUnit.MILLISECONDS); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(8.0, 10.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(75.0, 85.0); clock.add(999, TimeUnit.MILLISECONDS); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(11.0, 13.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(75.0, 85.0); histogram.recordLong(1); histogram.recordLong(200); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(0.0, 2.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(190.0, 210.0); clock.add(10000, TimeUnit.MILLISECONDS); assertThat(percentileValue(histogram, 0.0)).isZero(); assertThat(percentileValue(histogram, 1.0)).isZero(); histogram.recordLong(3); clock.add(3999, TimeUnit.MILLISECONDS); assertThat(percentileValue(histogram, 0.0)).isStrictlyBetween(2.0, 4.0); assertThat(percentileValue(histogram, 1.0)).isStrictlyBetween(2.0, 4.0); clock.add(1, TimeUnit.MILLISECONDS); assertThat(percentileValue(histogram, 0.0)).isZero(); assertThat(percentileValue(histogram, 1.0)).isZero(); } |
TimeWindowFixedBoundaryHistogram extends AbstractTimeWindowHistogram<TimeWindowFixedBoundaryHistogram.FixedBoundaryHistogram, Void> { @Override final void recordDouble(FixedBoundaryHistogram bucket, double value) { recordLong(bucket, (long) Math.ceil(value)); } TimeWindowFixedBoundaryHistogram(Clock clock, DistributionStatisticConfig config, boolean supportsAggregablePercentiles); } | @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(3); assertThat(histogram.takeSnapshot(0, 0, 0).histogramCounts()).containsExactly( new CountAtBucket(3.0, 1), new CountAtBucket(6.0, 1), new CountAtBucket(7.0, 1)); histogram.recordDouble(6); histogram.recordDouble(7); assertThat(histogram.takeSnapshot(0, 0, 0).histogramCounts()).containsExactly( new CountAtBucket(3.0, 1), new CountAtBucket(6.0, 2), new CountAtBucket(7.0, 3) ); } } |
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; } CountedAspect(MeterRegistry meterRegistry); CountedAspect(MeterRegistry meterRegistry, Function<ProceedingJoinPoint, Iterable<Tag>> tagsBasedOnJoinPoint); @Around("@annotation(counted)") Object interceptAndRecord(ProceedingJoinPoint pjp, Counted counted); final String DEFAULT_EXCEPTION_TAG_VALUE; final String RESULT_TAG_FAILURE_VALUE; final String RESULT_TAG_SUCCESS_VALUE; } | @Test void countedWithoutSuccessfulMetrics() { countedService.succeedWithoutMetrics(); assertThatThrownBy(() -> meterRegistry.get("metric.none").counter()) .isInstanceOf(MeterNotFoundException.class); }
@Test void countedWithSuccessfulMetrics() { countedService.succeedWithMetrics(); Counter counter = meterRegistry.get("metric.success") .tag("method", "succeedWithMetrics") .tag("class", "io.micrometer.core.aop.CountedAspectTest$CountedService") .tag("extra", "tag") .tag("result", "success").counter(); assertThat(counter.count()).isOne(); assertThat(counter.getId().getDescription()).isNull(); }
@Test void countedWithFailure() { try { countedService.fail(); } catch (Exception ignored) { } Counter counter = meterRegistry.get("metric.failing") .tag("method", "fail") .tag("class", "io.micrometer.core.aop.CountedAspectTest$CountedService") .tag("exception", "RuntimeException") .tag("result", "failure").counter(); assertThat(counter.count()).isOne(); assertThat(counter.getId().getDescription()).isEqualTo("To record something"); }
@Test void countedWithEmptyMetricNames() { countedService.emptyMetricName(); try { countedService.emptyMetricNameWithException(); } catch (Exception ignored) { } assertThat(meterRegistry.get("method.counted").counters()).hasSize(2); assertThat(meterRegistry.get("method.counted").tag("result", "success").counter().count()).isOne(); assertThat(meterRegistry.get("method.counted").tag("result", "failure").counter().count()).isOne(); }
@Test void countedWithoutSuccessfulMetricsWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture<?> completableFuture = asyncCountedService.succeedWithoutMetrics(guardedResult); guardedResult.complete(); completableFuture.join(); assertThatThrownBy(() -> meterRegistry.get("metric.none").counter()) .isInstanceOf(MeterNotFoundException.class); }
@Test void countedWithSuccessfulMetricsWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture<?> completableFuture = asyncCountedService.succeedWithMetrics(guardedResult); assertThat(meterRegistry.find("metric.success") .tag("method", "succeedWithMetrics") .tag("class", "io.micrometer.core.aop.CountedAspectTest$AsyncCountedService") .tag("extra", "tag") .tag("exception", "none") .tag("result", "success").counter()).isNull(); guardedResult.complete(); completableFuture.join(); Counter counterAfterCompletion = meterRegistry.get("metric.success") .tag("method", "succeedWithMetrics") .tag("class", "io.micrometer.core.aop.CountedAspectTest$AsyncCountedService") .tag("extra", "tag") .tag("exception", "none") .tag("result", "success").counter(); assertThat(counterAfterCompletion.count()).isOne(); assertThat(counterAfterCompletion.getId().getDescription()).isNull(); }
@Test void countedWithFailureWhenCompleted() { GuardedResult guardedResult = new GuardedResult(); CompletableFuture<?> completableFuture = asyncCountedService.fail(guardedResult); assertThat(meterRegistry.find("metric.failing") .tag("method", "fail") .tag("class", "io.micrometer.core.aop.CountedAspectTest$AsyncCountedService") .tag("exception", "RuntimeException") .tag("result", "failure").counter()).isNull(); guardedResult.complete(new RuntimeException()); assertThatThrownBy(completableFuture::join).isInstanceOf(RuntimeException.class); Counter counter = meterRegistry.get("metric.failing") .tag("method", "fail") .tag("class", "io.micrometer.core.aop.CountedAspectTest$AsyncCountedService") .tag("exception", "RuntimeException") .tag("result", "failure").counter(); assertThat(counter.count()).isOne(); assertThat(counter.getId().getDescription()).isEqualTo("To record something"); }
@Test void countedWithEmptyMetricNamesWhenCompleted() { GuardedResult emptyMetricNameResult = new GuardedResult(); GuardedResult emptyMetricNameWithExceptionResult = new GuardedResult(); CompletableFuture<?> emptyMetricNameFuture = asyncCountedService.emptyMetricName(emptyMetricNameResult); CompletableFuture<?> emptyMetricNameWithExceptionFuture = asyncCountedService.emptyMetricName(emptyMetricNameWithExceptionResult); assertThat(meterRegistry.find("method.counted").counters()).hasSize(0); emptyMetricNameResult.complete(); emptyMetricNameWithExceptionResult.complete(new RuntimeException()); emptyMetricNameFuture.join(); assertThatThrownBy(emptyMetricNameWithExceptionFuture::join).isInstanceOf(RuntimeException.class); assertThat(meterRegistry.get("method.counted").counters()).hasSize(2); assertThat(meterRegistry.get("method.counted").tag("result", "success").counter().count()).isOne(); assertThat(meterRegistry.get("method.counted").tag("result", "failure").counter().count()).isOne(); } |
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(response), JerseyTags.outcome(response)); } @Override Iterable<Tag> httpRequestTags(RequestEvent event); @Override Iterable<Tag> httpLongRequestTags(RequestEvent event); } | @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}"))) .containsExactlyInAnyOrder(tagsFrom("/hello/{name}", 200, null, "SUCCESS")); }
@Test public void applicationPathIsPresent() { assertThat(tagsProvider.httpRequestTags(event(200, null, "/app", "/", "/hello"))) .containsExactlyInAnyOrder(tagsFrom("/app/hello", 200, null, "SUCCESS")); }
@Test public void notFoundsAreShunted() { assertThat(tagsProvider.httpRequestTags(event(404, null, "/app", "/", "/not-found"))) .containsExactlyInAnyOrder(tagsFrom("NOT_FOUND", 404, null, "CLIENT_ERROR")); }
@Test public void redirectsAreShunted() { assertThat(tagsProvider.httpRequestTags(event(301, null, "/app", "/", "/redirect301"))) .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 301, null, "REDIRECTION")); assertThat(tagsProvider.httpRequestTags(event(302, null, "/app", "/", "/redirect302"))) .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 302, null, "REDIRECTION")); assertThat(tagsProvider.httpRequestTags(event(399, null, "/app", "/", "/redirect399"))) .containsExactlyInAnyOrder(tagsFrom("REDIRECTION", 399, null, "REDIRECTION")); }
@Test @SuppressWarnings("serial") public void exceptionsAreMappedCorrectly() { assertThat(tagsProvider.httpRequestTags( event(500, new IllegalArgumentException(), "/app", (String[]) null))) .containsExactlyInAnyOrder(tagsFrom("/app", 500, "IllegalArgumentException", "SERVER_ERROR")); assertThat(tagsProvider.httpRequestTags(event(500, new IllegalArgumentException(new NullPointerException()), "/app", (String[]) null))) .containsExactlyInAnyOrder(tagsFrom("/app", 500, "NullPointerException", "SERVER_ERROR")); assertThat(tagsProvider.httpRequestTags( event(406, new NotAcceptableException(), "/app", (String[]) null))) .containsExactlyInAnyOrder(tagsFrom("/app", 406, "NotAcceptableException", "CLIENT_ERROR")); assertThat(tagsProvider.httpRequestTags( event(500, new Exception("anonymous") { }, "/app", (String[]) null))) .containsExactlyInAnyOrder(tagsFrom("/app", 500, "io.micrometer.jersey2.server.DefaultJerseyTagsProviderTest$1", "SERVER_ERROR")); } |
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> httpLongRequestTags(RequestEvent event); } | @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))); } @SuppressWarnings("deprecation") AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock); protected AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(AppOpticsConfig config); } | @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).isPresent()).isTrue(); }
@Test void writeTimeGaugeShouldDropNanValue() { AtomicReference<Double> obj = new AtomicReference<>(Double.NaN); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeTimeGauge(timeGauge).isPresent()).isFalse(); }
@Test void writeTimeGaugeShouldDropInfiniteValues() { AtomicReference<Double> obj = new AtomicReference<>(Double.POSITIVE_INFINITY); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeTimeGauge(timeGauge).isPresent()).isFalse(); obj = new AtomicReference<>(Double.NEGATIVE_INFINITY); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeTimeGauge(timeGauge).isPresent()).isFalse(); } |
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(); } @SuppressWarnings("deprecation") AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock); protected AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(AppOpticsConfig config); } | @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, this::writeCounter, this::writeTimer, this::writeSummary, this::writeLongTaskTimer, this::writeTimeGauge, this::writeFunctionCounter, this::writeFunctionTimer, this::writeMeter) ) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); if (meters.isEmpty()) { continue; } httpClient.post(config.uri()) .withBasicAuthentication(config.apiToken(), "") .withJsonContent( meters.stream().collect(joining(",", bodyMeasurementsPrefix, BODY_MEASUREMENTS_SUFFIX))) .send() .onSuccess(response -> { if (!response.body().contains("\"failed\":0")) { logger.error("failed to send at least some metrics to appoptics: {}", response.body()); } else { logger.debug("successfully sent {} metrics to appoptics", batch.size()); } }) .onError(response -> logger.error("failed to send metrics to appoptics: {}", response.body())); } } catch (Throwable t) { logger.warn("failed to send metrics to appoptics", t); } } @SuppressWarnings("deprecation") AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock); protected AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(AppOpticsConfig config); } | @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_MEASUREMENTS_PREFIX, wallTimeInSeconds); } @SuppressWarnings("deprecation") AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock); protected AppOpticsMeterRegistry(AppOpticsConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(AppOpticsConfig config); } | @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, clock, mockThreadFactory, mockSender); clock.add(Duration.ofSeconds(63)); assertThat(meterRegistry.getBodyMeasurementsPrefix()).isEqualTo( String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60)); clock.addSeconds(56); assertThat(meterRegistry.getBodyMeasurementsPrefix()).isEqualTo( String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60)); clock.addSeconds(1); assertThat(meterRegistry.getBodyMeasurementsPrefix()).isEqualTo( String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 120)); } |
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())); new AtlasMeterRegistry(config, Clock.SYSTEM).close(); server.verify(postRequestedFor(urlEqualTo("/api/v1/publish"))); } |
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); } @Override public Duration lwcStep() { return step(); } }, clock); FunctionCounter.builder("test", count, AtomicLong::doubleValue).register(registry); Supplier<Double> valueSupplier = () -> { AtlasRegistry r = (AtlasRegistry) registry.getSpectatorRegistry(); PolledMeter.update(r); clock.add(Duration.ofMinutes(1)); return r.measurements() .filter(m -> m.id().name().equals("test")) .findFirst() .map(Measurement::value) .orElse(Double.NaN); }; count.addAndGet(60); assertThat(valueSupplier.get()).isEqualTo(1.0); count.addAndGet(120); assertThat(valueSupplier.get()).isEqualTo(2.0); count.addAndGet(90); assertThat(valueSupplier.get()).isEqualTo(1.5); } |
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 String baseUnit); @Override String tagKey(String key); } | @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(measurement.value(), unit); } } return Double.NaN; } SpectatorTimer(Id id, Timer timer, Clock clock, DistributionStatisticConfig statsConf, PauseDetector pauseDetector, TimeUnit baseTimeUnit); @Override long count(); @Override double totalTime(TimeUnit unit); @Override double max(TimeUnit unit); } | @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, TimeUnit.SECONDS); clock(registry).add(atlasConfig.step()); assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000); } |
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.debug("created {} as custom metric in dynatrace", customMetric.getMetricId()); createdCustomMetrics.add(customMetric.getMetricId()); }) .onError(response -> { if (logger.isErrorEnabled()) { logger.error("failed to create custom metric {} in dynatrace: {}", customMetric.getMetricId(), response.body()); } }); } catch (Throwable e) { logger.error("failed to create custom metric in dynatrace: {}", customMetric.getMetricId(), e); } } @SuppressWarnings("deprecation") DynatraceMeterRegistry(DynatraceConfig config, Clock clock); private DynatraceMeterRegistry(DynatraceConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(DynatraceConfig config); } | @Test void putCustomMetricOnSuccessShouldAddMetricIdToCreatedCustomMetrics() throws NoSuchFieldException, IllegalAccessException { Field createdCustomMetricsField = DynatraceMeterRegistry.class.getDeclaredField("createdCustomMetrics"); createdCustomMetricsField.setAccessible(true); @SuppressWarnings("unchecked") Set<String> createdCustomMetrics = (Set<String>) createdCustomMetricsField.get(meterRegistry); assertThat(createdCustomMetrics).isEmpty(); DynatraceMetricDefinition customMetric = new DynatraceMetricDefinition("metricId", null, null, null, new String[]{"type"}, null); meterRegistry.putCustomMetric(customMetric); assertThat(createdCustomMetrics).containsExactly("metricId"); } |
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(), wallTime, value)); } @SuppressWarnings("deprecation") DynatraceMeterRegistry(DynatraceConfig config, Clock clock); private DynatraceMeterRegistry(DynatraceConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(DynatraceConfig config); } | @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.gauge").gauge(); assertThat(meterRegistry.writeMeter(gauge)).isEmpty(); }
@SuppressWarnings("unchecked") @Test void writeMeterWithGaugeWhenChangingFiniteToNaNShouldWork() { AtomicBoolean first = new AtomicBoolean(true); meterRegistry.gauge("my.gauge", first, (b) -> b.getAndSet(false) ? 1d : Double.NaN); Gauge gauge = meterRegistry.find("my.gauge").gauge(); Stream<DynatraceMeterRegistry.DynatraceCustomMetric> stream = meterRegistry.writeMeter(gauge); List<DynatraceMeterRegistry.DynatraceCustomMetric> metrics = stream.collect(Collectors.toList()); assertThat(metrics).hasSize(1); DynatraceMeterRegistry.DynatraceCustomMetric metric = metrics.get(0); DynatraceTimeSeries timeSeries = metric.getTimeSeries(); try { Map<String, Object> map = mapper.readValue(timeSeries.asJson(), Map.class); List<List<Number>> dataPoints = (List<List<Number>>) map.get("dataPoints"); assertThat(dataPoints.get(0).get(1).doubleValue()).isEqualTo(1d); } catch (IOException ex) { throw new RuntimeException(ex); } }
@Test void writeMeterWithGaugeShouldDropInfiniteValues() { meterRegistry.gauge("my.gauge", Double.POSITIVE_INFINITY); Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeMeter(gauge)).isEmpty(); meterRegistry.gauge("my.gauge", Double.NEGATIVE_INFINITY); gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeMeter(gauge)).isEmpty(); }
@Test void writeMeterWithTimeGauge() { 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.writeMeter(timeGauge)).hasSize(1); }
@Test void writeMeterWithTimeGaugeShouldDropNanValue() { AtomicReference<Double> obj = new AtomicReference<>(Double.NaN); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeMeter(timeGauge)).isEmpty(); }
@Test void writeMeterWithTimeGaugeShouldDropInfiniteValues() { AtomicReference<Double> obj = new AtomicReference<>(Double.POSITIVE_INFINITY); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeMeter(timeGauge)).isEmpty(); obj = new AtomicReference<>(Double.NEGATIVE_INFINITY); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeMeter(timeGauge)).isEmpty(); } |
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 String footer = "]}"; final int headerFooterBytes = header.getBytes(UTF_8).length + footer.getBytes(UTF_8).length; final int maxMessageSize = MAX_MESSAGE_SIZE - headerFooterBytes; List<DynatraceBatchedPayload> payloadBodies = createPostMessageBodies(timeSeries, maxMessageSize); return payloadBodies.stream().map(body -> { String message = header + body.payload + footer; return new DynatraceBatchedPayload(message, body.metricCount); }).collect(Collectors.toList()); } @SuppressWarnings("deprecation") DynatraceMeterRegistry(DynatraceConfig config, Clock clock); private DynatraceMeterRegistry(DynatraceConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient); static Builder builder(DynatraceConfig config); } | @Test void whenAllTsTooLargeEmptyMessageListReturned() { List<DynatraceBatchedPayload> messages = meterRegistry.createPostMessages("my.type", null, Collections.singletonList(createTimeSeriesWithDimensions(10_000))); assertThat(messages).isEmpty(); }
@Test void splitsWhenExactlyExceedingMaxByComma() { List<DynatraceBatchedPayload> messages = meterRegistry.createPostMessages("my.type", "my.group", Arrays.asList(createTimeSeriesWithDimensions(750), createTimeSeriesWithDimensions(23, "asdfg"), createTimeSeriesWithDimensions(750), createTimeSeriesWithDimensions(22, "asd") )); assertThat(messages).hasSize(3); assertThat(messages.get(0).metricCount).isEqualTo(1); assertThat(messages.get(1).metricCount).isEqualTo(1); assertThat(messages.get(2).metricCount).isEqualTo(2); assertThat(messages.get(2).payload.getBytes(UTF_8).length).isEqualTo(15360); assertThat(messages.stream().map(message -> message.payload).allMatch(this::isValidJson)).isTrue(); }
@Test void countsPreviousAndNextComma() { List<DynatraceBatchedPayload> messages = meterRegistry.createPostMessages("my.type", null, Arrays.asList(createTimeSeriesWithDimensions(750), createTimeSeriesWithDimensions(10, "asdf"), createTimeSeriesWithDimensions(10, "asdf") )); assertThat(messages).hasSize(2); assertThat(messages.get(0).metricCount).isEqualTo(2); assertThat(messages.get(1).metricCount).isEqualTo(1); assertThat(messages.stream().map(message -> message.payload).allMatch(this::isValidJson)).isTrue(); } |
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.truncate(group, MAX_GROUP_NAME) + "\""; if (unit != null) body += ",\"unit\":\"" + unit + "\""; if (dimensions != null && !dimensions.isEmpty()) body += ",\"dimensions\":[" + dimensions.stream() .map(d -> "\"" + d + "\"") .collect(Collectors.joining(",")) + "]"; body += ",\"types\":[" + stream(technologyTypes).map(type -> "\"" + type + "\"").collect(Collectors.joining(",")) + "]"; body += "}"; return body; } DynatraceMetricDefinition(String metricId, @Nullable String description, @Nullable DynatraceUnit unit, @Nullable Set<String> dimensions,
String[] technologyTypes, String group); } | @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 void escapesStringsInDescription() { final DynatraceMetricDefinition metric = new DynatraceMetricDefinition( "custom:test.metric", "The /\"recent cpu usage\" for the Java Virtual Machine process", null, null, technologyTypes, null); assertThat(metric.asJson()).isEqualTo("{\"displayName\":\"The /\\\"recent cpu usage\\\" for the Java Virtual Machine process\",\"types\":[\"java\"]}"); }
@Test void addsUnitWhenAvailable() { final DynatraceMetricDefinition metric = new DynatraceMetricDefinition("custom:test.metric", "my test metric", DynatraceMetricDefinition.DynatraceUnit.Count, null, technologyTypes, null); assertThat(metric.asJson()).isEqualTo("{\"displayName\":\"my test metric\",\"unit\":\"Count\",\"types\":[\"java\"]}"); }
@Test void addsDimensionsWhenAvailable() { final Set<String> dimensions = new HashSet<>(); dimensions.add("first"); dimensions.add("second"); dimensions.add("unknown"); final DynatraceMetricDefinition metric = new DynatraceMetricDefinition("custom:test.metric", "my test metric", null, dimensions, technologyTypes, null); assertThat(metric.asJson()).isEqualTo("{\"displayName\":\"my test metric\",\"dimensions\":[\"first\",\"second\",\"unknown\"],\"types\":[\"java\"]}"); }
@Test void addsGroupWhenAvailable() { final DynatraceMetricDefinition metric = new DynatraceMetricDefinition("custom:test.metric", "my test metric", DynatraceMetricDefinition.DynatraceUnit.Count, null, technologyTypes, "my test group"); assertThat(metric.asJson()).isEqualTo("{\"displayName\":\"my test metric\",\"group\":\"my test group\",\"unit\":\"Count\",\"types\":[\"java\"]}"); } |
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 name(String name, Meter.Type type, @Nullable String baseUnit); @Override String tagKey(String key); } | @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.name("my_name1", Meter.Type.COUNTER, null)).isEqualTo("custom:my_name1"); assertThat(convention.name("my-name1", Meter.Type.COUNTER, null)).isEqualTo("custom:my-name1"); }
@Test void nameShouldSanitize() { assertThat(convention.name("my,name1", Meter.Type.COUNTER, null)).isEqualTo("custom:my_name1"); }
@Test void nameWithSystemLoadAverageOneMintueShouldSanitize() { assertThat(convention.name("system.load.average.1m", Meter.Type.COUNTER, null)) .isEqualTo("custom:system.load.average.oneminute"); } |
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, @Nullable String baseUnit); @Override String tagKey(String key); } | @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() + "\":\"" + StringEscapeUtils.escapeJson(t.getValue()) + "\"") .collect(Collectors.joining(",")) + "}"; } body += "}"; return body; } DynatraceTimeSeries(final String metricId, final long time, final double value, @Nullable final Map<String, String> dimensions); String getMetricId(); } | @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("{\"timeseriesId\":\"custom:test.metric\",\"dataPoints\":[[12345,1]],\"dimensions\":{\"first\":\"one\",\"second\":\"two\"}}"); }
@Test void asJsonShouldEscapeDimensionValue() { Map<String, String> dimensions = new HashMap<>(); dimensions.put("path", "C:\\MyPath"); dimensions.put("second", "two"); DynatraceTimeSeries timeSeries = new DynatraceTimeSeries("custom:test.metric", 12345, 1, dimensions); assertThat(timeSeries.asJson()).isEqualTo("{\"timeseriesId\":\"custom:test.metric\",\"dataPoints\":[[12345,1]],\"dimensions\":{\"path\":\"C:\\\\MyPath\",\"second\":\"two\"}}"); } |
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", () -> 1.0).register(registry).getId(); Meter.Id actual = filter.map(original); assertThat(actual).isNotEqualTo(original); assertThat(actual.getName()).isEqualTo("process.open.fds"); } |
PrometheusMeterRegistry extends MeterRegistry { public PrometheusMeterRegistry throwExceptionOnRegistrationFailure() { config().onMeterRegistrationFailed((id, reason) -> { throw new IllegalArgumentException(reason); }); return this; } PrometheusMeterRegistry(PrometheusConfig config); PrometheusMeterRegistry(PrometheusConfig config, CollectorRegistry registry, Clock clock); String scrape(); void scrape(Writer writer); @Override Counter newCounter(Meter.Id id); @Override DistributionSummary newDistributionSummary(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double scale); CollectorRegistry getPrometheusRegistry(); PrometheusMeterRegistry throwExceptionOnRegistrationFailure(); } | @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").increment(); assertThat(failedLatch.await(1, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> registry .throwExceptionOnRegistrationFailure() .counter("my.counter", "k1", "v1") ).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> registry.counter("my.counter", "k2", "v2")) .isInstanceOf(IllegalArgumentException.class); } |
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 Counter newCounter(Meter.Id id); @Override DistributionSummary newDistributionSummary(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double scale); CollectorRegistry getPrometheusRegistry(); PrometheusMeterRegistry throwExceptionOnRegistrationFailure(); } | @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("distribution summary s with a tag value of %s", v) .isEqualTo(1.0, offset(1e-12)); }); }
@DisplayName("custom meters can be typed") @Test void typedCustomMeters() { Meter.builder("name", Meter.Type.COUNTER, Collections.singletonList(new Measurement(() -> 1.0, Statistic.COUNT))) .register(registry); Collector.MetricFamilySamples metricFamilySamples = registry.getPrometheusRegistry().metricFamilySamples().nextElement(); assertThat(metricFamilySamples.type) .describedAs("custom counter with a type of COUNTER") .isEqualTo(Collector.Type.COUNTER); assertThat(metricFamilySamples.samples.get(0).labelNames).containsExactly("statistic"); assertThat(metricFamilySamples.samples.get(0).labelValues).containsExactly("COUNT"); } |
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)){ return c; }else{ try { removeConnection(c); } catch (IOException e) { logger.log(Level.SEVERE,"Failure removing cache",e); } } } } } return null; } CacheController(); CacheController(int connectionTimeout); CacheController(int connectionTimeout, int checkWaitTime); CachedConnectionData addConnection(ClientConnection c); void removeConnection(ClientConnection c); void removeDevice(NetworkDevice d); void closeConnection(ClientConnection c); ClientConnection getConnection(String deviceName); } | @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 currentDeviceHost = connectionManagerControlCenter.getHost(networkInterface.getNetworkAddress()); if(deviceHost != null && deviceHost.equals(currentDeviceHost)) { logger.fine("Host of device entered is the same of current device:" + device.getNetworkDeviceName()); return; } } UpDevice upDevice = retrieveDevice(deviceHost,device.getNetworkDeviceType()); if (upDevice == null){ upDevice = doHandshake(device, upDevice); if (upDevice != null){ doDriversRegistry(device, upDevice); } }else{ logger.fine("Already known device "+device.getNetworkDeviceName()); } } DeviceManager(UpDevice currentDevice, DeviceDao deviceDao,
DriverDao driverDao,
ConnectionManagerControlCenter connectionManagerControlCenter,
ConnectivityManager connectivityManager, Gateway gateway,
DriverManager driverManager); void registerDevice(UpDevice device); UpDevice retrieveDevice(String deviceName); UpDevice retrieveDevice(String networkAddress, String networkType); @Override void deviceEntered(NetworkDevice device); @Override void deviceLeft(NetworkDevice device); List<UpDevice> listDevices(); DeviceDao getDeviceDao(); } | @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 JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1").addParameter("s1p1", ParameterType.MANDATORY) .addParameter("s1p2", ParameterType.OPTIONAL); dummy.addService("s2").addParameter("s2p1", ParameterType.MANDATORY); driverList.put("id1", dummy.toJSON()); driverList.put("id2", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); when(proxier.doProxying()).thenReturn(true); deviceManager.deviceEntered(enteree); ArgumentCaptor<UpDevice> deviceCatcher = ArgumentCaptor .forClass(UpDevice.class); ArgumentCaptor<String> idCatcher = ArgumentCaptor .forClass(String.class); verify(proxier, times(2)).registerProxyDriver(eq(dummy), deviceCatcher.capture(), idCatcher.capture()); assertEquals("A", deviceCatcher.getValue().getName()); assertEquals("id2", idCatcher.getAllValues().get(0)); assertEquals("id1", idCatcher.getAllValues().get(1)); }
@Test public void AfterListingIfProxyingIsNotEnabledDoNothing() 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 JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1").addParameter("s1p1", ParameterType.MANDATORY) .addParameter("s1p2", ParameterType.OPTIONAL); dummy.addService("s2").addParameter("s2p1", ParameterType.MANDATORY); driverList.put("id1", dummy.toJSON()); driverList.put("id2", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); when(proxier.doProxying()).thenReturn(false); deviceManager.deviceEntered(enteree); verify(proxier, never()).registerProxyDriver(any(UpDriver.class), any(UpDevice.class), any(String.class)); }
@Test @SuppressWarnings("unchecked") public void ifTheDeviceIsNullShouldDoNothing() throws Exception { assertEquals(1, dao.list().size()); deviceManager.deviceEntered(null); verify(gateway, never()).callService(any(UpDevice.class), any(String.class), any(String.class), any(String.class), any(String.class), any(Map.class)); assertEquals(1, dao.list().size()); }
@Test @SuppressWarnings("unchecked") public void ifTheDeviceProvidesNoDatalShouldDoNothing() throws Exception { assertEquals(1, dao.list().size()); deviceManager.deviceEntered(mock(NetworkDevice.class)); verify(gateway, never()).callService(any(UpDevice.class), any(String.class), any(String.class), any(String.class), any(String.class), any(Map.class)); assertEquals(1, dao.list().size()); }
@Test public void IfDontKnowTheDeviceCallAHandshakeWithIt() throws Exception { when(gateway.callService((UpDevice)anyObject(), (Call)anyObject())) .thenReturn(new Response().addParameter("device", new UpDevice("The Guy").toJSON())); NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); deviceManager.deviceEntered(enteree); ArgumentCaptor<Call> scCacther = ArgumentCaptor .forClass(Call.class); verify(gateway, times(2)).callService(any(UpDevice.class), scCacther.capture()); Call parameter = scCacther.getAllValues().get(0); assertEquals("handshake", parameter.getService()); assertEquals("uos.DeviceDriver", parameter.getDriver()); assertNull(parameter.getInstanceId()); assertNull(parameter.getSecurityType()); assertEquals(currentDevice.toString(), parameter.getParameter("device")); }
@Test public void IfTheHandShakeWorksRegisterTheReturnedDevice() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice newGuy = new UpDevice("TheNewGuy").addNetworkInterface( "ADDR_UNKNOWN", "UNEXISTANT").addNetworkInterface( "127.255.255.666", "Ethernet:TFH"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", newGuy.toString())); deviceManager.deviceEntered(enteree); assertEquals(2, dao.list().size()); assertEquals(newGuy, dao.find(newGuy.getName())); }
@Test public void IfTheHandShakeHappensTwiceDoNothing() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice newGuy = new UpDevice("TheNewGuy") .addNetworkInterface("ADDR_UNKNOWN", "UNEXISTANT") .addNetworkInterface("127.255.255.666", "Ethernet:TFH"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", newGuy.toString())); deviceManager.deviceEntered(enteree); deviceManager.deviceEntered(enteree); assertEquals(2, dao.list().size()); assertEquals(newGuy, dao.find(newGuy.getName())); }
@Test public void IfTheSecondHandShakeSucceedsRegisterDevice() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice newGuy = new UpDevice("TheNewGuy") .addNetworkInterface("ADDR_UNKNOWN", "UNEXISTANT") .addNetworkInterface("127.255.255.666", "Ethernet:TFH"); deviceManager.deviceEntered(enteree); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", newGuy.toString())); deviceManager.deviceEntered(enteree); assertEquals(2, dao.list().size()); assertEquals(newGuy, dao.find(newGuy.getName())); }
@Test public void IfTheHandShakeDoesNotWorksNothingHappens_NoResponse() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn(null); deviceManager.deviceEntered(enteree); assertEquals(1, dao.list().size()); }
@Test public void IfTheHandShakeDoesNotWorksNothingHappens_NoData() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn(new Response()); deviceManager.deviceEntered(enteree); assertEquals(1, dao.list().size()); }
@Test public void IfTheHandShakeDoesNotWorksNothingHappens_ErrorOnResponse() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); Response error = new Response(); error.setError("Just Kidding"); when(gatewayHandshakeCall()).thenReturn(error); deviceManager.deviceEntered(enteree); assertEquals(1, dao.list().size()); }
@Test public void IfTheHandShakeDoesNotWorksNothingHappens_Exception() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenThrow(new RuntimeException()); deviceManager.deviceEntered(enteree); assertEquals(1, dao.list().size()); }
@Test public void IfDontKnowTheDeviceCallListDriversOnIt() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn( new Response().addParameter("device", new UpDevice("A") .addNetworkInterface("A", "T").toString())); deviceManager.deviceEntered(enteree); Call listDrivers = new Call( "uos.DeviceDriver", "listDrivers", null); verify(gateway, times(1)).callService(any(UpDevice.class), eq(listDrivers)); }
@Test public void AfterListingTheDriverTheyMustBeRegistered() 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 JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1").addParameter("s1p1", ParameterType.MANDATORY) .addParameter("s1p2", ParameterType.OPTIONAL); dummy.addService("s2").addParameter("s2p1", ParameterType.MANDATORY); driverList.put("id1", dummy.toJSON()); driverList.put("id2", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList",driverList)); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(2, newGuyDrivers.size()); assertEquals("id1", newGuyDrivers.get(0).id()); assertThat(newGuyDrivers.get(0).driver().toJSON().toMap()) .isEqualTo(dummy.toJSON().toMap()); assertEquals("id2", newGuyDrivers.get(1).id()); assertThat(newGuyDrivers.get(1).driver().toJSON().toMap()) .isEqualTo(dummy.toJSON().toMap()); }
@Test public void shouldNotRegisterADriverDueToInterfaceValidationError() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); JSONObject driverList = new JSONObject(); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList)); List<JSONObject> jsonList = new ArrayList<JSONObject>(); UpDriver equivalentDriver = new UpDriver("equivalentDriver"); equivalentDriver.addEquivalentDrivers(Pointer.DRIVER_NAME); UpService service = new UpService(Pointer.MOVE_EVENT); service.addParameter(Pointer.AXIS_X, ParameterType.MANDATORY); service.addParameter(Pointer.AXIS_Y, ParameterType.MANDATORY); equivalentDriver.addEvent(service); UpService register = new UpService("registerListener").addParameter("eventKey", ParameterType.MANDATORY); equivalentDriver.addService(register); UpService unregister = new UpService("unregisterListener").addParameter("eventKey", ParameterType.OPTIONAL); equivalentDriver.addService(unregister); jsonList.add(equivalentDriver.toJSON()); when(gatewayTellEquivalentDriverCall()).thenReturn(new Response().addParameter("interfaces",new JSONArray(jsonList).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldNotRegisterADriverDueToNullEquivalentDriverResponse() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); JSONObject driverList = new JSONObject(); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); when(gatewayTellEquivalentDriverCall()).thenReturn(null); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldNotRegisterADriverDueToInterfaceNotProvided() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); JSONObject driverList = new JSONObject(); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); when(gatewayTellEquivalentDriverCall()).thenReturn( new Response().addParameter("interfaces", null)); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldNotRegisterADriverDueToWrongJSONObject() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers(Pointer.DRIVER_NAME); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", new String("wrongJSONObject"))); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldNotRegisterADriverDueToMissingServer() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers(Pointer.DRIVER_NAME); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldNotRegisterADriverDueToEquivalentDriverInterfaceValidationError() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); List<JSONObject> jsonList = new ArrayList<JSONObject>(); UpDriver equivalentDriver = new UpDriver("equivalentDriver"); equivalentDriver.addEquivalentDrivers(Pointer.DRIVER_NAME); equivalentDriver.addService("s1"); jsonList.add(equivalentDriver.toJSON()); when(gatewayTellEquivalentDriverCall()).thenReturn( new Response().addParameter("interfaces", new JSONArray( jsonList).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldNotRegisterADriverWithEquivalentDriverNotInformed() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); List<JSONObject> jsonList = new ArrayList<JSONObject>(); UpDriver equivalentDriver = new UpDriver("equivalentDriver"); equivalentDriver.addService("s1"); equivalentDriver.addEquivalentDrivers("notInformedEquivalentDriver"); jsonList.add(equivalentDriver.toJSON()); when(gatewayTellEquivalentDriverCall()).thenReturn( new Response().addParameter("interfaces", new JSONArray( jsonList).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(0, newGuyDrivers.size()); }
@Test public void shouldRegisterADriverWithUnknownEquivalentDriver() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); List<JSONObject> jsonList = new ArrayList<JSONObject>(); UpDriver equivalentDriver = new UpDriver("equivalentDriver"); equivalentDriver.addService("s1"); jsonList.add(equivalentDriver.toJSON()); when(gatewayTellEquivalentDriverCall()).thenReturn( new Response().addParameter("interfaces", new JSONArray( jsonList).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(1, newGuyDrivers.size()); assertEquals("id1", newGuyDrivers.get(0).id()); assertThat(newGuyDrivers.get(0).driver().toJSON().toMap()) .isEqualTo(dummy.toJSON().toMap()); }
@Test public void shouldRegisterTwoDriversWithTheSameUnknownEquivalentDriver() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy1 = new UpDriver("DummyDriver1"); dummy1.addService("s1"); dummy1.addEquivalentDrivers("equivalentDriver"); UpDriver dummy2 = new UpDriver("DummyDriver2"); dummy2.addService("s1"); dummy2.addEquivalentDrivers("equivalentDriver"); driverList.put("iddummy1", dummy1.toJSON()); driverList.put("iddummy2", dummy2.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); List<JSONObject> jsonList = new ArrayList<JSONObject>(); UpDriver equivalentDriver = new UpDriver("equivalentDriver"); equivalentDriver.addService("s1"); jsonList.add(equivalentDriver.toJSON()); when(gatewayTellEquivalentDriverCall()).thenReturn( new Response().addParameter("interfaces", new JSONArray( jsonList).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(2, newGuyDrivers.size()); assertEquals("iddummy1", newGuyDrivers.get(0).id()); assertThat(newGuyDrivers.get(0).driver().toJSON().toMap()) .isEqualTo(dummy1.toJSON().toMap()); assertEquals("iddummy2", newGuyDrivers.get(1).id()); assertThat(newGuyDrivers.get(1).driver().toJSON().toMap()) .isEqualTo(dummy2.toJSON().toMap()); }
@Test public void shouldRegisterADriverWithTwoLevelsOfUnknownEquivalentDrivers() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy = new UpDriver("DummyDriver"); dummy.addService("s1"); dummy.addEquivalentDrivers("equivalentDriver"); driverList.put("id1", dummy.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); UpDriver equivalentDriver = new UpDriver("equivalentDriver"); equivalentDriver.addService("s1"); equivalentDriver .addEquivalentDrivers("equivalentToTheEquivalentDriver"); UpDriver equivalentToTheEquivalentDriver = new UpDriver( "equivalentToTheEquivalentDriver"); equivalentToTheEquivalentDriver.addService("s1"); List<JSONObject> equivalentDrivers = new ArrayList<JSONObject>(); equivalentDrivers.add(equivalentDriver.toJSON()); equivalentDrivers.add(equivalentToTheEquivalentDriver.toJSON()); when(gatewayTellEquivalentDriverCall()).thenReturn( new Response().addParameter("interfaces", new JSONArray( equivalentDrivers).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(1, newGuyDrivers.size()); assertEquals("id1", newGuyDrivers.get(0).id()); assertThat(newGuyDrivers.get(0).driver().toJSON().toMap()) .isEqualTo(dummy.toJSON().toMap()); }
@Test public void shouldRegisterTwoDriversWithTheSameUnknownEquivalentDriverFromDifferentLevels() throws ServiceCallException, JSONException { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); UpDevice device = new UpDevice("A").addNetworkInterface("A", "T"); when(gatewayHandshakeCall()) .thenReturn( new Response().addParameter("device", device.toString())); JSONObject driverList = new JSONObject(); UpDriver dummy1 = new UpDriver("D1"); dummy1.addService("s1"); dummy1.addEquivalentDrivers("D0"); UpDriver dummy2 = new UpDriver("D4"); dummy2.addService("s1"); dummy2.addEquivalentDrivers("D3"); driverList.put("iddummy1", dummy1.toJSON()); driverList.put("iddummy2", dummy2.toJSON()); when(gatewayListDriversCall()).thenReturn( new Response().addParameter("driverList", driverList.toString())); List<JSONObject> jsonList = new ArrayList<JSONObject>(); UpDriver d0 = new UpDriver("D0"); d0.addService("s1"); UpDriver d2 = new UpDriver("D2"); d2.addService("s1"); d2.addEquivalentDrivers(d0.getName()); UpDriver d3 = new UpDriver("D3"); d3.addService("s1"); d3.addEquivalentDrivers(d2.getName()); jsonList.add(d3.toJSON()); jsonList.add(d0.toJSON()); jsonList.add(d2.toJSON()); when(gatewayTellTwoEquivalentDrivers()).thenReturn( new Response().addParameter("interfaces", new JSONArray( jsonList).toString())); deviceManager.deviceEntered(enteree); List<DriverModel> newGuyDrivers = driverDao.list(null, "A"); assertEquals(2, newGuyDrivers.size()); if (newGuyDrivers.get(0).id().equals("iddummy1")){ assertEquals("iddummy1", newGuyDrivers.get(0).id()); assertThat(newGuyDrivers.get(0).driver().toJSON().toMap()) .isEqualTo(dummy1.toJSON().toMap()); assertEquals("iddummy2", newGuyDrivers.get(1).id()); assertThat(newGuyDrivers.get(1).driver().toJSON().toMap()) .isEqualTo(dummy2.toJSON().toMap()); }else{ assertEquals("iddummy2", newGuyDrivers.get(0).id()); assertThat(newGuyDrivers.get(0).driver().toJSON().toMap()) .isEqualTo(dummy2.toJSON().toMap()); assertEquals("iddummy1", newGuyDrivers.get(1).id()); assertThat(newGuyDrivers.get(1).driver().toJSON().toMap()) .isEqualTo(dummy1.toJSON().toMap()); } }
@Test public void IfTheListDriversDoesNotWorksNothingHappens_NoResponse() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn( new Response().addParameter("device", new UpDevice("A") .addNetworkInterface("A", "T").toString())); when(gatewayListDriversCall()).thenReturn(null); deviceManager.deviceEntered(enteree); assertEquals(0, driverDao.list(null, "A").size()); }
@Test public void IfTheListDriversDoesNotWorksNothingHappens_NoData() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn( new Response().addParameter("device", new UpDevice("A") .addNetworkInterface("A", "T").toString())); when(gatewayListDriversCall()).thenReturn(new Response()); deviceManager.deviceEntered(enteree); assertEquals(0, driverDao.list(null, "A").size()); }
@Test public void shouldNotHandshakeWithItsSelf() throws NetworkException, ServiceCallException, JSONException { NetworkDevice enteree = mock(NetworkDevice.class); when(enteree.getNetworkDeviceName()).thenReturn("127.0.0.1:8080"); when(enteree.getNetworkDeviceType()).thenReturn("Ethernet:TCP"); when(connManager.getHost("127.0.0.1:8080")).thenReturn("127.0.0.1"); when(connManager.getHost("127.0.0.1:80")).thenReturn("127.0.0.1"); deviceManager.deviceEntered(enteree); verify(gateway, never()).callService((UpDevice)any(), (Call)any()); }
@Test public void IfTheListDriversDoesNotWorksNothingHappens_ThrowingException() throws Exception { NetworkDevice enteree = networkDevice("ADDR_UNKNOWN", "UNEXISTANT"); when(gatewayHandshakeCall()).thenReturn( new Response().addParameter("device", new UpDevice("A") .addNetworkInterface("A", "T").toString())); when(gatewayListDriversCall()).thenThrow(new RuntimeException()); deviceManager.deviceEntered(enteree); assertEquals(0, driverDao.list(null, "A").size()); } |
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."); String host = connectionManagerControlCenter.getHost(device.getNetworkDeviceName()); List<UpDevice> devices = deviceDao.list(host,device.getNetworkDeviceType()); if (devices != null && !devices.isEmpty()){ UpDevice upDevice = devices.get(0); List<DriverModel> returnedDrivers = driverManager.list(null, upDevice.getName()); if (returnedDrivers != null && !returnedDrivers.isEmpty()){ for (DriverModel rdd : returnedDrivers){ driverManager.delete(rdd.id(), rdd.device()); } } deviceDao.delete(upDevice.getName()); logger.info( String.format("Device '%s' left", upDevice.getName())); } else { logger.info("Device not found in database."); } } DeviceManager(UpDevice currentDevice, DeviceDao deviceDao,
DriverDao driverDao,
ConnectionManagerControlCenter connectionManagerControlCenter,
ConnectivityManager connectivityManager, Gateway gateway,
DriverManager driverManager); void registerDevice(UpDevice device); UpDevice retrieveDevice(String deviceName); UpDevice retrieveDevice(String networkAddress, String networkType); @Override void deviceEntered(NetworkDevice device); @Override void deviceLeft(NetworkDevice device); List<UpDevice> listDevices(); DeviceDao getDeviceDao(); } | @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())); driverDao .insert(new DriverModel("id2", driver, currentDevice.getName())); assertEquals(2, driverDao.list().size()); deviceManager.deviceLeft(leavingGuy); assertEquals(1, dao.list().size()); assertEquals(2, driverDao.list().size()); } |
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 ("+ serviceCall.getService()+ ") on Driver (" + serviceCall.getDriver() + ") in instance ("+ serviceCall.getInstanceId() + ")"); handleStreamCall(serviceCall, messageContext); Response response = new Response(); serviceMethod.invoke(instanceDriver,serviceCall,response,messageContext); logger.info("Finished service call."); return response; }else{ String msg = String.format( "No Service Implementation found " + "for service '%s' on driver '%s' with id '%s'.", serviceCall.getService(), serviceCall.getDriver(), serviceCall.getInstanceId() ); logger.severe(msg); throw new DriverManagerException(msg); } } catch (Exception e) { logInternalError(serviceCall, e); return null; } }else{ String msg = "Null Service Call"; if (serviceCall != null){ msg = String.format( "No Instance Driver (%s) Found for ServiceCall.", serviceCall.getDriver()); } logger.severe(msg); throw new DriverManagerException(msg); } } ReflectionServiceCaller(ConnectionManagerControlCenter connectionManagerControlCenter); Response callServiceOnDriver(Call serviceCall, Object instanceDriver, CallContext messageContext); @SuppressWarnings({ "rawtypes", "unchecked" }) Response callServiceOnApp(UosApplication app,
Call call,
CallContext context); } | @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, "nonExistantService"), new DriverSpy(), null); }
@Test(expected=DriverManagerException.class) public void shouldFailOnAnNonPublicServiceMethod() throws Exception{ caller.callServiceOnDriver(new Call(null, "privateService"), new DriverSpy(), null); }
@Test(expected=DriverManagerException.class) public void shouldFailForNoServiceInformed() throws Exception{ caller.callServiceOnDriver(new Call(), new DriverSpy(), null); }
@Test(expected=DriverManagerException.class) public void shouldFailOnAMethodWithoutACompliantInterface() throws Exception{ caller.callServiceOnDriver(new Call(null, "wrongService"), new DriverSpy(), null); }
@Test public void shouldCallASimpleCompliantServiceWhithTheRightParameters() throws Exception{ Call call = new Call(null, "myService"); CallContext msgCtx = new CallContext(); DriverSpy driver = new DriverSpy(); caller.callServiceOnDriver(call, driver, msgCtx); assertEquals(call,driver.capturedCall); assertEquals(msgCtx,driver.capturedContext); assertNotNull(driver.capturedResponse); assertNull(driver.capturedResponse.getResponseData()); }
@Test public void shouldCallASimpleCompliantServiceIgnoringCase() throws Exception{ Call call = new Call(null, "MySeRvIcE"); CallContext msgCtx = new CallContext(); DriverSpy driver = new DriverSpy(); caller.callServiceOnDriver(call, driver, msgCtx); assertEquals(call,driver.capturedCall); assertEquals(msgCtx,driver.capturedContext); assertNotNull(driver.capturedResponse); assertNull(driver.capturedResponse.getResponseData()); }
@Test(expected=DriverManagerException.class) public void shouldFailWhenServiceFails() throws Exception{ caller.callServiceOnDriver(new Call(null, "failService"), new DriverSpy(), new CallContext()); }
@Test public void shouldForwardServiceOnAProxyDriverMaintainingTheParameters() throws Exception{ Call call = new Call(null, "myService"); CallContext msgCtx = new CallContext(); ProxyDriverSpy driver = new ProxyDriverSpy(); caller.callServiceOnDriver(call, driver, msgCtx); assertTrue(driver.forwardCalled); assertEquals(call,driver.capturedCall); assertEquals(call,driver.capturedCall); assertEquals(msgCtx,driver.capturedContext); assertNotNull(driver.capturedResponse); assertNull(driver.capturedResponse.getResponseData()); }
@Test public void shouldCreateTheAppropriateChannelsForAStreamService() throws Exception{ final LoopbackDevice device = new LoopbackDevice(182); CallContext msgCtx = new CallContext(){ public NetworkDevice getCallerNetworkDevice() { return device; } }; ConnectionManagerControlCenter mockNet = mock(ConnectionManagerControlCenter.class); ClientConnection cc = mock(ClientConnection.class); when(cc.getDataInputStream()).thenReturn(new DataInputStream(null)); when(cc.getDataOutputStream()).thenReturn(new DataOutputStream(null)); when(mockNet.openActiveConnection(anyString(), anyString())).thenReturn(cc); when(mockNet.getHost(anyString())).thenReturn("myname"); caller = new ReflectionServiceCaller(mockNet); Call call = new Call(null, "myService"); call.setServiceType(ServiceType.STREAM); call.setChannelType(device.getNetworkDeviceType()); call.setChannels(4); call.setChannelIDs(new String[]{"P1","P2","P3","P4"}); caller.callServiceOnDriver(call, new DriverSpy(), msgCtx); verify(mockNet).openActiveConnection("myname:P1",call.getChannelType()); verify(mockNet).openActiveConnection("myname:P2",call.getChannelType()); verify(mockNet).openActiveConnection("myname:P3",call.getChannelType()); verify(mockNet).openActiveConnection("myname:P4",call.getChannelType()); for (int i =0; i < 4; i++){ assertNotNull("InputStream: "+i,msgCtx.getDataInputStream(i)); assertNotNull("OutputStream: "+i,msgCtx.getDataOutputStream(i)); } assertNull(msgCtx.getDataInputStream(4)); assertNull(msgCtx.getDataOutputStream(4)); } |
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.parameters = json.optJSONObject("parameters").toMap(); } return e; } Notify(); Notify(String eventKey); Notify(String eventKey, String driver); Notify(String eventKey, String driver, String instanceId); String getEventKey(); void setEventKey(String eventKey); Map<String, Object> getParameters(); void setParameters(Map<String, Object> parameters); Notify addParameter(String key, String value); Notify addParameter(String key, Number value); Object getParameter(String key); @Override boolean equals(Object obj); @Override int hashCode(); String getDriver(); void setDriver(String driver); String getInstanceId(); void setInstanceId(String instanceId); JSONObject toJSON(); static Notify fromJSON(JSONObject json); @Override String toString(); } | @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<DriverModel> list(String name, String device); void clear(); void delete(String id, String device); DriverModel retrieve(String id, String device); } | @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 Instance found with id '"+serviceCall.getInstanceId()+"'"); throw new DriverManagerException("No Instance found with id '"+serviceCall.getInstanceId()+"'"); } }else{ List<DriverModel> list = driverDao.list(serviceCall.getDriver(),currentDevice.getName()); if(list == null || list.isEmpty()){ TreeNode driverNode = driverHash.get(serviceCall.getDriver()); if(driverNode == null) { logger.fine("No instance found for handling driver '"+serviceCall.getDriver()+"'"); throw new DriverManagerException("No instance found for handling driver '"+serviceCall.getDriver()+"'"); } list = findEquivalentDriver(driverNode.getChildren()); if(list == null || list.isEmpty()) { logger.fine("No instance found for handling driver '"+serviceCall.getDriver()+"'"); throw new DriverManagerException("No instance found for handling driver '"+serviceCall.getDriver()+"'"); } } model = list.iterator().next(); } return callServiceOnDriver(serviceCall, instances.get(model.rowid()), messageContext); } DriverManager(UpDevice currentDevice, DriverDao driverDao, DeviceDao deviceDao, ReflectionServiceCaller serviceCaller); Response handleServiceCall(Call serviceCall, CallContext messageContext); void deployDriver(UpDriver driver, Object instance); void deployDriver(UpDriver driver, Object instance, String instanceId); void addToEquivalenceTree(List<UpDriver> drivers); void addToEquivalenceTree(UpDriver driver); void undeployDriver(String instanceId); List<UosDriver> listDrivers(); UpDriver getDriverFromEquivalanceTree(String driverName); List<DriverData> listDrivers(String driverName, String deviceName); void initDrivers(Gateway gateway, InitialProperties properties); void tearDown(); UosDriver driver(String id); List<DriverModel> list(String name, String device); void delete(String id, String device); void insert(DriverModel driverModel); DriverDao getDriverDao(); } | @Test(expected=DriverManagerException.class) public void shouldFailCallingServiceOnDriverUsingAnInvalidInstanceId() throws DriverManagerException, InterfaceValidationException, DriverNotFoundException{ manager.handleServiceCall(new Call("driver","service","id"), null); }
@Test(expected=DriverManagerException.class) public void shouldFailCallingServiceOnDriverUsingAnInvalidDriver() throws DriverManagerException, InterfaceValidationException, DriverNotFoundException{ manager.handleServiceCall(new Call("driver","service"), null); } |
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; } DriverManager(UpDevice currentDevice, DriverDao driverDao, DeviceDao deviceDao, ReflectionServiceCaller serviceCaller); Response handleServiceCall(Call serviceCall, CallContext messageContext); void deployDriver(UpDriver driver, Object instance); void deployDriver(UpDriver driver, Object instance, String instanceId); void addToEquivalenceTree(List<UpDriver> drivers); void addToEquivalenceTree(UpDriver driver); void undeployDriver(String instanceId); List<UosDriver> listDrivers(); UpDriver getDriverFromEquivalanceTree(String driverName); List<DriverData> listDrivers(String driverName, String deviceName); void initDrivers(Gateway gateway, InitialProperties properties); void tearDown(); UosDriver driver(String id); List<DriverModel> list(String name, String device); void delete(String id, String device); void insert(DriverModel driverModel); DriverDao getDriverDao(); } | @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<String> it = toInitialize.iterator(); logger.fine(String.format("Initializing %s drivers.", toInitialize.size())); while(it.hasNext()){ String id = it.next(); DriverModel model = driverDao.retrieve(id,currentDevice.getName()); UosDriver driver = instances.get(model.rowid()); driver.init(gateway, properties, id); it.remove(); logger.fine(String.format("Initialized Driver %s with id '%s'", model.driver().getName(),id)); } } DriverManager(UpDevice currentDevice, DriverDao driverDao, DeviceDao deviceDao, ReflectionServiceCaller serviceCaller); Response handleServiceCall(Call serviceCall, CallContext messageContext); void deployDriver(UpDriver driver, Object instance); void deployDriver(UpDriver driver, Object instance, String instanceId); void addToEquivalenceTree(List<UpDriver> drivers); void addToEquivalenceTree(UpDriver driver); void undeployDriver(String instanceId); List<UosDriver> listDrivers(); UpDriver getDriverFromEquivalanceTree(String driverName); List<DriverData> listDrivers(String driverName, String deviceName); void initDrivers(Gateway gateway, InitialProperties properties); void tearDown(); UosDriver driver(String id); List<DriverModel> list(String name, String device); void delete(String id, String device); void insert(DriverModel driverModel); DriverDao getDriverDao(); } | @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 deployDriver(UpDriver driver, Object instance); void deployDriver(UpDriver driver, Object instance, String instanceId); void addToEquivalenceTree(List<UpDriver> drivers); void addToEquivalenceTree(UpDriver driver); void undeployDriver(String instanceId); List<UosDriver> listDrivers(); UpDriver getDriverFromEquivalanceTree(String driverName); List<DriverData> listDrivers(String driverName, String deviceName); void initDrivers(Gateway gateway, InitialProperties properties); void tearDown(); UosDriver driver(String id); List<DriverModel> list(String name, String device); void delete(String id, String device); void insert(DriverModel driverModel); DriverDao getDriverDao(); } | @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.instanceID); } } return false; } DriverData(UpDriver driver, UpDevice device, String instanceID); boolean equals(Object obj); String getInstanceID(); UpDriver getDriver(); UpDevice getDevice(); } | @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); DriverData that = new DriverData(new UpDriver("b"),null,null); assertFalse(thiz.equals(that)); }
@Test public void notEqualsWithDifferentDevice(){ DriverData thiz = new DriverData(new UpDriver("a"),new UpDevice("da"),null); DriverData that = new DriverData(new UpDriver("b"),new UpDevice("db"),null); assertFalse(thiz.equals(that)); }
@Test public void notEqualsWithDifferentInstanceId(){ DriverData thiz = new DriverData(new UpDriver("a"),new UpDevice("da"),"ida"); DriverData that = new DriverData(new UpDriver("b"),new UpDevice("db"),"idb"); assertFalse(thiz.equals(that)); }
@Test public void equalsWithAllDataEquals(){ DriverData thiz = new DriverData(new UpDriver("a"),new UpDevice("da"),"ida"); DriverData that = new DriverData(new UpDriver("a"),new UpDevice("da"),"ida"); assertTrue(thiz.equals(that)); } |
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 startApplications(); void deploy(UosApplication app); void deploy(UosApplication app, String id); void tearDown(); UosApplication findApplication(String id); Response handleServiceCall(Call serviceCall,
CallContext messageContext); } | @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 deploy(UosApplication app); void deploy(UosApplication app, String id); void tearDown(); UosApplication findApplication(String id); Response handleServiceCall(Call serviceCall,
CallContext messageContext); } | @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 listener for event :"+eventIdentifier); if (findListener(listener, listenerMap.get(eventIdentifier))== null){ ListenerInfo info = new ListenerInfo(); info.driver = driver; info.instanceId = instanceId; info.eventKey = eventKey; info.listener = listener; info.device = device; registerNewListener(device, parameters, eventIdentifier, info); } } EventManager(MessageEngine messageEngine); void notify(Notify notify, UpDevice device); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String,Object> parameters); void unregister(UosEventListener listener, UpDevice device, String driver, String instanceId, String eventKey); void handleNofify(Notify notify, UpDevice device); } | @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().getService()).isEqualTo("registerListener"); }
@Test public void registeringDelegatesToMessageEngineWithParams() throws Exception{ UpDevice device = new UpDevice("the_device"); @SuppressWarnings("serial") Map<String,Object> parameters = new HashMap<String, Object>(){{ put("example","this"); }}; manager.register(listener, device, "driver", "id", "key",parameters); verify(engine).callService(eq(device), call.capture()); assertThat(call.getAllValues()).hasSize(1); assertThat(call.getValue().getService()).isEqualTo("registerListener"); assertThat(call.getValue().getDriver()).isEqualTo("driver"); assertThat(call.getValue().getInstanceId()).isEqualTo("id"); assertThat(call.getValue().getParameterString("eventKey")).isEqualTo("key"); assertThat(call.getValue().getParameterString("example")).isEqualTo("this"); }
@Test(expected=NotifyException.class) public void registeringRejectsParameterWithReservedKey() throws Exception{ UpDevice device = new UpDevice("the_device"); @SuppressWarnings("serial") Map<String,Object> parameters = new HashMap<String, Object>(){{ put("eventKey","this"); }}; manager.register(listener, device, "driver", "id", "key",parameters); }
@Test(expected=NotifyException.class) public void registeringHandlesErrors() throws Exception{ Response r = new Response(); r.setError("Something"); when(engine.callService((UpDevice)any(), (Call)any())).thenReturn(r); manager.register(listener, new UpDevice("the_device"), "driver", "id", "key", null); }
@Test(expected=NotifyException.class) public void registeringHandlesNullResponse() throws Exception{ when(engine.callService((UpDevice)any(), (Call)any())).thenReturn(null); manager.register(listener, new UpDevice("the_device"), "driver", "id", "key", null); }
@Test public void registeringDontDelegatesForNullDevice() throws Exception{ manager.register(listener, null, "driver", "id", "key", null); verify(engine,never()).callService((UpDevice)any(),(Call)any()); } |
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 IllegalArgumentException("Either the Device or Service is invalid."); } try { JSONObject jsonCall = serviceCall.toJSON(); if (serviceCall.getSecurityType() != null ){ String data = sendEncapsulated(jsonCall.toString(), serviceCall.getSecurityType(), device); return Response.fromJSON(new JSONObject(data)); } String returnedMessage = send(jsonCall.toString(), device,true); if (returnedMessage != null) return Response.fromJSON(new JSONObject(returnedMessage)); } catch (Exception e) { throw new MessageEngineException(e); } return null; } MessageHandler(
InitialProperties bundle,
ConnectionManagerControlCenter connectionManagerControlCenter,
SecurityManager securityManager,
ConnectivityManager connectivityManager
); Response callService(UpDevice device,Call serviceCall); void notifyEvent(Notify notify, UpDevice device); } | @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")); }
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectNullDriverAndServiceOnCall() throws Exception{ handler.callService(mock(UpDevice.class),new Call()); }
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectNullDriverOnCall() throws Exception{ handler.callService(mock(UpDevice.class),new Call(null,"s")); }
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectNullServiceOnCall() throws Exception{ handler.callService(mock(UpDevice.class),new Call("d",null)); }
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectEmptyDriverAndServiceOnCall() throws Exception{ handler.callService(mock(UpDevice.class),new Call("","")); }
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectEmptyDriverOnCall() throws Exception{ handler.callService(mock(UpDevice.class),new Call("","s")); }
@Test(expected=IllegalArgumentException.class) public void callService_ShouldRejectEmptyServiceOnCall() throws Exception{ handler.callService(mock(UpDevice.class),new Call("d","")); }
@Test public void callService_aSimpleCallMustBeSentAndItsResponseRetrieved() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); for (char c : "{type:\"SERVICE_CALL_RESPONSE\", responseData:{pic:\"NotAvailable\"}}\n".toCharArray()){ scenario.wifiInterfaceIn.write(c); } Response response = handler .callService(scenario.target, scenario.snapshot); assertEquals("Should return the same response that was stimulated.", "NotAvailable",response.getResponseData("pic")); assertThat(Call.fromJSON(new JSONObject(scenario.grabSentString()))) .isEqualTo(scenario.snapshot); }
@Test public void callService_aSimpleCallMustBeSentButWhenNoResponseIsRetrievedNullShouldBeReturned() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); assertNull("No response must be returned.", handler.callService(scenario.target, scenario.snapshot)); assertThat(Call.fromJSON(new JSONObject(scenario.grabSentString()))) .isEqualTo(scenario.snapshot); }
@Test public void callService_aSimpleCallMustBeSentButWhenNoConnectionIsPossibleNullShouldBeReturned() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); when(controlCenter.openActiveConnection( scenario.wifi.getNetworkAddress(), scenario.wifi.getNetType())).thenReturn(null); assertNull("No response must be returned.", handler.callService(scenario.target, scenario.snapshot)); }
@Test public void callService_aSimpleCallMustBeSentButWhenNoValidConnectionIsReturnedNullShouldBeReturned() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); ClientConnection mock = mock(ClientConnection.class); when(controlCenter.openActiveConnection( scenario.wifi.getNetworkAddress(), scenario.wifi.getNetType())).thenReturn(mock); assertNull("No response must be returned.", handler.callService(scenario.target, scenario.snapshot)); }
@Test public void callService_ACallWithSecurityTypeMustResultOnAnEncapsulatedMessage() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); scenario.snapshot.setSecurityType("Pig-Latin"); AuthenticationHandler auth = mock(AuthenticationHandler.class); when(securityManager.getAuthenticationHandler("Pig-Latin")).thenReturn(auth); TranslationHandler translator = mock(TranslationHandler.class); when(securityManager.getTranslationHandler("Pig-Latin")).thenReturn(translator); when(translator.encode(any(String.class), eq(scenario.target.getName()))) .thenReturn("Encoded Output Message"); for (char c : "{type:\"ENCAPSULATED_MESSAGE\", innerMessage:\"Encoded Input Message\", securityType:\"Pig-Latin\"}\n".toCharArray()){ scenario.wifiInterfaceIn.write(c); } when(translator.decode(eq("Encoded Input Message"), eq(scenario.target.getName()))) .thenReturn("{type:\"SERVICE_CALL_RESPONSE\", responseData:{pic:\"StillNotAvailable\"}}"); Response response = handler.callService(scenario.target, scenario.snapshot); assertEquals("StillNotAvailable",response.getResponseData("pic")); verify(auth).authenticate(scenario.target, handler); Capsule sentMessage = Capsule.fromJSON(new JSONObject(scenario.grabSentString())); assertEquals("The security type should be unchanged.","Pig-Latin",sentMessage.getSecurityType()); assertEquals("Should have sent the encoded message.","Encoded Output Message",sentMessage.getInnerMessage()); }
@Test(expected=MessageEngineException.class) public void callService_ACallWithProblemsThrowsAnException() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); when(controlCenter.openActiveConnection(any(String.class), any(String.class))) .thenThrow(new RuntimeException()); handler.callService(scenario.target, scenario.snapshot); }
@Test(expected=MessageEngineException.class) public void callService_ACallWithSecurityTypeFailsWihtoutProperAuthenticator() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); scenario.snapshot.setSecurityType("Pig-Latin"); AuthenticationHandler auth = mock(AuthenticationHandler.class); when(securityManager.getAuthenticationHandler("Not-Pig-Latin")).thenReturn(auth); TranslationHandler translator = mock(TranslationHandler.class); when(securityManager.getTranslationHandler("Pig-Latin")).thenReturn(translator); handler.callService(scenario.target, scenario.snapshot); }
@Test(expected=MessageEngineException.class) public void callService_ACallWithSecurityTypeFailsWihtoutProperTranslator() throws Exception{ SnapshotScenario scenario = new SnapshotScenario(); scenario.snapshot.setSecurityType("Pig-Latin"); AuthenticationHandler auth = mock(AuthenticationHandler.class); when(securityManager.getAuthenticationHandler("Pig-Latin")).thenReturn(auth); TranslationHandler translator = mock(TranslationHandler.class); when(securityManager.getTranslationHandler("NotPig-Latin")).thenReturn(translator); handler.callService(scenario.target, scenario.snapshot); } |
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 messageEngine); void notify(Notify notify, UpDevice device); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String,Object> parameters); void unregister(UosEventListener listener, UpDevice device, String driver, String instanceId, String eventKey); void handleNofify(Notify notify, UpDevice device); } | @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 exception = null; Iterator<ListenerInfo> it = listeners.iterator(); ListenerInfo li; while(it.hasNext() ){ li = it.next(); if (li.listener.equals(listener) ){ boolean remove = true; if (driver != null && li.driver != null){ remove = li.driver.equals(driver); } if (instanceId != null && li.instanceId != null){ remove = li.instanceId.equals(instanceId); } if (remove){ try { unregisterForEvent(li); it.remove(); } catch (NotifyException e) { logger.log(Level.SEVERE,"Failed to unregisterForEvent",e); exception = e; } } } } if (exception != null){ throw exception; } } EventManager(MessageEngine messageEngine); void notify(Notify notify, UpDevice device); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String,Object> parameters); void unregister(UosEventListener listener, UpDevice device, String driver, String instanceId, String eventKey); void handleNofify(Notify notify, UpDevice device); } | @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, parameters); } void init(AdaptabilityEngine adaptabilityEngine,
UpDevice currentDevice, SecurityManager securityManager,
ConnectivityManager connectivityManager,
DeviceManager deviceManager, DriverManager driverManager,
ApplicationDeployer applicationDeployer, Ontology ontology); Response callService(UpDevice device, String serviceName,
String driverName, String instanceId, String securityType,
Map<String, Object> parameters); Response callService(UpDevice device, Call serviceCall); void register(UosEventListener listener, UpDevice device,
String driver, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String, Object> parameters); List<DriverData> listDrivers(String driverName); List<UpDevice> listDevices(); UpDevice getCurrentDevice(); void notify(Notify notify, UpDevice device); void unregister(UosEventListener listener); void unregister(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); SecurityManager getSecurityManager(); ConnectivityManager getConnectivityManager(); DeviceManager getDeviceManager(); DriverManager getDriverManager(); ApplicationDeployer getApplicationDeployer(); StartReasoner getOntologyReasoner(); Ontology getOntology(); } | @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 Exception{ UpDevice target = new UpDevice("a"); gateway.callService(target, "s", "d", "i", "t", new HashMap<String, Object>()); verify(engine).callService(target, "s", "d", "i", "t", new HashMap<String, Object>()); } |
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 securityManager,
ConnectivityManager connectivityManager,
DeviceManager deviceManager, DriverManager driverManager,
ApplicationDeployer applicationDeployer, Ontology ontology); Response callService(UpDevice device, String serviceName,
String driverName, String instanceId, String securityType,
Map<String, Object> parameters); Response callService(UpDevice device, Call serviceCall); void register(UosEventListener listener, UpDevice device,
String driver, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String, Object> parameters); List<DriverData> listDrivers(String driverName); List<UpDevice> listDevices(); UpDevice getCurrentDevice(); void notify(Notify notify, UpDevice device); void unregister(UosEventListener listener); void unregister(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); SecurityManager getSecurityManager(); ConnectivityManager getConnectivityManager(); DeviceManager getDeviceManager(); DriverManager getDriverManager(); ApplicationDeployer getApplicationDeployer(); StartReasoner getOntologyReasoner(); Ontology getOntology(); } | @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 registerForEventWithMultipleParamsAlsoDelegatesToAdaptabilityEngine() throws Exception{ UpDevice target = new UpDevice("a"); UosEventListener listener = new EventListener(); gateway.register(listener,target, "d", "i", "e"); verify(engine).register(listener, target, "d", "i", "e",null); }
@Test public void registerForEventWithParamsAlsoDelegatesToAdaptabilityEngine() throws Exception{ UpDevice target = new UpDevice("a"); UosEventListener listener = new EventListener(); HashMap<String, Object> params = new HashMap<String, Object>(); gateway.register(listener,target, "d", "i", "e",params); verify(engine).register(listener, target, "d", "i", "e",params); } |
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,
DeviceManager deviceManager, DriverManager driverManager,
ApplicationDeployer applicationDeployer, Ontology ontology); Response callService(UpDevice device, String serviceName,
String driverName, String instanceId, String securityType,
Map<String, Object> parameters); Response callService(UpDevice device, Call serviceCall); void register(UosEventListener listener, UpDevice device,
String driver, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String, Object> parameters); List<DriverData> listDrivers(String driverName); List<UpDevice> listDevices(); UpDevice getCurrentDevice(); void notify(Notify notify, UpDevice device); void unregister(UosEventListener listener); void unregister(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); SecurityManager getSecurityManager(); ConnectivityManager getConnectivityManager(); DeviceManager getDeviceManager(); DriverManager getDriverManager(); ApplicationDeployer getApplicationDeployer(); StartReasoner getOntologyReasoner(); Ontology getOntology(); } | @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,
DeviceManager deviceManager, DriverManager driverManager,
ApplicationDeployer applicationDeployer, Ontology ontology); Response callService(UpDevice device, String serviceName,
String driverName, String instanceId, String securityType,
Map<String, Object> parameters); Response callService(UpDevice device, Call serviceCall); void register(UosEventListener listener, UpDevice device,
String driver, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String, Object> parameters); List<DriverData> listDrivers(String driverName); List<UpDevice> listDevices(); UpDevice getCurrentDevice(); void notify(Notify notify, UpDevice device); void unregister(UosEventListener listener); void unregister(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); SecurityManager getSecurityManager(); ConnectivityManager getConnectivityManager(); DeviceManager getDeviceManager(); DriverManager getDriverManager(); ApplicationDeployer getApplicationDeployer(); StartReasoner getOntologyReasoner(); Ontology getOntology(); } | @Test public void unregisterForEventDelegatesToAdaptabilityEngine() throws Exception{ UosEventListener listener = new EventListener(); gateway.unregister(listener); verify(engine).unregister(listener); }
@Test public void unregisterForEventWithMultipleParamsAlsoDelegatesToAdaptabilityEngine() throws Exception{ UosEventListener listener = new EventListener(); UpDevice target = new UpDevice("a"); gateway.unregister(listener,target,"d","i","e"); verify(engine).unregister(listener,target,"d","i","e"); } |
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 deviceManager, DriverManager driverManager,
ApplicationDeployer applicationDeployer, Ontology ontology); Response callService(UpDevice device, String serviceName,
String driverName, String instanceId, String securityType,
Map<String, Object> parameters); Response callService(UpDevice device, Call serviceCall); void register(UosEventListener listener, UpDevice device,
String driver, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String, Object> parameters); List<DriverData> listDrivers(String driverName); List<UpDevice> listDevices(); UpDevice getCurrentDevice(); void notify(Notify notify, UpDevice device); void unregister(UosEventListener listener); void unregister(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); SecurityManager getSecurityManager(); ConnectivityManager getConnectivityManager(); DeviceManager getDeviceManager(); DriverManager getDriverManager(); ApplicationDeployer getApplicationDeployer(); StartReasoner getOntologyReasoner(); Ontology getOntology(); } | @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 driverManager,
ApplicationDeployer applicationDeployer, Ontology ontology); Response callService(UpDevice device, String serviceName,
String driverName, String instanceId, String securityType,
Map<String, Object> parameters); Response callService(UpDevice device, Call serviceCall); void register(UosEventListener listener, UpDevice device,
String driver, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); void register(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey,
Map<String, Object> parameters); List<DriverData> listDrivers(String driverName); List<UpDevice> listDevices(); UpDevice getCurrentDevice(); void notify(Notify notify, UpDevice device); void unregister(UosEventListener listener); void unregister(UosEventListener listener, UpDevice device,
String driver, String instanceId, String eventKey); SecurityManager getSecurityManager(); ConnectivityManager getConnectivityManager(); DeviceManager getDeviceManager(); DriverManager getDriverManager(); ApplicationDeployer getApplicationDeployer(); StartReasoner getOntologyReasoner(); Ontology getOntology(); } | @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") void listDrivers(Call serviceCall, Response serviceResponse, CallContext messageContext); void authenticate(Call serviceCall,
Response serviceResponse, CallContext messageContext); void handshake(Call serviceCall, Response serviceResponse, CallContext messageContext); void goodbye(Call serviceCall,Response serviceResponse, CallContext messageContext); void tellEquivalentDrivers(Call serviceCall, Response serviceResponse, CallContext messageContext); } | @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) ); }
@Test public void declareAuthenticate(){ assertThat(instance.getDriver().getServices()) .contains( new UpService("authenticate") .addParameter("securityType", UpService.ParameterType.MANDATORY) ); }
@Test public void declareGoodbye(){ assertThat(instance.getDriver().getServices()) .contains( new UpService("goodbye") ); }
@Test public void declareHandshake(){ assertThat(instance.getDriver().getServices()) .contains( new UpService("handshake") .addParameter("device", UpService.ParameterType.MANDATORY) ); }
@Test public void declareTellEquivalentDriver(){ assertThat(instance.getDriver().getServices()) .contains( new UpService("tellEquivalentDriver") .addParameter("driverName", UpService.ParameterType.MANDATORY) ); } |
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,temp.instanceId)) return false; if(!compare(this.parameters,temp.parameters)) return false; return true; } Notify(); Notify(String eventKey); Notify(String eventKey, String driver); Notify(String eventKey, String driver, String instanceId); String getEventKey(); void setEventKey(String eventKey); Map<String, Object> getParameters(); void setParameters(Map<String, Object> parameters); Notify addParameter(String key, String value); Notify addParameter(String key, Number value); Object getParameter(String key); @Override boolean equals(Object obj); @Override int hashCode(); String getDriver(); void setDriver(String driver); String getInstanceId(); void setInstanceId(String instanceId); JSONObject toJSON(); static Notify fromJSON(JSONObject json); @Override String toString(); } | @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"))); assertFalse(new Notify("e","d", "id1").equals(new Notify("e","d","id2"))); }
@Test public void equalsWithEmpty(){ assertTrue(new Notify().equals(new Notify())); }
@Test public void notEqualsWithNullData(){ assertFalse(new Notify().equals(new Notify("e"))); assertFalse(new Notify().equals(new Notify("e","d"))); assertFalse(new Notify().equals(new Notify("e","d","id"))); }
@Test public void equalsWithEventKey(){ assertTrue(new Notify("e").equals(new Notify("e"))); assertTrue(new Notify("e","d").equals(new Notify("e","d"))); assertTrue(new Notify("e","d","id").equals(new Notify("e","d","id"))); } |
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 Device or Service is invalid."); } try { String message = notify.toJSON().toString(); send(message, device,false); } catch (Exception e) { throw new MessageEngineException(e); } } MessageHandler(
InitialProperties bundle,
ConnectionManagerControlCenter connectionManagerControlCenter,
SecurityManager securityManager,
ConnectivityManager connectivityManager
); Response callService(UpDevice device,Call serviceCall); void notifyEvent(Notify notify, UpDevice device); } | @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"),null); }
@Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectNullDriverAndKeyOnEvent() throws Exception{ handler.notifyEvent(new Notify(),mock(UpDevice.class)); }
@Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectNullDriverOnEvent() throws Exception{ handler.notifyEvent(new Notify(null,"s"),mock(UpDevice.class)); }
@Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectNullKeyOnEvent() throws Exception{ handler.notifyEvent(new Notify("d",null),mock(UpDevice.class)); }
@Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectEmptyDriverAndKeyOnEvent() throws Exception{ handler.notifyEvent(new Notify("",""),mock(UpDevice.class)); }
@Test(expected=IllegalArgumentException.class) public void notifyEventShouldRejectEmptyDriverOnEvent() throws Exception{ handler.notifyEvent(new Notify("","s"),mock(UpDevice.class)); }
@Test(expected=IllegalArgumentException.class) public void notifyEvent_ShouldRejectEmptyKeyOnEvent() throws Exception{ handler.notifyEvent(new Notify("d",""),mock(UpDevice.class)); }
@Test public void notifyEvent_shouldSendForASimpleEvent() throws Exception{ UserEnteredScenario scenario = new UserEnteredScenario(); handler.notifyEvent(scenario.userEntered,scenario.target); assertEquals("The JSON sent should be compatible with the snapshot created.", scenario.userEntered, Notify.fromJSON(new JSONObject(scenario.grabSentString()))); }
@Test(expected=MessageEngineException.class) public void notifyEvent_ACallWithProblemsThrowsAnException() throws Exception{ UserEnteredScenario scenario = new UserEnteredScenario(); when(controlCenter.openActiveConnection(any(String.class), any(String.class))) .thenThrow(new RuntimeException()); handler.notifyEvent(scenario.userEntered, scenario.target); } |
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(); UpDriver(String name); String getName(); void setName(String name); List<UpService> getServices(); void setServices(List<UpService> services); UpService addService(UpService service); UpService addService(String serviceName); List<String> getEquivalentDrivers(); void setEquivalentDrivers(List<String> equivalentDrivers); List<String> addEquivalentDrivers(String driver); @Override boolean equals(Object obj); @Override int hashCode(); UpDriver addEvent(UpService event); UpService addEvent(String event); List<UpService> getEvents(); void setEvents(List<UpService> events); JSONObject toJSON(); static UpDriver fromJSON(JSONObject json); } | @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 notEqualsWithNullName(){ assertFalse(new UpDriver(null).equals(new UpDriver("name"))); }
@Test public void equalsWithBothWithNullName(){ assertTrue(new UpDriver(null).equals(new UpDriver(null))); }
@Test public void equalsWithNameEquals(){ assertTrue(new UpDriver("driver").equals(new UpDriver("driver"))); } |
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); UpService addService(String serviceName); List<String> getEquivalentDrivers(); void setEquivalentDrivers(List<String> equivalentDrivers); List<String> addEquivalentDrivers(String driver); @Override boolean equals(Object obj); @Override int hashCode(); UpDriver addEvent(UpService event); UpService addEvent(String event); List<UpService> getEvents(); void setEvents(List<UpService> events); JSONObject toJSON(); static UpDriver fromJSON(JSONObject json); } | @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(String name); String getName(); void setName(String name); List<UpService> getServices(); void setServices(List<UpService> services); UpService addService(UpService service); UpService addService(String serviceName); List<String> getEquivalentDrivers(); void setEquivalentDrivers(List<String> equivalentDrivers); List<String> addEquivalentDrivers(String driver); @Override boolean equals(Object obj); @Override int hashCode(); UpDriver addEvent(UpService event); UpService addEvent(String event); List<UpService> getEvents(); void setEvents(List<UpService> events); JSONObject toJSON(); static UpDriver fromJSON(JSONObject json); } | @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().toMap()) .isEqualTo(json.toMap()); } |
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(String name); String getName(); void setName(String name); List<UpService> getServices(); void setServices(List<UpService> services); UpService addService(UpService service); UpService addService(String serviceName); List<String> getEquivalentDrivers(); void setEquivalentDrivers(List<String> equivalentDrivers); List<String> addEquivalentDrivers(String driver); @Override boolean equals(Object obj); @Override int hashCode(); UpDriver addEvent(UpService event); UpService addEvent(String event); List<UpService> getEvents(); void setEvents(List<UpService> events); JSONObject toJSON(); static UpDriver fromJSON(JSONObject json); } | @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(); UpDevice(String name); UpDevice addNetworkInterface(String networkAdress, String networkType); String getName(); void setName(String name); List<UpNetworkInterface> getNetworks(); void setNetworks(List<UpNetworkInterface> networks); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Object getProperty(String key); void addProperty(String key, String value); Map<String, String> getMeta(); void setMeta(Map<String, String> meta); JSONObject toJSON(); static UpDevice fromJSON(JSONObject json); } | @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(){ assertFalse(new UpDevice(null).equals(new UpDevice("name"))); }
@Test public void equalsWithBothWithNullName(){ assertTrue(new UpDevice(null).equals(new UpDevice(null))); }
@Test public void equalsWithNameEquals(){ assertTrue(new UpDevice("d").equals(new UpDevice("d"))); } |
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 setNetworks(List<UpNetworkInterface> networks); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Object getProperty(String key); void addProperty(String key, String value); Map<String, String> getMeta(); void setMeta(Map<String, String> meta); JSONObject toJSON(); static UpDevice fromJSON(JSONObject json); } | @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 setName(String name); List<UpNetworkInterface> getNetworks(); void setNetworks(List<UpNetworkInterface> networks); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Object getProperty(String key); void addProperty(String key, String value); Map<String, String> getMeta(); void setMeta(Map<String, String> meta); JSONObject toJSON(); static UpDevice fromJSON(JSONObject json); } | @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 addNetworkInterface(String networkAdress, String networkType); String getName(); void setName(String name); List<UpNetworkInterface> getNetworks(); void setNetworks(List<UpNetworkInterface> networks); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Object getProperty(String key); void addProperty(String key, String value); Map<String, String> getMeta(); void setMeta(Map<String, String> meta); JSONObject toJSON(); static UpDevice fromJSON(JSONObject json); } | @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.fromJSON(temp)) .isEqualTo(dummyDevice()); }
@Test public void fromJSONForEmpty() throws JSONException{ assertThat(UpDevice.fromJSON(new JSONObject())) .isEqualTo(new UpDevice()); } |
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 = retrieveMessageType(json); if (messageType != null){ if (messageType == Message.Type.SERVICE_CALL_REQUEST){ logger.info("Incoming Service Call"); CallContext messageContext = new CallContext(); messageContext.setCallerNetworkDevice(clientDevice); return handleServiceCall(message, messageContext); }else if (messageType == Message.Type.NOTIFY){ logger.info("Incoming Notify"); handleNotify(message,clientDevice); return null; }else if (messageType == Message.Type.ENCAPSULATED_MESSAGE){ logger.info("Incoming Encapsulated Message"); return handleEncapsulatedMessage(message,clientDevice); } } } catch (JSONException e) { logger.log(Level.INFO,"Failure to handle the incoming message",e); Notify event = new Notify(); event.setError("Failure to handle the incoming message"); try {return event.toJSON().toString();} catch (JSONException z) {logger.severe("Never Happens");} } return null; } @Override String handleIncomingMessage(String message,NetworkDevice clientDevice); void notify(Notify notify, UpDevice device); Response callService(UpDevice device,Call serviceCall); @Override void create(InitialProperties properties); @Override void init(UOSComponentFactory factory); @Override void start(); @Override void stop(); void setDeviceManager(DeviceManager deviceManager); } | @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 handleIncomingMessage_returnErrorForMalformedJson() throws Exception{ JSONObject response = new JSONObject(engine.handleIncomingMessage("not a json", mock(NetworkDevice.class))); assertTrue(response.has("error")); assertFalse(response.optString("error").isEmpty()); }
@Test public void handleIncomingMessage_returnErrorFoMessageWithoutKnowType() throws Exception{ assertNull(engine.handleIncomingMessage("{type:\"NotKnownType\"}", mock(NetworkDevice.class))); }
@Test public void handleIncomingMessage_delegateNotifyToHandler() throws Exception{ JSONObject call = new JSONObject(); call.put("type", "NOTIFY"); call.put("driver", "my.driver"); call.put("eventKey", "my.event"); NetworkDevice caller = mock(NetworkDevice.class); when(deviceManager.retrieveDevice(null, null)).thenReturn(new UpDevice("oi")); assertNull(engine.handleIncomingMessage(call.toString(), caller)); ArgumentCaptor<Notify> eventCatcher = ArgumentCaptor.forClass(Notify.class); ArgumentCaptor<UpDevice> deviceCatcher = ArgumentCaptor.forClass(UpDevice.class); verify(eventHandler).handleNofify(eventCatcher.capture(), deviceCatcher.capture()); assertEquals("my.driver",eventCatcher.getValue().getDriver()); assertEquals("my.event",eventCatcher.getValue().getEventKey()); assertEquals("oi",deviceCatcher.getValue().getName()); }
@Test public void handleIncomingMessage_ErrorsDuringEventsDontGenerateConsequences() throws Exception{ JSONObject call = new JSONObject(); call.put("type", "NOTIFY"); call.put("driver", "my.driver"); call.put("eventKey", "my.event"); NetworkDevice caller = mock(NetworkDevice.class); when(deviceManager.retrieveDevice(null, null)).thenThrow(new RuntimeException()); assertNull(engine.handleIncomingMessage(call.toString(), caller)); }
@Test public void handleIncomingMessage_AnEncapsulatedMessageMustBeDelegatedToTheAppropriateKindOfHanlderAfterTranslation_Notify() throws Exception{ JSONObject call = new JSONObject(); call.put("type", "ENCAPSULATED_MESSAGE"); call.put("innerMessage", "my.msg"); call.put("securityType", "abacate"); JSONObject innerCall = new JSONObject(); innerCall.put("type", "NOTIFY"); innerCall.put("driver", "my.driver"); innerCall.put("eventKey", "my.event"); TranslationHandler translator = mock(TranslationHandler.class); when(translator.decode("my.msg", "my.cell")).thenReturn(innerCall.toString()); when(translator.encode(any(String.class), eq("my.cell"))).thenReturn("my.return"); when(securityManager.getTranslationHandler("abacate")).thenReturn(translator); when(deviceManager.retrieveDevice(null, null)).thenReturn(new UpDevice("my.cell")); NetworkDevice caller = mock(NetworkDevice.class); assertNull(engine.handleIncomingMessage(call.toString(), caller)); ArgumentCaptor<Notify> eventCatcher = ArgumentCaptor.forClass(Notify.class); verify(eventHandler).handleNofify(eventCatcher.capture(), any(UpDevice.class)); assertEquals("my.event",eventCatcher.getValue().getEventKey()); }
@Test public void handleIncomingMessage_AnEncapsulatedMessageNeverGenerateAnReturnInCaseOfError() throws Exception{ JSONObject call = new JSONObject(); call.put("type", "ENCAPSULATED_MESSAGE"); call.put("innerMessage", "my.msg"); call.put("securityType", "abacate"); JSONObject innerCall = new JSONObject(); innerCall.put("type", "BUGGEDINNERMESSAGE"); innerCall.put("driver", "my.driver"); innerCall.put("eventKey", "my.event"); TranslationHandler translator = mock(TranslationHandler.class); when(translator.decode("my.msg", "my.cell")).thenReturn(innerCall.toString()); when(translator.encode(any(String.class), eq("my.cell"))).thenReturn("my.return"); when(securityManager.getTranslationHandler("abacate")).thenReturn(translator); when(deviceManager.retrieveDevice(null, null)).thenThrow(new RuntimeException()); NetworkDevice caller = mock(NetworkDevice.class); assertNull(engine.handleIncomingMessage(call.toString(), caller)); } |
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(ni.getNetType()).add(device); if(!addressMap.containsKey(ni.getNetworkAddress())){ addressMap.put(ni.getNetworkAddress(), new ArrayList<UpDevice>()); } addressMap.get(ni.getNetworkAddress()).add(device); } } deviceMap.put(device.getName().toLowerCase(),device); } DeviceDao(InitialProperties bundle); void save(UpDevice device); void update(String oldname, UpDevice device); void delete(String name); List<UpDevice> list(); List<UpDevice> list(String address, String networktype); UpDevice find(String name); void clear(); } | @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 gateway,
DriverManager driverManager); void registerDevice(UpDevice device); UpDevice retrieveDevice(String deviceName); UpDevice retrieveDevice(String networkAddress, String networkType); @Override void deviceEntered(NetworkDevice device); @Override void deviceLeft(NetworkDevice device); List<UpDevice> listDevices(); DeviceDao getDeviceDao(); } | @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(toRegister)); }
@Test public void shouldRetrieveMultipleInstancesByDriverName() throws DriverManagerException, DriverNotFoundException { UpDriver driver = new UpDriver("d1"); UpDevice myPhone = new UpDevice("my.Phone"); deviceManager.registerDevice(myPhone); driverManager.insert(new DriverModel("id1", driver, "my.Phone")); driverManager.insert(new DriverModel("id2", driver, currentDevice .getName())); driverManager.insert(new DriverModel("id3", new UpDriver("d3"), "my.tablet")); List<DriverData> list = driverManager.listDrivers("d1", null); assertNotNull(list); assertEquals(2, list.size()); assertEquals("id1", list.get(0).getInstanceID()); assertEquals(myPhone, list.get(0).getDevice()); assertEquals("id2", list.get(1).getInstanceID()); assertEquals(currentDevice, list.get(1).getDevice()); }
@Test public void shouldRetrieveMultipleInstancesByDeviceName() throws DriverManagerException, DriverNotFoundException { UpDriver driver = new UpDriver("d1"); driver.addService("s1").addParameter("p1", ParameterType.MANDATORY); UpDriver driverD3 = new UpDriver("d3"); driverD3.addEvent("e1"); UpDevice myPhone = new UpDevice("my.Phone"); deviceManager.registerDevice(myPhone); driverManager.insert(new DriverModel("id1", driver, "my.Phone")); driverManager.insert(new DriverModel("id2", driver, currentDevice .getName())); driverManager.insert(new DriverModel("id3", driverD3, "my.Phone")); List<DriverData> list = driverManager.listDrivers(null, "my.Phone"); assertNotNull(list); assertEquals(2, list.size()); assertEquals("id1", list.get(0).getInstanceID()); assertEquals(myPhone, list.get(0).getDevice()); assertEquals(driver, list.get(0).getDriver()); assertEquals("id3", list.get(1).getInstanceID()); assertEquals(myPhone, list.get(1).getDevice()); assertEquals(driverD3, list.get(1).getDriver()); } |
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); Notify(String eventKey, String driver); Notify(String eventKey, String driver, String instanceId); String getEventKey(); void setEventKey(String eventKey); Map<String, Object> getParameters(); void setParameters(Map<String, Object> parameters); Notify addParameter(String key, String value); Notify addParameter(String key, Number value); Object getParameter(String key); @Override boolean equals(Object obj); @Override int hashCode(); String getDriver(); void setDriver(String driver); String getInstanceId(); void setInstanceId(String instanceId); JSONObject toJSON(); static Notify fromJSON(JSONObject json); @Override String toString(); } | @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"); Notify edid5 = new Notify("ex","d","id"); assertThat(e2.hashCode()).isEqualTo(e1.hashCode()); assertThat(ed1.hashCode()).isEqualTo(ed2.hashCode()); assertThat(edid1.hashCode()).isEqualTo(edid2.hashCode()); assertThat(edid1.hashCode()).isNotEqualTo(edid3.hashCode()); assertThat(edid1.hashCode()).isNotEqualTo(edid4.hashCode()); assertThat(edid1.hashCode()).isNotEqualTo(edid5.hashCode()); } |
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(String eventKey); Notify(String eventKey, String driver); Notify(String eventKey, String driver, String instanceId); String getEventKey(); void setEventKey(String eventKey); Map<String, Object> getParameters(); void setParameters(Map<String, Object> parameters); Notify addParameter(String key, String value); Notify addParameter(String key, Number value); Object getParameter(String key); @Override boolean equals(Object obj); @Override int hashCode(); String getDriver(); void setDriver(String driver); String getInstanceId(); void setInstanceId(String instanceId); JSONObject toJSON(); static Notify fromJSON(JSONObject json); @Override String toString(); } | @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(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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 throws no exception"); } catch( NullPointerException ex ) { } } |
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_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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 ex ) { } try { StringUtils.strip( "xxxx", null ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } assertEquals("xyz", StringUtils.strip("xyz", "")); assertEquals("xyz", StringUtils.strip(" xyz ", " ")); assertEquals("xyz", StringUtils.strip(" xyz", " ")); assertEquals("xyz\t", StringUtils.strip(" xyz\t", " ")); assertEquals("xyz\t", StringUtils.strip(" xyz\t ", " ")); assertEquals("xy z", StringUtils.strip(" xy z\t ", " \t")); assertEquals("xy z", StringUtils.strip(" xy z\t \t", " \t")); assertEquals("xy z", StringUtils.strip(" xy z\t \n", " \t\n")); }
@Test public void testStrip_StringBuilder_String() { System.out.println("strip"); try { StringUtils.strip( (StringBuilder)null, "" ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } try { StringUtils.strip( (StringBuilder)null, null ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } try { StringUtils.strip( new StringBuilder("xxxx"), null ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } assertEquals("xyz", StringUtils.strip( new StringBuilder("xyz"), "")); assertEquals("xyz", StringUtils.strip( new StringBuilder(" xyz "), " ")); assertEquals("xyz", StringUtils.strip( new StringBuilder(" xyz"), " ")); assertEquals("xyz\t", StringUtils.strip( new StringBuilder(" xyz\t"), " ")); assertEquals("xyz\t", StringUtils.strip( new StringBuilder(" xyz\t "), " ")); assertEquals("xy z", StringUtils.strip( new StringBuilder(" xy z\t "), " \t")); assertEquals("xy z", StringUtils.strip( new StringBuilder(" xy z\t \t"), " \t")); assertEquals("xy z", StringUtils.strip( new StringBuilder(" xy z\t \n"), " \t\n")); } |
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 strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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(testTextA),20); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA20, res); res = StringUtils.autoLineBreak(new StringBuilder(testTextA),30); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA30, res); res = StringUtils.autoLineBreak(new StringBuilder(testTextA),40); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA40, res); res = StringUtils.autoLineBreak(new StringBuilder(testTextA),50); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA50, res); res = StringUtils.autoLineBreak(new StringBuilder(testTextB),50); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextB50, res); res = StringUtils.autoLineBreak(new StringBuilder(testTextC),50); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextC50, res); }
@Test public void testAutoLineBreak_String_int() { System.out.println("autoLineBreak"); String res; res = StringUtils.autoLineBreak(testTextA,10); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA10, res); res = StringUtils.autoLineBreak(testTextA,20); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA20, res); res = StringUtils.autoLineBreak(testTextA,30); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA30, res); res = StringUtils.autoLineBreak(testTextA,40); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA40, res); res = StringUtils.autoLineBreak(testTextA,50); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextA50, res); res = StringUtils.autoLineBreak(testTextB,50); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextB50, res); res = StringUtils.autoLineBreak(testTextC,50); System.out.println("=== RES ===\n" + res + "\n============\n"); assertText(testTextC50, res); } |
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, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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 public void testFormatDouble_double() { System.out.println("formatDouble"); assertEquals(String.format("%.3f", 12.234), StringUtils.formatDouble(12.2340000) ); assertEquals(String.format("%.2f", 0.03), StringUtils.formatDouble(0.03) ); assertEquals("12", StringUtils.formatDouble(12.0000) ); } |
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_a_yes_value.equalsIgnoreCase("1")) { return true; } if (maybe_a_yes_value.equalsIgnoreCase("x")) { return true; } if (maybe_a_yes_value.equalsIgnoreCase("+")) { return true; } return false; } 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(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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")); assertFalse(StringUtils.isYes("hugo")); } |
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(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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 function"); } } } |
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') { lbCounter++; } } truncatedString = String.valueOf(arr, idx, (arr.length - idx)); return truncatedString; } 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(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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)); assertEquals(testTest, StringUtils.skipLeadingLines(testTest, -1)); assertEquals(testTest.substring(9), StringUtils.skipLeadingLines(testTest, 2)); assertEquals("", StringUtils.skipLeadingLines(testTest, 100)); } |
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 boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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"), " ", 4)); assertEquals(4, StringUtils.skip_char(new StringBuilder( "das ist ein Text"), " ", 3)); try { StringUtils.skip_char(null, null, 0); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } try { StringUtils.skip_char(new StringBuilder("x"), null, 0); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } try { StringUtils.skip_char(null, " ", 0); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } } |
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 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(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); } | @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 = instance.getProperties(); assertEquals(expResult, result); } } |
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(); assertEquals(expResult, result); } } |
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(); assertEquals(expResult, result); } } |
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(); assertEquals(expResult, result); } } |
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 create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; } | @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 = BaseHolidays.getEaster(year); assertEquals(dm, result); } for( int year = 1970; year < 2030; year++ ) { System.out.print("getEaster " + year + ": "); LocalDate result = BaseHolidays.getEaster(year); System.out.println(result); } } |
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 ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; } | @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 a prototype."); } |
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 ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; } | @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 prototype."); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.