method2testcases
stringlengths
118
6.63k
### Question: SlotKeySerDes { protected static int shardFromSlotKey(String s) { return Integer.parseInt(s.split(",", -1)[2]); } static SlotKey deserialize(String stateStr); String serialize(SlotKey slotKey); String serialize(Granularity gran, int slot, int shard); }### Answer: @Test public void testShardFromSlotKey() { int expectedShard = 1; int shard = SlotKeySerDes.shardFromSlotKey(SlotKey.of(Granularity.MIN_5, 10, expectedShard).toString()); Assert.assertEquals(expectedShard, shard); }
### Question: SimpleNumber implements Rollup { public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", value.intValue()); case LONG: return String.format("%d (long)", value.longValue()); case DOUBLE: return String.format("%s (double)", value.toString()); default: return super.toString(); } } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void toStringWithIntegerPrintsIntegerString() { SimpleNumber sn = new SimpleNumber(123); assertEquals("123 (int)", sn.toString()); } @Test public void toStringWithLongPrintsLongString() { SimpleNumber sn = new SimpleNumber(123L); assertEquals("123 (long)", sn.toString()); } @Test public void toStringWithDoublePrintsDoubleString() { SimpleNumber sn = new SimpleNumber(123.45d); assertEquals("123.45 (double)", sn.toString()); }
### Question: SimpleNumber implements Rollup { @Override public RollupType getRollupType() { return RollupType.NOT_A_ROLLUP; } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void rollupTypeIsNotTypical() { SimpleNumber sn = new SimpleNumber(123.45d); assertEquals(RollupType.NOT_A_ROLLUP, sn.getRollupType()); }
### Question: SimpleNumber implements Rollup { @Override public int hashCode() { return value.hashCode(); } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void hashCodeIsValuesHashCode() { Double value = 123.45d; SimpleNumber sn = new SimpleNumber(value); assertEquals(value.hashCode(), sn.hashCode()); }
### Question: SimpleNumber implements Rollup { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof SimpleNumber)) return false; SimpleNumber other = (SimpleNumber)obj; return other.value == this.value || other.value.equals(this.value); } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void equalsWithNullReturnsFalse() { SimpleNumber sn = new SimpleNumber(123.45d); assertFalse(sn.equals(null)); } @Test public void equalsWithOtherTypeReturnsFalse() { SimpleNumber sn = new SimpleNumber(123.45d); assertFalse(sn.equals(Double.valueOf(123.45d))); } @Test public void equalsWithSimpleNumberOfOtherTypeReturnsFalse() { SimpleNumber sn = new SimpleNumber(123); SimpleNumber other = new SimpleNumber(123L); assertFalse(sn.equals(other)); } @Test public void equalsWithSimpleNumberOfSameTypeReturnsTrue() { SimpleNumber sn = new SimpleNumber(123); SimpleNumber other = new SimpleNumber(123); assertTrue(sn.equals(other)); } @Test public void equalsWithSimpleNumberOfSameBoxedValueReturnsTrue() { Integer value = 123; SimpleNumber sn = new SimpleNumber(value); SimpleNumber other = new SimpleNumber(value); assertTrue(sn.equals(other)); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized boolean getActive() { return active; } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getActiveGetsActiveFlag() { assertEquals(true, service.getActive()); }
### Question: BluefloodTimerRollup implements Rollup, IBaseRollup { public static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB) { double totalCount = countA + countB; double totalTime = ((double)countA / countPerSecA) + ((double)countB / countPerSecB); return totalCount / totalTime; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); }### Answer: @Test public void testCountPerSecondCalculation() { Assert.assertEquals(7.5d, BluefloodTimerRollup.calculatePerSecond(150, 5d, 300, 10d)); }
### Question: BluefloodTimerRollup implements Rollup, IBaseRollup { public BluefloodTimerRollup withSampleCount(int sampleCount) { this.sampleCount = sampleCount; return this; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); }### Answer: @Test public void testNullVersusZero() throws IOException { final BluefloodTimerRollup timerWithData = new BluefloodTimerRollup() .withSampleCount(1); final BluefloodTimerRollup timerWithoutData = new BluefloodTimerRollup() .withSampleCount(0); Assert.assertNotSame(timerWithData, timerWithoutData); }
### Question: BluefloodTimerRollup implements Rollup, IBaseRollup { public static Number sum(Collection<Number> numbers) { long longSum = 0; double doubleSum = 0d; boolean useDouble = false; for (Number number : numbers) { if (useDouble || number instanceof Double || number instanceof Float) { if (!useDouble) { useDouble = true; doubleSum += longSum; } doubleSum += number.doubleValue(); } else if (number instanceof Long || number instanceof Integer) longSum += number.longValue(); } if (useDouble) return doubleSum; else return longSum; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); }### Answer: @Test public void testSum() { Assert.assertEquals(6L, BluefloodTimerRollup.sum(longs)); Assert.assertEquals(6.0d, BluefloodTimerRollup.sum(doubles)); Assert.assertEquals(6.0d, BluefloodTimerRollup.sum(mixed)); Assert.assertEquals(6.0d, BluefloodTimerRollup.sum(alsoMixed)); }
### Question: BluefloodTimerRollup implements Rollup, IBaseRollup { public static Number avg(Collection<Number> numbers) { Number sum = BluefloodTimerRollup.sum(numbers); if (sum instanceof Long || sum instanceof Integer) return (Long)sum / numbers.size(); else return (Double)sum / (double)numbers.size(); } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); }### Answer: @Test public void testAverage() { Assert.assertEquals(2L, BluefloodTimerRollup.avg(longs)); Assert.assertEquals(2.0d, BluefloodTimerRollup.avg(doubles)); Assert.assertEquals(2.0d, BluefloodTimerRollup.avg(mixed)); Assert.assertEquals(2.0d, BluefloodTimerRollup.avg(alsoMixed)); }
### Question: BluefloodTimerRollup implements Rollup, IBaseRollup { public static Number max(Collection<Number> numbers) { long longMax = numbers.iterator().next().longValue(); double doubleMax = numbers.iterator().next().doubleValue(); boolean useDouble = false; for (Number number : numbers) { if (useDouble || number instanceof Double || number instanceof Float) { if (!useDouble) { useDouble = true; doubleMax = Math.max(doubleMax, (double)longMax); } doubleMax = Math.max(doubleMax, number.doubleValue()); } else { longMax = Math.max(longMax, number.longValue()); } } if (useDouble) return doubleMax; else return longMax; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); }### Answer: @Test public void testMax() { Assert.assertEquals(3L, BluefloodTimerRollup.max(longs)); Assert.assertEquals(3.0d, BluefloodTimerRollup.max(doubles)); Assert.assertEquals(3.0d, BluefloodTimerRollup.max(mixed)); Assert.assertEquals(3.0d, BluefloodTimerRollup.max(alsoMixed)); }
### Question: Average extends AbstractRollupStat { public void add(Long input) { count++; final long longAvgUntilNow = toLong(); setLongValue(toLong() + ((input + longRemainder - longAvgUntilNow) / count)); longRemainder = (input + longRemainder - longAvgUntilNow) % count; } Average(); @SuppressWarnings("unused") // used by Jackson Average(long value); @SuppressWarnings("unused") // used by Jackson Average(double value); Average(int count, Object value); void add(Long input); void addBatch(Long input, long dataPoints); void add(Double input); void addBatch(Double input, long dataPoints); @Override byte getStatType(); }### Answer: @Test public void testLongAverage() { Average avg = new Average(); avg.add(2L); avg.add(4L); avg.add(4L); Assert.assertEquals(3L, avg.toLong()); } @Test public void testDoubleAverage() { Average avg = new Average(); avg.add(2.0D); avg.add(4.0D); avg.add(4.0D); Assert.assertEquals(3.3333333333333335D, avg.toDouble(), 0); Assert.assertEquals(3.3333333333333335D, avg.toDouble(), 0); }
### Question: RollupService implements Runnable, RollupServiceMBean { public Collection<Integer> getManagedShards() { return new TreeSet<Integer>(shardStateManager.getManagedShards()); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getManagedShardsGetsCollectionFromManager() { HashSet<Integer> managedShards = new HashSet<Integer>(); managedShards.add(0); managedShards.add(1); managedShards.add(2); doReturn(managedShards).when(shardStateManager).getManagedShards(); Collection<Integer> actual = service.getManagedShards(); assertEquals(managedShards.size(), actual.size()); assertTrue(actual.containsAll(managedShards)); verify(shardStateManager).getManagedShards(); verifyNoMoreInteractions(shardStateManager); }
### Question: BluefloodCounterRollup implements Rollup { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof BluefloodCounterRollup)) return false; BluefloodCounterRollup other = (BluefloodCounterRollup)obj; return this.getCount().equals(other.getCount()) && this.rate == other.rate && this.getSampleCount() == other.getSampleCount(); } BluefloodCounterRollup(); BluefloodCounterRollup withCount(Number count); BluefloodCounterRollup withRate(double rate); BluefloodCounterRollup withSampleCount(int sampleCount); Number getCount(); double getRate(); int getSampleCount(); @Override String toString(); @Override boolean equals(Object obj); static BluefloodCounterRollup buildRollupFromRawSamples(Points<SimpleNumber> input); static BluefloodCounterRollup buildRollupFromCounterRollups(Points<BluefloodCounterRollup> input); @Override Boolean hasData(); @Override RollupType getRollupType(); }### Answer: @Test public void equalsOtherNullReturnsFalse() { BluefloodCounterRollup rollup = new BluefloodCounterRollup(); assertFalse(rollup.equals(null)); } @Test public void equalsOtherNotRollupReturnsFalse() { BluefloodCounterRollup rollup = new BluefloodCounterRollup(); assertFalse(rollup.equals("")); }
### Question: BluefloodCounterRollup implements Rollup { public static BluefloodCounterRollup buildRollupFromRawSamples(Points<SimpleNumber> input) throws IOException { long minTime = Long.MAX_VALUE; long maxTime = Long.MIN_VALUE; BluefloodCounterRollup rollup = new BluefloodCounterRollup(); Number count = 0L; for (Points.Point<SimpleNumber> point : input.getPoints().values()) { count = sum(count, point.getData().getValue()); minTime = Math.min(minTime, point.getTimestamp()); maxTime = Math.max(maxTime, point.getTimestamp()); } double numSeconds = (double)(maxTime - minTime); double rate = count.doubleValue() / numSeconds; return rollup.withCount(count).withRate(rate).withSampleCount(input.getPoints().size()); } BluefloodCounterRollup(); BluefloodCounterRollup withCount(Number count); BluefloodCounterRollup withRate(double rate); BluefloodCounterRollup withSampleCount(int sampleCount); Number getCount(); double getRate(); int getSampleCount(); @Override String toString(); @Override boolean equals(Object obj); static BluefloodCounterRollup buildRollupFromRawSamples(Points<SimpleNumber> input); static BluefloodCounterRollup buildRollupFromCounterRollups(Points<BluefloodCounterRollup> input); @Override Boolean hasData(); @Override RollupType getRollupType(); }### Answer: @Test(expected = NullPointerException.class) public void rawSampleBuilderWithNullInputsThrowsException() throws IOException { BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromRawSamples(null); }
### Question: BluefloodCounterRollup implements Rollup { public static BluefloodCounterRollup buildRollupFromCounterRollups(Points<BluefloodCounterRollup> input) throws IOException { Number count = 0L; double seconds = 0; int sampleCount = 0; for (Points.Point<BluefloodCounterRollup> point : input.getPoints().values()) { count = sum(count, point.getData().getCount()); sampleCount = sampleCount + point.getData().getSampleCount(); seconds += Util.safeDiv(point.getData().getCount().doubleValue(), point.getData().getRate()); } double aggregateRate = Util.safeDiv(count.doubleValue(), seconds); return new BluefloodCounterRollup().withCount(count).withRate(aggregateRate).withSampleCount(sampleCount); } BluefloodCounterRollup(); BluefloodCounterRollup withCount(Number count); BluefloodCounterRollup withRate(double rate); BluefloodCounterRollup withSampleCount(int sampleCount); Number getCount(); double getRate(); int getSampleCount(); @Override String toString(); @Override boolean equals(Object obj); static BluefloodCounterRollup buildRollupFromRawSamples(Points<SimpleNumber> input); static BluefloodCounterRollup buildRollupFromCounterRollups(Points<BluefloodCounterRollup> input); @Override Boolean hasData(); @Override RollupType getRollupType(); }### Answer: @Test(expected = NullPointerException.class) public void counterRollupBuilderWithNullRollupInputThrowsException() throws IOException { Points<BluefloodCounterRollup> combined = new Points<BluefloodCounterRollup>(); combined.add(new Points.Point<BluefloodCounterRollup>(1234L, null)); BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromCounterRollups(combined); } @Test(expected = NullPointerException.class) public void counterRollupBuilderWithNullCombinedInputThrowsException() throws IOException { BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromCounterRollups(null); }
### Question: BluefloodCounterRollup implements Rollup { @Override public RollupType getRollupType() { return RollupType.COUNTER; } BluefloodCounterRollup(); BluefloodCounterRollup withCount(Number count); BluefloodCounterRollup withRate(double rate); BluefloodCounterRollup withSampleCount(int sampleCount); Number getCount(); double getRate(); int getSampleCount(); @Override String toString(); @Override boolean equals(Object obj); static BluefloodCounterRollup buildRollupFromRawSamples(Points<SimpleNumber> input); static BluefloodCounterRollup buildRollupFromCounterRollups(Points<BluefloodCounterRollup> input); @Override Boolean hasData(); @Override RollupType getRollupType(); }### Answer: @Test public void getRollupTypeReturnsCounter() { BluefloodCounterRollup rollup = new BluefloodCounterRollup(); assertEquals(RollupType.COUNTER, rollup.getRollupType()); }
### Question: Event { public Map<String, Object> toMap() { return new HashMap<String, Object>() { { put(FieldLabels.when.name(), getWhen()); put(FieldLabels.what.name(), getWhat()); put(FieldLabels.data.name(), getData()); put(FieldLabels.tags.name(), getTags()); } }; } Event(); @VisibleForTesting Event(long when, String what); Map<String, Object> toMap(); long getWhen(); void setWhen(long when); String getWhat(); void setWhat(String what); String getData(); void setData(String data); String getTags(); void setTags(String tags); static final String untilParameterName; static final String fromParameterName; static final String tagsParameterName; }### Answer: @Test public void testConvertToMap() { Map<String, Object> properties = event.toMap(); Assert.assertEquals(properties.get(Event.FieldLabels.when.name()), 1L); Assert.assertEquals(properties.get(Event.FieldLabels.data.name()), "2"); Assert.assertEquals(properties.get(Event.FieldLabels.tags.name()), "3"); Assert.assertEquals(properties.get(Event.FieldLabels.what.name()), "4"); }
### Question: ElasticTokensIO implements TokenDiscoveryIO { protected String[] getIndexesToSearch() { return new String[] {ELASTICSEARCH_TOKEN_INDEX_NAME_READ}; } ElasticTokensIO(); @Override void insertDiscovery(Token token); @Override void insertDiscovery(List<Token> tokens); @Override List<MetricName> getMetricNames(String tenantId, String query); static final String ES_DOCUMENT_TYPE; static String ELASTICSEARCH_TOKEN_INDEX_NAME_WRITE; static String ELASTICSEARCH_TOKEN_INDEX_NAME_READ; public ElasticsearchRestHelper elasticsearchRestHelper; }### Answer: @Test public void testGetIndexesToSearch() throws IOException { String[] indices = elasticTokensIO.getIndexesToSearch(); assertEquals(1, indices.length); assertEquals("metric_tokens", indices[0]); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized Collection<Integer> getRecentlyScheduledShards() { return context.getRecentlyScheduledShards(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getRecentlyScheduledShardsGetsFromContext() { Collection<Integer> recent = service.getRecentlyScheduledShards(); assertNotNull(recent); verify(context).getRecentlyScheduledShards(); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); }
### Question: MediaTypeChecker { public boolean isContentTypeValid(HttpHeaders headers) { String contentType = headers.get(HttpHeaders.Names.CONTENT_TYPE); return (Strings.isNullOrEmpty(contentType) || contentType.toLowerCase().contains(MEDIA_TYPE_APPLICATION_JSON)); } boolean isContentTypeValid(HttpHeaders headers); boolean isAcceptValid(HttpHeaders headers); }### Answer: @Test public void contentTypeEmptyShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn(""); assertTrue("empty content-type should be valid", mediaTypeChecker.isContentTypeValid(mockHeaders)); } @Test public void contentTypeJsonShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("application/json"); assertTrue("content-type application/json should be valid", mediaTypeChecker.isContentTypeValid(mockHeaders)); } @Test public void contentTypeJsonMixedCaseShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("aPpLiCaTiOn/JSON"); assertTrue("content-type aPpLiCaTiOn/JSON should be valid", mediaTypeChecker.isContentTypeValid(mockHeaders)); } @Test public void contentTypeJsonWithCharsetShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("application/json; charset=wtf-8"); assertTrue("content-type application/json should be valid", mediaTypeChecker.isContentTypeValid(mockHeaders)); } @Test public void contentTypePdfShouldBeInvalid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("application/pdf"); assertFalse("content-type application/pdf should be invalid", mediaTypeChecker.isContentTypeValid(mockHeaders)); }
### Question: MediaTypeChecker { public boolean isAcceptValid(HttpHeaders headers) { String accept = headers.get(HttpHeaders.Names.ACCEPT); return ( Strings.isNullOrEmpty(accept) || accept.contains(ACCEPT_ALL) || accept.toLowerCase().contains(MEDIA_TYPE_APPLICATION_JSON)); } boolean isContentTypeValid(HttpHeaders headers); boolean isAcceptValid(HttpHeaders headers); }### Answer: @Test public void acceptEmptyShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.ACCEPT)).thenReturn(""); assertTrue("empty accept should be valid", mediaTypeChecker.isAcceptValid(mockHeaders)); } @Test public void acceptAllShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.ACCEPT)).thenReturn("** should be valid", mediaTypeChecker.isAcceptValid(mockHeaders)); } @Test public void acceptJsonShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.ACCEPT)).thenReturn("application/json"); assertTrue("accept application/json should be valid", mediaTypeChecker.isAcceptValid(mockHeaders)); } @Test public void acceptAllWithCharsetQualityShouldBeValid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.ACCEPT)).thenReturn("text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8 should be valid", mediaTypeChecker.isAcceptValid(mockHeaders)); } @Test public void acceptXmlShouldBeInvalid() { HttpHeaders mockHeaders = mock(HttpHeaders.class); when(mockHeaders.get(HttpHeaders.Names.ACCEPT)).thenReturn("text/html,application/xhtml+xml,application/xml;q=0.9"); assertFalse("accept text/html,application/xhtml+xml,application/xml;q=0.9 should be invalid", mediaTypeChecker.isAcceptValid(mockHeaders)); }
### Question: HttpResponder { public void respond(ChannelHandlerContext ctx, FullHttpRequest req, HttpResponseStatus status) { respond(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, status)); } @VisibleForTesting HttpResponder(); @VisibleForTesting HttpResponder(int httpConnIdleTimeout); static HttpResponder getInstance(); void respond(ChannelHandlerContext ctx, FullHttpRequest req, HttpResponseStatus status); void respond(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res); }### Answer: @Test public void testDefaultHttpConnIdleTimeout_RequestKeepAlive_ShouldHaveResponseKeepAlive() { HttpResponder responder = new HttpResponder(); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); FullHttpRequest request = mock(FullHttpRequest.class); FullHttpResponse response = mock(FullHttpResponse.class); HttpHeaders headers = mock(HttpHeaders.class); Channel channel = mock(Channel.class); when(ctx.channel()).thenReturn(channel); when(request.content()).thenReturn(null); when(request.headers()).thenReturn(headers); when(headers.get(HttpHeaders.Names.CONNECTION)).thenReturn(HttpHeaders.Values.KEEP_ALIVE); when(request.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1); HttpHeaders responseHeaders = new DefaultHttpHeaders(); when(response.headers()).thenReturn(responseHeaders); responder.respond(ctx, request, response); assertEquals("Connection: response header", HttpHeaders.Values.KEEP_ALIVE, responseHeaders.get(HttpHeaders.Names.CONNECTION)); } @Test public void testNonZeroHttpConnIdleTimeout_RequestKeepAlive_ShouldHaveResponseKeepAliveTimeout() { int idleTimeout = 300; HttpResponder responder = new HttpResponder(idleTimeout); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); FullHttpRequest request = mock(FullHttpRequest.class); FullHttpResponse response = mock(FullHttpResponse.class); HttpHeaders headers = mock(HttpHeaders.class); Channel channel = mock(Channel.class); ChannelFuture future = mock(ChannelFuture.class); when(ctx.channel()).thenReturn(channel); when(ctx.writeAndFlush(any())).thenReturn(future); when(request.content()).thenReturn(null); when(request.headers()).thenReturn(headers); when(headers.get(HttpHeaders.Names.CONNECTION)).thenReturn(HttpHeaders.Values.KEEP_ALIVE); when(request.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1); HttpHeaders responseHeaders = new DefaultHttpHeaders(); when(response.headers()).thenReturn(responseHeaders); responder.respond(ctx, request, response); assertEquals("Connection: response header", HttpHeaders.Values.KEEP_ALIVE, responseHeaders.get(HttpHeaders.Names.CONNECTION)); assertEquals("Keep-Alive: response header", "timeout="+idleTimeout, responseHeaders.get("Keep-Alive")); }
### Question: RouteMatcher { public void get(String pattern, HttpRequestHandler handler) { addBinding(pattern, HttpMethod.GET.name(), handler, getBindings); } RouteMatcher(); RouteMatcher withNoRouteHandler(HttpRequestHandler noRouteHandler); void route(ChannelHandlerContext context, FullHttpRequest request); void get(String pattern, HttpRequestHandler handler); void put(String pattern, HttpRequestHandler handler); void post(String pattern, HttpRequestHandler handler); void delete(String pattern, HttpRequestHandler handler); void head(String pattern, HttpRequestHandler handler); void options(String pattern, HttpRequestHandler handler); void connect(String pattern, HttpRequestHandler handler); void patch(String pattern, HttpRequestHandler handler); Set<String> getSupportedMethodsForURL(String URL); }### Answer: @Test public void testValidRoutePatterns() throws Exception { FullHttpRequest modifiedReq = testPattern("/metrics/:metricId", "/metrics/foo"); Assert.assertTrue(testRouteHandlerCalled); Assert.assertEquals(1, modifiedReq.headers().names().size()); Assert.assertEquals("metricId", modifiedReq.headers().entries().get(0).getKey()); Assert.assertEquals("foo", modifiedReq.headers().entries().get(0).getValue()); testRouteHandlerCalled = false; modifiedReq = testPattern("/tenants/:tenantId/entities/:entityId", "/tenants/acFoo/entities/enBar"); Assert.assertTrue(testRouteHandlerCalled); Assert.assertEquals(2, modifiedReq.headers().names().size()); Assert.assertTrue(modifiedReq.headers().get("tenantId").equals("acFoo")); Assert.assertTrue(modifiedReq.headers().get("entityId").equals("enBar")); testRouteHandlerCalled = false; modifiedReq = testPattern("/tenants/:tenantId/entities/:entityId/checks/:checkId/metrics/:metricId/plot", "/tenants/acFoo/entities/enBar/checks/chFoo/metrics/myMetric/plot"); Assert.assertTrue(testRouteHandlerCalled); Assert.assertEquals(4, modifiedReq.headers().names().size()); Assert.assertTrue(modifiedReq.headers().get("tenantId").equals("acFoo")); Assert.assertTrue(modifiedReq.headers().get("entityId").equals("enBar")); Assert.assertTrue(modifiedReq.headers().get("entityId").equals("enBar")); Assert.assertTrue(modifiedReq.headers().get("checkId").equals("chFoo")); Assert.assertTrue(modifiedReq.headers().get("metricId").equals("myMetric")); testRouteHandlerCalled = false; modifiedReq = testPattern("/software/:name/:version", "/software/blueflood/v0.1"); Assert.assertTrue(testRouteHandlerCalled); Assert.assertEquals(2, modifiedReq.headers().names().size()); Assert.assertTrue(modifiedReq.headers().get("name").equals("blueflood")); Assert.assertTrue(modifiedReq.headers().get("version").equals("v0.1")); testRouteHandlerCalled = false; modifiedReq = testPattern("/software/:name/:version/", "/software/blueflood/v0.1/"); Assert.assertTrue(testRouteHandlerCalled); Assert.assertEquals(2, modifiedReq.headers().names().size()); Assert.assertTrue(modifiedReq.headers().get("name").equals("blueflood")); Assert.assertTrue(modifiedReq.headers().get("version").equals("v0.1")); testRouteHandlerCalled = false; modifiedReq = testPattern("/:name/:version","/blueflood/v0.1"); Assert.assertTrue(testRouteHandlerCalled); Assert.assertEquals(2, modifiedReq.headers().names().size()); Assert.assertTrue(modifiedReq.headers().get("name").equals("blueflood")); Assert.assertTrue(modifiedReq.headers().get("version").equals("v0.1")); testRouteHandlerCalled = false; }
### Question: HttpAggregatedMultiIngestionHandler implements HttpRequestHandler { public static List<AggregatedPayload> createBundleList(String json) { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(json); if (!element.isJsonArray()) { throw new InvalidDataException("Invalid request body"); } JsonArray jArray = element.getAsJsonArray(); ArrayList<AggregatedPayload> bundleList = new ArrayList<AggregatedPayload>(); for(JsonElement obj : jArray ) { AggregatedPayload bundle = AggregatedPayload.create(obj); bundleList.add(bundle); } return bundleList; } HttpAggregatedMultiIngestionHandler(HttpMetricsIngestionServer.Processor processor, TimeValue timeout); HttpAggregatedMultiIngestionHandler(HttpMetricsIngestionServer.Processor processor, TimeValue timeout, boolean enablePerTenantMetrics); @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); static List<AggregatedPayload> createBundleList(String json); }### Answer: @Test public void testEmptyButValidMultiJSON() { String badJson = "[]"; List<AggregatedPayload> bundle = HttpAggregatedMultiIngestionHandler.createBundleList(badJson); }
### Question: SlotStateSerDes { protected static Granularity granularityFromStateCol(String s) { String field = s.split(",", -1)[0]; for (Granularity g : Granularity.granularities()) if (g.name().startsWith(field)) return g; return null; } static SlotState deserialize(String stateStr); String serialize(SlotState state); String serialize(Granularity gran, int slot, UpdateStamp.State state); }### Answer: @Test public void testGranularityFromStateCol() { Granularity myGranularity = serDes.granularityFromStateCol("metrics_full,1,okay"); Assert.assertNotNull(myGranularity); Assert.assertEquals(myGranularity, Granularity.FULL); myGranularity = serDes.granularityFromStateCol("FULL"); Assert.assertNull(myGranularity); }
### Question: HttpMetricsIndexHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final String tenantId = request.headers().get("tenantId"); HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; List<String> query = requestWithParams.getQueryParams().get("query"); if (query == null || query.size() != 1) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid Query String", HttpResponseStatus.BAD_REQUEST); return; } discoveryHandle = (DiscoveryIO) ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); if (discoveryHandle == null) { sendResponse(ctx, request, null, HttpResponseStatus.NOT_FOUND); return; } try { List<SearchResult> searchResults = discoveryHandle.search(tenantId, query.get(0)); sendResponse(ctx, request, getSerializedJSON(searchResults), HttpResponseStatus.OK); } catch (Exception e) { log.error(String.format("Exception occurred while trying to get metrics index for %s", tenantId), e); DefaultHandler.sendErrorResponse(ctx, request, "Error getting metrics index", HttpResponseStatus.INTERNAL_SERVER_ERROR); } } @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); static String getSerializedJSON(List<SearchResult> searchResults); }### Answer: @Test public void testWithNoQueryParams() throws IOException { FullHttpRequest request = createQueryRequest(""); ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, request); verify(channel).write(argument.capture()); String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset()); ErrorResponse errorResponse = getErrorResponse(errorResponseBody); assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size()); assertEquals("Invalid error message", "Invalid Query String", errorResponse.getErrors().get(0).getMessage()); assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId()); assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus()); }
### Question: HttpMetricNamesHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final Timer.Context httpMetricNamesHandlerTimerContext = HttpMetricNamesHandlerTimer.time(); final String tenantId = request.headers().get("tenantId"); HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; List<String> query = requestWithParams.getQueryParams().get("query"); if (query == null || query.size() != 1) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid Query String", HttpResponseStatus.BAD_REQUEST); return; } if (discoveryHandle == null) { sendResponse(ctx, request, null, HttpResponseStatus.NOT_FOUND); return; } try { List<MetricName> metricNames = discoveryHandle.getMetricNames(tenantId, query.get(0)); sendResponse(ctx, request, getSerializedJSON(metricNames), HttpResponseStatus.OK); } catch (Exception e) { log.error(String.format("Exception occurred while trying to get metrics index for %s", tenantId), e); DefaultHandler.sendErrorResponse(ctx, request, "Error getting metrics index", HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpMetricNamesHandlerTimerContext.stop(); } } HttpMetricNamesHandler(); HttpMetricNamesHandler(DiscoveryIO discoveryHandle); @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); String getSerializedJSON(final List<MetricName> metricNames); static boolean EXP_TOKEN_SEARCH_IMPROVEMENTS; }### Answer: @Test public void emptyPrefix() throws Exception { ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, createGetRequest("/v2.0/" + TENANT + "/metric_name/search")); verify(channel).write(argument.capture()); verify(mockDiscoveryHandle, never()).getMetricNames(anyString(), anyString()); String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset()); ErrorResponse errorResponse = getErrorResponse(errorResponseBody); assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size()); assertEquals("Invalid error message", "Invalid Query String", errorResponse.getErrors().get(0).getMessage()); assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId()); assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus()); } @Test public void invalidQuerySize() throws Exception { ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, createGetRequest("/v2.0/" + TENANT + "/metric_name/search?query=foo&query=bar")); verify(channel).write(argument.capture()); verify(mockDiscoveryHandle, never()).getMetricNames(anyString(), anyString()); String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset()); ErrorResponse errorResponse = getErrorResponse(errorResponseBody); assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size()); assertEquals("Invalid error message", "Invalid Query String", errorResponse.getErrors().get(0).getMessage()); assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId()); assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus()); } @Test public void validQuery() throws Exception { handler.handle(context, createGetRequest("/v2.0/" + TENANT + "/metric_name/search?query=foo")); verify(mockDiscoveryHandle, times(1)).getMetricNames(anyString(), anyString()); }
### Question: HttpMetricNamesHandler implements HttpRequestHandler { public String getSerializedJSON(final List<MetricName> metricNames) { ArrayNode tokenInfoArrayNode = JsonNodeFactory.instance.arrayNode(); for (MetricName metricName : metricNames) { ObjectNode metricNameInfoNode = JsonNodeFactory.instance.objectNode(); metricNameInfoNode.put(metricName.getName(), JsonNodeFactory.instance.booleanNode(metricName.isCompleteName())); tokenInfoArrayNode.add(metricNameInfoNode); } return tokenInfoArrayNode.toString(); } HttpMetricNamesHandler(); HttpMetricNamesHandler(DiscoveryIO discoveryHandle); @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); String getSerializedJSON(final List<MetricName> metricNames); static boolean EXP_TOKEN_SEARCH_IMPROVEMENTS; }### Answer: @Test public void testOutput() throws ParseException { List<MetricName> inputMetricNames = new ArrayList<MetricName>() {{ add(new MetricName("foo", false)); add(new MetricName("bar", false)); }}; String output = handler.getSerializedJSON(inputMetricNames); JSONParser jsonParser = new JSONParser(); JSONArray tokenInfos = (JSONArray) jsonParser.parse(output); Assert.assertEquals("Unexpected result size", 2, tokenInfos.size()); Set<String> expectedOutputSet = new HashSet<String>(); for (MetricName metricName : inputMetricNames) { expectedOutputSet.add(metricName.getName() + "|" + metricName.isCompleteName()); } Set<String> outputSet = new HashSet<String>(); for (int i = 0; i< inputMetricNames.size(); i++) { JSONObject object = (JSONObject) tokenInfos.get(i); Iterator it = object.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); outputSet.add(entry.getKey() + "|" + entry.getValue()); } } Assert.assertEquals("Unexpected size", expectedOutputSet.size(), outputSet.size()); Assert.assertTrue("Output contains no more elements than expected", expectedOutputSet.containsAll(outputSet)); Assert.assertTrue("Output contains no less elements than expected", outputSet.containsAll(expectedOutputSet)); } @Test public void testEmptyOutput() throws ParseException { List<MetricName> inputMetricNames = new ArrayList<MetricName>(); String output = handler.getSerializedJSON(inputMetricNames); JSONParser jsonParser = new JSONParser(); JSONArray tokenInfos = (JSONArray) jsonParser.parse(output); Assert.assertEquals("Unexpected result size", 0, tokenInfos.size()); }
### Question: HttpEventsQueryHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final String tenantId = request.headers().get("tenantId"); ObjectMapper objectMapper = new ObjectMapper(); String responseBody = null; final Timer.Context httpEventsFetchTimerContext = httpEventsFetchTimer.time(); try { HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; Map<String, List<String>> params = requestWithParams.getQueryParams(); if (params == null || params.size() == 0) { throw new InvalidDataException("Query should contain at least one query parameter"); } parseDateFieldInQuery(params, "from"); parseDateFieldInQuery(params, "until"); List<Map<String, Object>> searchResult = searchIO.search(tenantId, params); responseBody = objectMapper.writeValueAsString(searchResult); DefaultHandler.sendResponse(ctx, request, responseBody, HttpResponseStatus.OK, null); } catch (InvalidDataException e) { log.error(String.format("Exception %s", e.toString())); responseBody = String.format("Error: %s", e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, responseBody, HttpResponseStatus.BAD_REQUEST); } catch (Exception e) { log.error(String.format("Exception %s", e.toString())); responseBody = String.format("Error: %s", e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, responseBody, HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpEventsFetchTimerContext.stop(); } } HttpEventsQueryHandler(EventsIO searchIO); @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); }### Answer: @Test public void testElasticSearchSearchNotCalledEmptyQuery() throws Exception { ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, createGetRequest("/v2.0/" + TENANT + "/events/")); verify(channel).write(argument.capture()); verify(searchIO, never()).search(TENANT, new HashMap<String, List<String>>()); String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset()); ErrorResponse errorResponse = getErrorResponse(errorResponseBody); assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size()); assertEquals("Invalid error message", "Error: Query should contain at least one query parameter", errorResponse.getErrors().get(0).getMessage()); assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId()); assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus()); }
### Question: BatchedMetricsJSONOutputSerializer extends JSONBasicRollupsOutputSerializer implements BatchedMetricsOutputSerializer<JSONObject> { @Override public JSONObject transformRollupData(Map<Locator, MetricData> metricData, Set<MetricStat> filterStats) throws SerializationException { final JSONObject globalJSON = new JSONObject(); final JSONArray metricsArray = new JSONArray(); for (Map.Entry<Locator, MetricData> one : metricData.entrySet()) { final JSONObject singleMetricJSON = new JSONObject(); singleMetricJSON.put("metric", one.getKey().getMetricName()); singleMetricJSON.put("unit", one.getValue().getUnit() == null ? Util.UNKNOWN : one.getValue().getUnit()); singleMetricJSON.put("type", one.getValue().getType()); Set<MetricStat> oneFilterStats = fixFilterStats(one.getValue(), filterStats); JSONArray values = transformDataToJSONArray(one.getValue(), oneFilterStats); singleMetricJSON.put("data", values); metricsArray.add(singleMetricJSON); } globalJSON.put("metrics", metricsArray); return globalJSON; } @Override JSONObject transformRollupData(Map<Locator, MetricData> metricData, Set<MetricStat> filterStats); }### Answer: @Test public void testBatchedMetricsSerialization() throws Exception { final BatchedMetricsJSONOutputSerializer serializer = new BatchedMetricsJSONOutputSerializer(); final Map<Locator, MetricData> metrics = new HashMap<Locator, MetricData>(); for (int i = 0; i < 2; i++) { final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeRollupPoints(), "unknown"); metrics.put(Locator.createLocatorFromPathComponents(tenantId, String.valueOf(i)), metricData); } JSONObject jsonMetrics = serializer.transformRollupData(metrics, filterStats); Assert.assertTrue(jsonMetrics.get("metrics") != null); JSONArray jsonMetricsArray = (JSONArray) jsonMetrics.get("metrics"); Iterator<JSONObject> metricsObjects = jsonMetricsArray.iterator(); Assert.assertTrue(metricsObjects.hasNext()); while (metricsObjects.hasNext()) { JSONObject singleMetricObject = metricsObjects.next(); Assert.assertTrue(singleMetricObject.get("unit").equals("unknown")); Assert.assertTrue(singleMetricObject.get("type").equals("number")); JSONArray data = (JSONArray) singleMetricObject.get("data"); Assert.assertTrue(data != null); } }
### Question: DateTimeParser { public static DateTime parse(String dateTimeOffsetString) { String stringToParse = dateTimeOffsetString.replace(" ", "").replace(",", "").replace("_", ""); if (StringUtils.isNumeric(stringToParse) && !isLikelyDateTime(stringToParse)) return dateTimeFromTimestamp(stringToParse); DateTime dateTime = tryParseDateTime("HH:mmyyyyMMdd", stringToParse); if (dateTime != null) return dateTime; List<String> splitList = splitDateTimeAndOffset(stringToParse); String offset = splitList.get(1); String dateTimeString = splitList.get(0); DateTimeOffsetParser parser = new DateTimeOffsetParser(dateTimeString, offset); return parser.updateDateTime(new DateTime()); } static DateTime parse(String dateTimeOffsetString); }### Answer: @Test public void testFromUnixTimestamp() { long unixTimestamp = nowDateTime().getMillis() / 1000; Assert.assertEquals(DateTimeParser.parse(Long.toString(unixTimestamp)), nowDateTime()); } @Test public void testPlainTimeDateFormat() { DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mmyyyyMMdd"); String dateTimeWithSpace = "10:55 2014 12 20"; String dateTimeWithUnderscore = "10:55_2014_12_20"; Assert.assertEquals(DateTimeParser.parse(dateTimeWithSpace), new DateTime(formatter.parseDateTime(dateTimeWithSpace.replace(" ", "")))); Assert.assertEquals(DateTimeParser.parse(dateTimeWithUnderscore), new DateTime(formatter.parseDateTime(dateTimeWithUnderscore.replace("_", "")))); } @Test public void testNowKeyword() { String nowTimestamp = "now"; Assert.assertEquals(DateTimeParser.parse(nowTimestamp), nowDateTime()); } @Test public void testRegularHourMinute() { String hourMinuteTimestamp = "12:24"; String hourMinuteWithAm = "9:13am"; String hourMinuteWithPm = "09:13pm"; Assert.assertEquals(DateTimeParser.parse(hourMinuteTimestamp), referenceDateTime().withHourOfDay(12).withMinuteOfHour(24)); Assert.assertEquals(DateTimeParser.parse(hourMinuteWithAm), referenceDateTime().withHourOfDay(9).withMinuteOfHour(13)); Assert.assertEquals(DateTimeParser.parse(hourMinuteWithPm), referenceDateTime().withHourOfDay(21).withMinuteOfHour(13)); } @Test public void testHourMinuteKeywords() { String noonTimestamp = "noon"; String teatimeTimestamp = "teatime"; String midnightTimestamp = "midnight"; Assert.assertEquals(DateTimeParser.parse(noonTimestamp), referenceDateTime().withHourOfDay(12).withMinuteOfHour(0)); Assert.assertEquals(DateTimeParser.parse(teatimeTimestamp), referenceDateTime().withHourOfDay(16).withMinuteOfHour(0)); Assert.assertEquals(DateTimeParser.parse(midnightTimestamp), referenceDateTime().withHourOfDay(0).withMinuteOfHour(0)); } @Test public void testDayKeywords() { String todayTimestamp = "today"; String yesterdayTimestamp = "yesterday"; String tomorrowTimeStamp = "tomorrow"; Assert.assertEquals(DateTimeParser.parse(todayTimestamp), referenceDateTime()); Assert.assertEquals(DateTimeParser.parse(yesterdayTimestamp), referenceDateTime().minusDays(1)); Assert.assertEquals(DateTimeParser.parse(tomorrowTimeStamp), referenceDateTime().plusDays(1)); } @Test public void testDayOfWeekFormat() { DateTime todayDate = referenceDateTime(); for (String dateTimeString: Arrays.asList("Fri", "14:42 Fri", "noon Fri")) { DateTime date = DateTimeParser.parse(dateTimeString); Assert.assertEquals(date.getDayOfWeek(), 5); Assert.assertTrue(todayDate.getDayOfYear() - date.getDayOfYear() <= 7); } }
### Question: Tracker implements TrackerMBean { public synchronized void register() { if (isRegistered) return; try { ObjectName objectName = new ObjectName(trackerName); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); if (!mBeanServer.isRegistered(objectName)) { ManagementFactory.getPlatformMBeanServer().registerMBean(instance, objectName); } isRegistered = true; log.info("MBean registered as " + trackerName); } catch (Exception exc) { log.error("Unable to register MBean " + trackerName, exc); } } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testRegister() { tracker.register(); verify(loggerMock, times(1)).info("MBean registered as com.rackspacecloud.blueflood.tracker:type=Tracker"); }
### Question: Tracker implements TrackerMBean { public void addTenant(String tenantId) { tenantIds.add(tenantId); log.info("[TRACKER] tenantId " + tenantId + " added."); } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testAddTenant() { tracker.addTenant(testTenant1); Set tenants = tracker.getTenants(); assertTrue( "tenant " + testTenant1 + " not added", tracker.isTracking( testTenant1 ) ); assertTrue( "tenants.size not 1", tenants.size() == 1 ); assertTrue( "tenants does not contain " + testTenant1, tenants.contains( testTenant1 ) ); }
### Question: Tracker implements TrackerMBean { public void removeTenant(String tenantId) { tenantIds.remove(tenantId); log.info("[TRACKER] tenantId " + tenantId + " removed."); } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testRemoveTenant() { tracker.addTenant(testTenant1); assertTrue( "tenant " + testTenant1 + " not added", tracker.isTracking( testTenant1 ) ); tracker.removeTenant(testTenant1); Set tenants = tracker.getTenants(); assertFalse( "tenant " + testTenant1 + " not removed", tracker.isTracking( testTenant1 ) ); assertEquals( "tenants.size not 0", tenants.size(), 0 ); assertFalse( "tenants contains " + testTenant1, tenants.contains( testTenant1 ) ); }
### Question: Tracker implements TrackerMBean { public void removeAllMetricNames() { metricNames.clear(); log.info("[TRACKER] All metric names removed."); } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testRemoveAllMetricNames() { tracker.addMetricName("metricName"); tracker.addMetricName("anotherMetricNom"); assertTrue("metricName not being logged",tracker.doesMessageContainMetricNames("Track.this.metricName")); assertTrue("anotherMetricNom not being logged",tracker.doesMessageContainMetricNames("Track.this.anotherMetricNom")); assertFalse("randomMetricNameNom should not be logged", tracker.doesMessageContainMetricNames("Track.this.randomMetricNameNom")); tracker.removeAllMetricNames(); assertTrue("Everything should be logged", tracker.doesMessageContainMetricNames("Track.this.metricName")); assertTrue("Everything should be logged", tracker.doesMessageContainMetricNames("Track.this.anotherMetricNom")); assertTrue("Everything should be logged", tracker.doesMessageContainMetricNames("Track.this.randomMetricNameNom")); }
### Question: Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testFindTidFound() { assertEquals( tracker.findTid( "/v2.0/6000/views" ), "6000" ); } @Test public void testTrackTenantNoVersion() { assertEquals( tracker.findTid( "/6000/views" ), null ); } @Test public void testTrackTenantBadVersion() { assertEquals( tracker.findTid( "blah/6000/views" ), null ); } @Test public void testTrackTenantTrailingSlash() { assertEquals( tracker.findTid( "/v2.0/6000/views/" ), "6000" ); }
### Question: Tracker implements TrackerMBean { public void setIsTrackingDelayedMetrics() { isTrackingDelayedMetrics = true; log.info("[TRACKER] Tracking delayed metrics started"); } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testSetIsTrackingDelayedMetrics() { tracker.resetIsTrackingDelayedMetrics(); tracker.setIsTrackingDelayedMetrics(); Assert.assertTrue("isTrackingDelayedMetrics should be true from setIsTrackingDelayedMetrics", tracker.getIsTrackingDelayedMetrics()); }
### Question: Tracker implements TrackerMBean { public void trackResponse(HttpRequest request, FullHttpResponse response) { if (request == null) return; if (response == null) return; String tenantId = findTid( request.getUri() ); if (isTracking(tenantId)) { HttpResponseStatus status = response.getStatus(); String messageBody = response.content().toString(Constants.DEFAULT_CHARSET); String queryParams = getQueryParameters(request); String headers = ""; for (String headerName : response.headers().names()) { headers += "\n" + headerName + "\t" + response.headers().get(headerName); } String responseContent = ""; if ((messageBody != null) && (!messageBody.isEmpty())) { responseContent = "\nRESPONSE_CONTENT:\n" + messageBody; } String logMessage = "[TRACKER] " + "Response for tenantId " + tenantId + " " + request.getMethod() + " request " + request.getUri() + queryParams + "\nRESPONSE_STATUS: " + status.code() + "\nRESPONSE HEADERS: " + headers + responseContent; log.info(logMessage); } } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testTrackResponse() throws Exception { String requestUri = "/v2.0/" + tenantId + "/metrics/search"; when(httpRequestMock.getUri()).thenReturn(requestUri); when(httpMethodMock.toString()).thenReturn("GET"); when(httpRequestMock.getMethod()).thenReturn(httpMethodMock); List<String> paramValues = new ArrayList<String>(); paramValues.add("locator1"); queryParams.put("query", paramValues); when((httpRequestMock).getQueryParams()).thenReturn(queryParams); when(httpResponseStatusMock.code()).thenReturn(200); when(httpResponseMock.getStatus()).thenReturn(httpResponseStatusMock); String result = "[TRACKER] Response for tenantId " + tenantId; when(httpResponseMock.content()).thenReturn(Unpooled.copiedBuffer(result.getBytes("UTF-8"))); tracker.addTenant(tenantId); tracker.trackResponse(httpRequestMock, httpResponseMock); verify(loggerMock, atLeastOnce()).info("[TRACKER] tenantId " + tenantId + " added."); verify(loggerMock, times(1)).info("[TRACKER] Response for tenantId " + tenantId + " GET request " + requestUri + "?query=locator1\n" + "RESPONSE_STATUS: 200\n" + "RESPONSE HEADERS: \n" + "RESPONSE_CONTENT:\n" + "[TRACKER] Response for tenantId " + tenantId); }
### Question: Tracker implements TrackerMBean { public void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics) { if (isTrackingDelayedMetrics) { String logMessage = String.format("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s", tenantid); log.info(logMessage); double delayedMinutes; long nowMillis = System.currentTimeMillis(); for (Metric metric : delayedMetrics) { delayedMinutes = (double)(nowMillis - metric.getCollectionTime()) / 1000 / 60; logMessage = String.format("[TRACKER][DELAYED METRIC] %s has collectionTime %s which is delayed by %.2f minutes", metric.getLocator().toString(), dateFormatter.format(new Date(metric.getCollectionTime())), delayedMinutes); log.info(logMessage); } } } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testTrackDelayedMetricsTenant() { tracker.setIsTrackingDelayedMetrics(); tracker.trackDelayedMetricsTenant(tenantId, delayedMetrics); verify(loggerMock, atLeastOnce()).info("[TRACKER] Tracking delayed metrics started"); verify(loggerMock, atLeastOnce()).info("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics " + tenantId); verify(loggerMock, atLeastOnce()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric1 has collectionTime 2016-01-01 00:00:00 which is delayed")); verify(loggerMock, atLeastOnce()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric2 has collectionTime 2016-01-01 00:00:00 which is delayed")); }
### Question: Tracker implements TrackerMBean { public void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames) { if (isTrackingDelayedMetrics) { String logMessage = String.format("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s", tenantId); log.info(logMessage); double delayMin = delayTimeMs / 1000 / 60; logMessage = String.format("[TRACKER][DELAYED METRIC] %s have collectionTime %s which is delayed by %.2f minutes", StringUtils.join(delayedMetricNames, ","), dateFormatter.format(new Date(collectionTimeMs)), delayMin); log.info(logMessage); } } private Tracker(); static Tracker getInstance(); synchronized void register(); void addTenant(String tenantId); void removeTenant(String tenantId); void removeAllTenants(); Set getTenants(); void addMetricName(String metricName); void removeMetricName(String metricName); void removeAllMetricNames(); Set<String> getMetricNames(); void setIsTrackingDelayedMetrics(); void resetIsTrackingDelayedMetrics(); boolean getIsTrackingDelayedMetrics(); boolean isTracking(String tenantId); boolean doesMessageContainMetricNames(String logmessage); void track(HttpRequest request); void trackResponse(HttpRequest request, FullHttpResponse response); void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics); void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames); static final String trackerName; }### Answer: @Test public void testTrackDelayedAggregatedMetricsTenant() { tracker.setIsTrackingDelayedMetrics(); List<String> delayedMetricNames = new ArrayList<String>() {{ for ( Metric metric : delayedMetrics ) { add(metric.getLocator().toString()); } }}; long ingestTime = System.currentTimeMillis(); tracker.trackDelayedAggregatedMetricsTenant(tenantId, delayedMetrics.get(0).getCollectionTime(), ingestTime, delayedMetricNames); verify(loggerMock, atLeastOnce()).info("[TRACKER] Tracking delayed metrics started"); verify(loggerMock, atLeastOnce()).info("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics " + tenantId); verify(loggerMock, atLeastOnce()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric1" + "," + tenantId + ".delayed.metric2 have collectionTime 2016-01-01 00:00:00 which is delayed")); }
### Question: RollupBatchWriter { public synchronized void drainBatch() { List<SingleRollupWriteContext> writeBasicContexts = new ArrayList<SingleRollupWriteContext>(); List<SingleRollupWriteContext> writePreAggrContexts = new ArrayList<SingleRollupWriteContext>(); try { for (int i=0; i<=ROLLUP_BATCH_MAX_SIZE; i++) { SingleRollupWriteContext context = rollupQueue.remove(); if ( context.getRollup().getRollupType() == RollupType.BF_BASIC ) { writeBasicContexts.add(context); } else { writePreAggrContexts.add(context); } } } catch (NoSuchElementException e) { } if (writeBasicContexts.size() > 0) { LOG.debug( String.format("drainBatch(): kicking off RollupBatchWriteRunnables for %d basic contexts", writeBasicContexts.size())); executor.execute(new RollupBatchWriteRunnable(writeBasicContexts, context, basicMetricsRW)); } if (writePreAggrContexts.size() > 0) { LOG.debug( String.format("drainBatch(): kicking off RollupBatchWriteRunnables for %d preAggr contexts", writePreAggrContexts.size())); executor.execute(new RollupBatchWriteRunnable(writePreAggrContexts, context, preAggregatedRW)); } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); }### Answer: @Test public void drainBatchWithNoItemsDoesNotTriggerBatching() { rbw.drainBatch(); verifyZeroInteractions(ctx); verifyZeroInteractions(executor); }
### Question: Configuration { private Configuration() { try { init(); } catch (IOException ex) { throw new RuntimeException(ex); } } private Configuration(); static Configuration getInstance(); void loadDefaults(ConfigDefaults[] configDefaults); void init(); Map<Object,Object> getProperties(); Map<Object, Object> getAllProperties(); String getStringProperty(Enum<? extends ConfigDefaults> name); String getStringProperty(String name); String getRawStringProperty(Enum<? extends ConfigDefaults> name); String getRawStringProperty(String name); boolean containsKey(String key); int getIntegerProperty(Enum<? extends ConfigDefaults> name); int getIntegerProperty(String name); static int intFromString(String value); float getFloatProperty(Enum<? extends ConfigDefaults> name); float getFloatProperty(String name); static float floatFromString(String value); long getLongProperty(Enum<? extends ConfigDefaults> name); long getLongProperty(String name); static long longFromString(String value); boolean getBooleanProperty(Enum<? extends ConfigDefaults> name); boolean getBooleanProperty(String name); static boolean booleanFromString(String value); List<String> getListProperty(Enum<? extends ConfigDefaults> name); List<String> getListProperty(String name); static List<String> stringListFromString(String value); void setProperty(String name, String val); void setProperty(Enum<? extends ConfigDefaults> name, String value); void clearProperty(String name); void clearProperty(Enum<? extends ConfigDefaults> name); }### Answer: @Test public void testConfiguration() { try { Configuration config = Configuration.getInstance(); Map<Object, Object> properties = config.getProperties(); Assert.assertNotNull(properties); Assert.assertEquals("127.0.0.1:19180", config.getStringProperty(CoreConfig.CASSANDRA_HOSTS)); System.setProperty("CASSANDRA_HOSTS", "127.0.0.2"); Assert.assertEquals("127.0.0.2", config.getStringProperty(CoreConfig.CASSANDRA_HOSTS)); Assert.assertEquals(60000, config.getIntegerProperty(CoreConfig.SCHEDULE_POLL_PERIOD)); } finally { System.clearProperty("CASSANDRA_HOSTS"); } }
### Question: Configuration { public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } private Configuration(); static Configuration getInstance(); void loadDefaults(ConfigDefaults[] configDefaults); void init(); Map<Object,Object> getProperties(); Map<Object, Object> getAllProperties(); String getStringProperty(Enum<? extends ConfigDefaults> name); String getStringProperty(String name); String getRawStringProperty(Enum<? extends ConfigDefaults> name); String getRawStringProperty(String name); boolean containsKey(String key); int getIntegerProperty(Enum<? extends ConfigDefaults> name); int getIntegerProperty(String name); static int intFromString(String value); float getFloatProperty(Enum<? extends ConfigDefaults> name); float getFloatProperty(String name); static float floatFromString(String value); long getLongProperty(Enum<? extends ConfigDefaults> name); long getLongProperty(String name); static long longFromString(String value); boolean getBooleanProperty(Enum<? extends ConfigDefaults> name); boolean getBooleanProperty(String name); static boolean booleanFromString(String value); List<String> getListProperty(Enum<? extends ConfigDefaults> name); List<String> getListProperty(String name); static List<String> stringListFromString(String value); void setProperty(String name, String val); void setProperty(Enum<? extends ConfigDefaults> name, String value); void clearProperty(String name); void clearProperty(Enum<? extends ConfigDefaults> name); }### Answer: @Test public void testMultipleCommaSeparatedItemsShouldYieldTheSameNumberOfElements() { String[] expected = { "a", "b", "c" }; List<String> actual = Configuration.stringListFromString("a,b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } @Test public void testWhitespaceBetweenElementsIsNotSignificant() { String[] expected = { "a", "b", "c" }; List<String> actual = Configuration.stringListFromString("a, b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } @Test public void testLeadingWhitespaceIsKept() { String[] expected = { " a", "b", "c" }; List<String> actual = Configuration.stringListFromString(" a,b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } @Test public void testTrailingWhitespaceIsKept() { String[] expected = { "a", "b", "c " }; List<String> actual = Configuration.stringListFromString("a,b,c "); Assert.assertArrayEquals(expected, actual.toArray()); } @Test public void testConsecutiveCommasDontProduceEmptyElements() { String[] expected = { "a", "b", "c" }; List<String> actual = Configuration.stringListFromString("a,,,b,c"); Assert.assertArrayEquals(expected, actual.toArray()); }
### Question: SlotStateSerDes { protected static int slotFromStateCol(String s) { return Integer.parseInt(s.split(",", -1)[1]); } static SlotState deserialize(String stateStr); String serialize(SlotState state); String serialize(Granularity gran, int slot, UpdateStamp.State state); }### Answer: @Test public void testSlotFromStateCol() { Assert.assertEquals(1, serDes.slotFromStateCol("metrics_full,1,okay")); }
### Question: Configuration { public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } private Configuration(); static Configuration getInstance(); void loadDefaults(ConfigDefaults[] configDefaults); void init(); Map<Object,Object> getProperties(); Map<Object, Object> getAllProperties(); String getStringProperty(Enum<? extends ConfigDefaults> name); String getStringProperty(String name); String getRawStringProperty(Enum<? extends ConfigDefaults> name); String getRawStringProperty(String name); boolean containsKey(String key); int getIntegerProperty(Enum<? extends ConfigDefaults> name); int getIntegerProperty(String name); static int intFromString(String value); float getFloatProperty(Enum<? extends ConfigDefaults> name); float getFloatProperty(String name); static float floatFromString(String value); long getLongProperty(Enum<? extends ConfigDefaults> name); long getLongProperty(String name); static long longFromString(String value); boolean getBooleanProperty(Enum<? extends ConfigDefaults> name); boolean getBooleanProperty(String name); static boolean booleanFromString(String value); List<String> getListProperty(Enum<? extends ConfigDefaults> name); List<String> getListProperty(String name); static List<String> stringListFromString(String value); void setProperty(String name, String val); void setProperty(Enum<? extends ConfigDefaults> name, String value); void clearProperty(String name); void clearProperty(Enum<? extends ConfigDefaults> name); }### Answer: @Test public void testNullShouldBeInterpretedAsBooleanFalse() { Assert.assertFalse(Configuration.booleanFromString(null)); } @Test public void test_TRUE_ShouldBeInterpretedAsBooleanTrue() { Assert.assertTrue(Configuration.booleanFromString("TRUE")); }
### Question: Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } private Configuration(); static Configuration getInstance(); void loadDefaults(ConfigDefaults[] configDefaults); void init(); Map<Object,Object> getProperties(); Map<Object, Object> getAllProperties(); String getStringProperty(Enum<? extends ConfigDefaults> name); String getStringProperty(String name); String getRawStringProperty(Enum<? extends ConfigDefaults> name); String getRawStringProperty(String name); boolean containsKey(String key); int getIntegerProperty(Enum<? extends ConfigDefaults> name); int getIntegerProperty(String name); static int intFromString(String value); float getFloatProperty(Enum<? extends ConfigDefaults> name); float getFloatProperty(String name); static float floatFromString(String value); long getLongProperty(Enum<? extends ConfigDefaults> name); long getLongProperty(String name); static long longFromString(String value); boolean getBooleanProperty(Enum<? extends ConfigDefaults> name); boolean getBooleanProperty(String name); static boolean booleanFromString(String value); List<String> getListProperty(Enum<? extends ConfigDefaults> name); List<String> getListProperty(String name); static List<String> stringListFromString(String value); void setProperty(String name, String val); void setProperty(Enum<? extends ConfigDefaults> name, String value); void clearProperty(String name); void clearProperty(Enum<? extends ConfigDefaults> name); }### Answer: @Test public void testIntegerOneShouldBeInterpretedAsOne() { Assert.assertEquals(1, Configuration.intFromString("1")); } @Test(expected=NumberFormatException.class) public void testIntegerLeadingWhitespaceShouldBeIgnored() { int value = Configuration.intFromString(" 1"); } @Test(expected=NumberFormatException.class) public void testIntegerTrailingWhitespaceShouldBeIgnored() { int value = Configuration.intFromString("1 "); }
### Question: Configuration { public static long longFromString(String value) { return Long.parseLong(value); } private Configuration(); static Configuration getInstance(); void loadDefaults(ConfigDefaults[] configDefaults); void init(); Map<Object,Object> getProperties(); Map<Object, Object> getAllProperties(); String getStringProperty(Enum<? extends ConfigDefaults> name); String getStringProperty(String name); String getRawStringProperty(Enum<? extends ConfigDefaults> name); String getRawStringProperty(String name); boolean containsKey(String key); int getIntegerProperty(Enum<? extends ConfigDefaults> name); int getIntegerProperty(String name); static int intFromString(String value); float getFloatProperty(Enum<? extends ConfigDefaults> name); float getFloatProperty(String name); static float floatFromString(String value); long getLongProperty(Enum<? extends ConfigDefaults> name); long getLongProperty(String name); static long longFromString(String value); boolean getBooleanProperty(Enum<? extends ConfigDefaults> name); boolean getBooleanProperty(String name); static boolean booleanFromString(String value); List<String> getListProperty(Enum<? extends ConfigDefaults> name); List<String> getListProperty(String name); static List<String> stringListFromString(String value); void setProperty(String name, String val); void setProperty(Enum<? extends ConfigDefaults> name, String value); void clearProperty(String name); void clearProperty(Enum<? extends ConfigDefaults> name); }### Answer: @Test public void testLongOneShouldBeInterpretedAsOne() { Assert.assertEquals(1L, Configuration.longFromString("1")); } @Test(expected=NumberFormatException.class) public void testLongLeadingWhitespaceShouldBeRejected() { long value = Configuration.longFromString(" 1"); } @Test(expected=NumberFormatException.class) public void testLongTrailingWhitespaceShouldBeRejected() { long value = Configuration.longFromString("1 "); }
### Question: Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); static Configuration getInstance(); void loadDefaults(ConfigDefaults[] configDefaults); void init(); Map<Object,Object> getProperties(); Map<Object, Object> getAllProperties(); String getStringProperty(Enum<? extends ConfigDefaults> name); String getStringProperty(String name); String getRawStringProperty(Enum<? extends ConfigDefaults> name); String getRawStringProperty(String name); boolean containsKey(String key); int getIntegerProperty(Enum<? extends ConfigDefaults> name); int getIntegerProperty(String name); static int intFromString(String value); float getFloatProperty(Enum<? extends ConfigDefaults> name); float getFloatProperty(String name); static float floatFromString(String value); long getLongProperty(Enum<? extends ConfigDefaults> name); long getLongProperty(String name); static long longFromString(String value); boolean getBooleanProperty(Enum<? extends ConfigDefaults> name); boolean getBooleanProperty(String name); static boolean booleanFromString(String value); List<String> getListProperty(Enum<? extends ConfigDefaults> name); List<String> getListProperty(String name); static List<String> stringListFromString(String value); void setProperty(String name, String val); void setProperty(Enum<? extends ConfigDefaults> name, String value); void clearProperty(String name); void clearProperty(Enum<? extends ConfigDefaults> name); }### Answer: @Test public void testFloatOneShouldBeInterpretedAsOne() { Assert.assertEquals(1.0f, Configuration.floatFromString("1"), 0.00001f); } @Test public void testFloatExtendedFormat() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1.1e3"), 0.00001f); } @Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceBeforeDotIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1 .1e3"), 0.00001f); } @Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceAfterDotIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1. 1e3"), 0.00001f); } @Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceBeforeExponentMarkerIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1.1 e3"), 0.00001f); } @Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceAfterExponentMarkerIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1.1e 3"), 0.00001f); } @Test public void testFloatLeadingWhitespaceShouldBeIgnored() { Assert.assertEquals(1.0f, Configuration.floatFromString(" 1"), 0.00001f); } @Test public void testFloatTrailingWhitespaceShouldBeIgnored() { Assert.assertEquals(1.0f, Configuration.floatFromString("1 "), 0.00001f); }
### Question: SlotStateSerDes { protected static String stateCodeFromStateCol(String s) { return s.split(",", -1)[2]; } static SlotState deserialize(String stateStr); String serialize(SlotState state); String serialize(Granularity gran, int slot, UpdateStamp.State state); }### Answer: @Test public void testStateFromStateCol() { Assert.assertEquals("okay", serDes.stateCodeFromStateCol("metrics_full,1,okay")); }
### Question: SlotState { public String toString() { return new StringBuilder().append(granularity == null ? "null" : granularity.name()) .append(",").append(slot) .append(",").append(state == null ? "null" : state.code()) .append(": ").append(getTimestamp() == null ? "" : getTimestamp()) .toString(); } SlotState(Granularity g, int slot, UpdateStamp.State state); SlotState(); SlotState withTimestamp(long timestamp); SlotState withLastUpdatedTimestamp(long lastUpdatedTimestamp); String toString(); boolean equals(Object other); Granularity getGranularity(); int getSlot(); UpdateStamp.State getState(); Long getTimestamp(); long getLastUpdatedTimestamp(); }### Answer: @Test public void testStringConversion() { Assert.assertEquals(s1 + ": ", ss1.toString()); Assert.assertEquals(s2 + ": " + time, ss2.toString()); Assert.assertEquals(s3 + ": " + time, ss3.toString()); }
### Question: SlotState { public SlotState withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } SlotState(Granularity g, int slot, UpdateStamp.State state); SlotState(); SlotState withTimestamp(long timestamp); SlotState withLastUpdatedTimestamp(long lastUpdatedTimestamp); String toString(); boolean equals(Object other); Granularity getGranularity(); int getSlot(); UpdateStamp.State getState(); Long getTimestamp(); long getLastUpdatedTimestamp(); }### Answer: @Test public void testEquality() { Assert.assertEquals(ss1, fromString(s1)); Assert.assertEquals(ss2, fromString(s2).withTimestamp(time)); Assert.assertEquals(new SlotState(Granularity.FULL, 1, UpdateStamp.State.Active), new SlotState(Granularity.FULL, 1, UpdateStamp.State.Running)); Assert.assertNotSame(new SlotState(Granularity.FULL, 1, UpdateStamp.State.Active), new SlotState(Granularity.FULL, 1, UpdateStamp.State.Rolled)); SlotState timestampedState = fromString(s1).withTimestamp(time); Assert.assertNotSame(timestampedState, fromString(s1)); }
### Question: SlotState { public Granularity getGranularity() { return granularity; } SlotState(Granularity g, int slot, UpdateStamp.State state); SlotState(); SlotState withTimestamp(long timestamp); SlotState withLastUpdatedTimestamp(long lastUpdatedTimestamp); String toString(); boolean equals(Object other); Granularity getGranularity(); int getSlot(); UpdateStamp.State getState(); Long getTimestamp(); long getLastUpdatedTimestamp(); }### Answer: @Test public void testGranularity() { Assert.assertEquals(Granularity.FULL, fromString(s1).getGranularity()); Assert.assertNull(fromString("FULL,1,X").getGranularity()); }
### Question: SlotStateSerDes { protected static UpdateStamp.State stateFromCode(String stateCode) { if (stateCode.equals(UpdateStamp.State.Rolled.code())) { return UpdateStamp.State.Rolled; } else { return UpdateStamp.State.Active; } } static SlotState deserialize(String stateStr); String serialize(SlotState state); String serialize(Granularity gran, int slot, UpdateStamp.State state); }### Answer: @Test public void testStateFromStateCode() { Assert.assertEquals(UpdateStamp.State.Active, serDes.stateFromCode("foo")); Assert.assertEquals(UpdateStamp.State.Active, serDes.stateFromCode("A")); Assert.assertEquals(UpdateStamp.State.Rolled, serDes.stateFromCode("X")); }
### Question: BluefloodServiceStarter { public static void validateCassandraHosts() { String hosts = Configuration.getInstance().getStringProperty(CoreConfig.CASSANDRA_HOSTS); if (!(hosts.length() >= 3)) { log.error("No cassandra hosts found in configuration option 'CASSANDRA_HOSTS'"); throw new BluefloodServiceStarterException(-1, "No cassandra hosts found in configuration option 'CASSANDRA_HOSTS'"); } for (String host : hosts.split(",")) { if (!host.matches("[\\d\\w\\.\\-_]+:\\d+")) { log.error("Invalid Cassandra host found in Configuration option 'CASSANDRA_HOSTS' -- Should be of the form <hostname>:<port>"); throw new BluefloodServiceStarterException(-1, "Invalid Cassandra host found in Configuration option 'CASSANDRA_HOSTS' -- Should be of the form <hostname>:<port>"); } } } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); }### Answer: @Test(expected = BluefloodServiceStarterException.class) public void testNoCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); BluefloodServiceStarter.validateCassandraHosts(); } @Test(expected = BluefloodServiceStarterException.class) public void testInvalidCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "something"); BluefloodServiceStarter.validateCassandraHosts(); } @Test(expected = BluefloodServiceStarterException.class) public void testCassandraHostWithoutPortFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "127.0.0.1"); BluefloodServiceStarter.validateCassandraHosts(); } @Test public void testCassandraHostWithHyphenSucceedsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "my-hostname:9160"); BluefloodServiceStarter.validateCassandraHosts(); } @Test public void testCassandraHostWithUnderscoreSucceedsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "my_hostname:9160"); BluefloodServiceStarter.validateCassandraHosts(); }
### Question: SearchResult { public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj == null) { return false; } else if (!getClass().equals(obj.getClass())) { return false; } return equals((SearchResult) obj); } SearchResult(String tenantId, String name, String unit); String getTenantId(); String getMetricName(); String getUnit(); @Override String toString(); @Override int hashCode(); boolean equals(Object obj); boolean equals(SearchResult other); }### Answer: @Test public void testEquals() { SearchResult result1 = new SearchResult(TENANT_ID, METRIC_NAME, null); SearchResult result2 = new SearchResult(TENANT_ID, METRIC_NAME, null); Assert.assertTrue("result1 should equal self", result1.equals(result1)); Assert.assertTrue("result1 should equal result2", result1.equals(result2)); Assert.assertTrue("result1 should not equal null", !result1.equals(null)); String METRIC_NAME2 = "metric2"; SearchResult result3 = new SearchResult(TENANT_ID, METRIC_NAME2, UNIT); SearchResult result4 = new SearchResult(TENANT_ID, METRIC_NAME2, UNIT); Assert.assertTrue("result3 should equal result4", result3.equals(result4)); Assert.assertTrue("result1 should not equal result3", !result1.equals(result3)); }
### Question: RollupBatchWriteRunnable implements Runnable { @Override public void run() { Timer.Context ctx = batchWriteTimer.time(); try { metricsRW.insertRollups(writeContexts); } catch (Exception e) { LOG.warn("not able to insert rollups", e); executionContext.markUnsuccessful(e); } finally { executionContext.decrementWriteCounter(writeContexts.size()); rollupsPerBatch.update(writeContexts.size()); rollupsWriteRate.mark(writeContexts.size()); RollupService.lastRollupTime.set(System.currentTimeMillis()); ctx.stop(); } } RollupBatchWriteRunnable(List<SingleRollupWriteContext> writeContexts, RollupExecutionContext executionContext, AbstractMetricsRW metricsRW); @Override void run(); }### Answer: @Test public void runSendsRollupsToWriterAndDecrementsCount() throws Exception { final AtomicLong decrementCount = new AtomicLong(0); Answer contextAnswer = new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { decrementCount.set((Long)invocation.getArguments()[0]); return null; } }; doAnswer(contextAnswer).when(ctx).decrementWriteCounter(anyLong()); final Object[] insertRollupsArg = new Object[1]; Answer writerAnswer = new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { insertRollupsArg[0] = invocation.getArguments()[0]; return null; } }; doAnswer(writerAnswer).when(writer).insertRollups( Matchers.<ArrayList<SingleRollupWriteContext>>any()); rbwr.run(); verify(writer).insertRollups(Matchers.<ArrayList<SingleRollupWriteContext>>any()); assertSame(wcs, insertRollupsArg[0]); verifyNoMoreInteractions(writer); verify(ctx).decrementWriteCounter(anyLong()); assertEquals(wcs.size(), decrementCount.get()); verifyNoMoreInteractions(ctx); } @Test public void connectionExceptionMarksUnsuccessful() throws Exception { Throwable cause = new IOException("exception for testing purposes") { }; doThrow(cause).when(writer).insertRollups( Matchers.<ArrayList<SingleRollupWriteContext>>any()); rbwr.run(); verify(writer).insertRollups(Matchers.<ArrayList<SingleRollupWriteContext>>any()); verifyNoMoreInteractions(writer); verify(ctx).markUnsuccessful(Matchers.<Throwable>any()); verify(ctx).decrementWriteCounter(anyLong()); verifyNoMoreInteractions(ctx); }
### Question: RetryNTimes implements RetryPolicy { @Override public RetryDecision onReadTimeout(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataReceived, int rTime) { if (dataReceived) { return RetryDecision.ignore(); } else if (rTime < readAttempts) { LOG.info(String.format("Retrying on ReadTimeout: stmnt %s, " + "consistency %s, requiredResponse %d, " + "receivedResponse %d, dataReceived %s, rTime %d", stmnt, cl, requiredResponses, receivedResponses, dataReceived, rTime)); return RetryDecision.retry(cl); } else { return RetryDecision.rethrow(); } } RetryNTimes(int readAttempts, int writeAttempts, int unavailableAttempts); @Override RetryDecision onReadTimeout(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataReceived, int rTime); @Override RetryDecision onWriteTimeout(Statement stmnt, ConsistencyLevel cl, WriteType wt, int requiredResponses, int receivedResponses, int wTime); @Override RetryDecision onUnavailable(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, int uTime); @Override RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry); @Override void init(Cluster cluster); @Override void close(); }### Answer: @Test public void firstTimeRetryOnReadTimeout_shouldRetry() throws Exception { RetryNTimes retryPolicy = new RetryNTimes(3, 3, 3); Statement mockStatement = mock( Statement.class ); RetryPolicy.RetryDecision retryResult = retryPolicy.onReadTimeout(mockStatement, ConsistencyLevel.LOCAL_ONE, 1, 0, false, 0); RetryPolicy.RetryDecision retryExpected = RetryPolicy.RetryDecision.retry(ConsistencyLevel.LOCAL_ONE); assertRetryDecisionEquals(retryExpected, retryResult); } @Test public void maxTimeRetryOnReadTimeout_shouldRethrow() throws Exception { RetryNTimes retryPolicy = new RetryNTimes(3, 3, 3); Statement mockStatement = mock( Statement.class ); RetryPolicy.RetryDecision retryResult = retryPolicy.onReadTimeout(mockStatement, ConsistencyLevel.LOCAL_ONE, 1, 0, false, 3); RetryPolicy.RetryDecision retryExpected = RetryPolicy.RetryDecision.rethrow(); assertRetryDecisionEquals(retryExpected, retryResult); }
### Question: LocatorFetchRunnable implements Runnable { public void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { executionContext.incrementReadCounter(); final SingleRollupReadContext singleRollupReadContext = new SingleRollupReadContext(locator, parentRange, getGranularity()); RollupRunnable rollupRunnable = new RollupRunnable(executionContext, singleRollupReadContext, rollupBatchWriter); rollupReadExecutor.execute(rollupRunnable); } LocatorFetchRunnable(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); @VisibleForTesting void initialize(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); void run(); void drainExecutionContext(long waitStart, int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter); void finishExecution(long waitStart, RollupExecutionContext executionContext); int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); Set<Locator> getDelayedLocators(RollupExecutionContext executionContext, SlotKey slotkey); Set<Locator> getLocators(RollupExecutionContext executionContext); }### Answer: @Test public void executeRollupForLocatorTriggersExecutionOfRollupRunnable() { lfr.executeRollupForLocator(executionContext, rollupBatchWriter, locators.get(0)); verify(rollupReadExecutor, times(1)).execute(Matchers.<RollupRunnable>any()); verifyNoMoreInteractions(rollupReadExecutor); verify(executionContext, times(1)).incrementReadCounter(); verifyNoMoreInteractions(executionContext); verifyZeroInteractions(rollupBatchWriter); }
### Question: LocatorFetchRunnable implements Runnable { public int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { if (log.isTraceEnabled()) log.trace("Rolling up (check,metric,dimension) {} for (gran,slot,shard) {}", locator, parentSlotKey); try { executeRollupForLocator(executionContext, rollupBatchWriter, locator); rollCount += 1; } catch (Throwable any) { executionContext.markUnsuccessful(any); executionContext.decrementReadCounter(); log.error(String.format( "BasicRollup failed for %s, locator %s, at %d", parentSlotKey, locator, serverTime), any); } return rollCount; } LocatorFetchRunnable(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); @VisibleForTesting void initialize(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); void run(); void drainExecutionContext(long waitStart, int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter); void finishExecution(long waitStart, RollupExecutionContext executionContext); int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); Set<Locator> getDelayedLocators(RollupExecutionContext executionContext, SlotKey slotkey); Set<Locator> getLocators(RollupExecutionContext executionContext); }### Answer: @Test public void processLocatorTriggersRunnable() { int count = lfr.processLocator(0, executionContext, rollupBatchWriter, locators.get(0)); Assert.assertEquals(1, count); verify(executionContext, never()).markUnsuccessful(Matchers.<Throwable>any()); verify(executionContext, never()).decrementReadCounter(); } @Test public void processLocatorIncrementsCount() { int count = lfr.processLocator(1, executionContext, rollupBatchWriter, locators.get(0)); Assert.assertEquals(2, count); verify(executionContext, never()).markUnsuccessful(Matchers.<Throwable>any()); verify(executionContext, never()).decrementReadCounter(); } @Test public void processLocatorExceptionCausesRollupToFail() { Throwable cause = new UnsupportedOperationException("exception for testing purposes"); doThrow(cause).when(rollupReadExecutor).execute(Matchers.<Runnable>any()); int count = lfr.processLocator(0, executionContext, rollupBatchWriter, locators.get(0)); Assert.assertEquals(0, count); verify(executionContext, times(1)).markUnsuccessful(Matchers.<Throwable>any()); verify(executionContext, times(1)).decrementReadCounter(); }
### Question: LocatorFetchRunnable implements Runnable { public void finishExecution(long waitStart, RollupExecutionContext executionContext) { if (executionContext.wasSuccessful()) { this.scheduleCtx.clearFromRunning(parentSlotKey); log.info("Successful completion of rollups for (gran,slot,shard) {} in {} ms", new Object[]{parentSlotKey, System.currentTimeMillis() - waitStart}); } else { log.error("Performing BasicRollups for {} failed", parentSlotKey); this.scheduleCtx.pushBackToScheduled(parentSlotKey, false); } } LocatorFetchRunnable(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); @VisibleForTesting void initialize(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); void run(); void drainExecutionContext(long waitStart, int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter); void finishExecution(long waitStart, RollupExecutionContext executionContext); int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); Set<Locator> getDelayedLocators(RollupExecutionContext executionContext, SlotKey slotkey); Set<Locator> getLocators(RollupExecutionContext executionContext); }### Answer: @Test public void finishExecutionWhenSuccessful() { when(executionContext.wasSuccessful()).thenReturn(true); lfr.finishExecution(0, executionContext); verify(executionContext, times(1)).wasSuccessful(); verifyNoMoreInteractions(executionContext); verify(scheduleCtx, times(1)).clearFromRunning(Matchers.<SlotKey>any()); verify(scheduleCtx).getCurrentTimeMillis(); verifyNoMoreInteractions(scheduleCtx); } @Test public void finishExecutionWhenNotSuccessful() { when(executionContext.wasSuccessful()).thenReturn(false); lfr.finishExecution(0, executionContext); verify(executionContext, times(1)).wasSuccessful(); verifyNoMoreInteractions(executionContext); verify(scheduleCtx, times(1)).pushBackToScheduled(Matchers.<SlotKey>any(), eq(false)); verify(scheduleCtx).getCurrentTimeMillis(); verifyNoMoreInteractions(scheduleCtx); }
### Question: LocatorFetchRunnable implements Runnable { protected RollupExecutionContext createRollupExecutionContext() { return new RollupExecutionContext(Thread.currentThread()); } LocatorFetchRunnable(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); @VisibleForTesting void initialize(ScheduleContext scheduleCtx, SlotKey destSlotKey, ExecutorService rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor); void run(); void drainExecutionContext(long waitStart, int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter); void finishExecution(long waitStart, RollupExecutionContext executionContext); int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); Set<Locator> getDelayedLocators(RollupExecutionContext executionContext, SlotKey slotkey); Set<Locator> getLocators(RollupExecutionContext executionContext); }### Answer: @Test public void createRollupExecutionContextReturnsValidObject() { RollupExecutionContext execCtx = lfr.createRollupExecutionContext(); assertNotNull(execCtx); }
### Question: MavenRepositories { public static List<RemoteRepository> getRemoteRepositories(MavenContainer container, Settings settings) { Set<RemoteRepository> remoteRepos = new HashSet<>(); remoteRepos.addAll(container.getEnabledRepositoriesFromProfile(settings)); String centralRepoURL = getCentralMirrorURL(settings).orElse(MAVEN_CENTRAL_REPO); remoteRepos.add(convertToMavenRepo("central", centralRepoURL, settings)); return new ArrayList<>(remoteRepos); } static List<RemoteRepository> getRemoteRepositories(MavenContainer container, Settings settings); }### Answer: @Test public void testMirrorCentralWithoutProfiles() throws Exception { SettingsBuilder settingsBuilder = new DefaultSettingsBuilderFactory().newInstance(); SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest(); settingsRequest.setUserSettingsFile(new File("src/test/resources/profiles/mirror-settings.xml")); Settings settings = settingsBuilder.build(settingsRequest).getEffectiveSettings(); MavenContainer container = new MavenContainer(); List<RemoteRepository> remoteRepositories = MavenRepositories.getRemoteRepositories(container, settings); Assert.assertThat(remoteRepositories.size(), equalTo(1)); Assert.assertThat(remoteRepositories.get(0).getId(), equalTo("central")); Assert.assertThat(remoteRepositories.get(0).getUrl(), equalTo("http: } @Test public void testCentralWithProfiles() throws Exception { SettingsBuilder settingsBuilder = new DefaultSettingsBuilderFactory().newInstance(); SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest(); settingsRequest.setUserSettingsFile(new File("src/test/resources/profiles/settings.xml")); Settings settings = settingsBuilder.build(settingsRequest).getEffectiveSettings(); MavenContainer container = new MavenContainer(); List<RemoteRepository> remoteRepositories = MavenRepositories.getRemoteRepositories(container, settings); Assert.assertEquals(2, remoteRepositories.size()); Assert.assertEquals("test-repository", remoteRepositories.get(1).getId()); List<RemoteRepository> centralRepos = remoteRepositories.stream().filter(repo -> repo.getId().equals("central")).collect(Collectors.toList()); Assert.assertEquals(1, centralRepos.size()); Assert.assertEquals(MavenRepositories.MAVEN_CENTRAL_REPO, centralRepos.get(0).getUrl()); }
### Question: Versions { public static VersionRange parseVersionRange(String range) throws VersionException { Assert.notNull(range, "Version range must not be null."); boolean lowerBoundInclusive = range.startsWith("["); boolean upperBoundInclusive = range.endsWith("]"); String process = range.substring(1, range.length() - 1).trim(); VersionRange result; int index = process.indexOf(","); if (index < 0) { if (!lowerBoundInclusive || !upperBoundInclusive) { throw new VersionException("Single version must be surrounded by []: " + range); } Version version = SingleVersion.valueOf(process); result = new DefaultVersionRange(version, lowerBoundInclusive, version, upperBoundInclusive); } else { String lowerBound = process.substring(0, index).trim(); String upperBound = process.substring(index + 1).trim(); if (lowerBound.equals(upperBound)) { throw new VersionException("Range cannot have identical boundaries: " + range); } Version lowerVersion = null; if (lowerBound.length() > 0) { lowerVersion = SingleVersion.valueOf(lowerBound); } Version upperVersion = null; if (upperBound.length() > 0) { upperVersion = SingleVersion.valueOf(upperBound); } if (upperVersion != null && lowerVersion != null && upperVersion.compareTo(lowerVersion) < 0) { throw new VersionException("Range defies version ordering: " + range); } result = new DefaultVersionRange(lowerVersion, lowerBoundInclusive, upperVersion, upperBoundInclusive); } return result; } static boolean isApiCompatible(Version runtimeVersion, Version addonApiVersion); static VersionRange parseVersionRange(String range); static MultipleVersionRange parseMultipleVersionRange(String intersection); static VersionRange intersection(VersionRange... ranges); static VersionRange intersection(Collection<VersionRange> ranges); static boolean isSnapshot(Version version); static Version getSpecificationVersionFor(Class<?> type); static Version getImplementationVersionFor(Class<?> type); }### Answer: @Test public void testVersionRangeSame() throws Exception { VersionRange range = Versions.parseVersionRange("[7]"); Assert.assertEquals(SingleVersion.valueOf("7"), range.getMin()); Assert.assertEquals(SingleVersion.valueOf("7"), range.getMax()); Assert.assertEquals("[7]", range.toString()); } @Test public void testParseVersionRange() throws Exception { VersionRange range = Versions.parseVersionRange("[0,15]"); Assert.assertEquals(SingleVersion.valueOf("0"), range.getMin()); Assert.assertEquals(SingleVersion.valueOf("15"), range.getMax()); Assert.assertTrue(range.isMinInclusive()); Assert.assertTrue(range.isMaxInclusive()); }
### Question: Versions { public static boolean isSnapshot(Version version) { Assert.notNull(version, "Version must not be null."); return version.toString().endsWith(SNAPSHOT_SUFFIX); } static boolean isApiCompatible(Version runtimeVersion, Version addonApiVersion); static VersionRange parseVersionRange(String range); static MultipleVersionRange parseMultipleVersionRange(String intersection); static VersionRange intersection(VersionRange... ranges); static VersionRange intersection(Collection<VersionRange> ranges); static boolean isSnapshot(Version version); static Version getSpecificationVersionFor(Class<?> type); static Version getImplementationVersionFor(Class<?> type); }### Answer: @Test public void testVersionSnapshot() throws Exception { Version nonSnapshot = SingleVersion.valueOf("1.1.1"); Assert.assertFalse(Versions.isSnapshot(nonSnapshot)); Version snapshot = SingleVersion.valueOf("1.1.1-SNAPSHOT"); Assert.assertTrue(Versions.isSnapshot(snapshot)); }
### Question: Versions { public static boolean isApiCompatible(Version runtimeVersion, Version addonApiVersion) { if (addonApiVersion == null || addonApiVersion.toString().length() == 0 || runtimeVersion == null || runtimeVersion.toString().length() == 0) return true; int runtimeMajorVersion = runtimeVersion.getMajorVersion(); int runtimeMinorVersion = runtimeVersion.getMinorVersion(); int addonApiMajorVersion = addonApiVersion.getMajorVersion(); int addonApiMinorVersion = addonApiVersion.getMinorVersion(); return (addonApiMajorVersion == runtimeMajorVersion && addonApiMinorVersion <= runtimeMinorVersion); } static boolean isApiCompatible(Version runtimeVersion, Version addonApiVersion); static VersionRange parseVersionRange(String range); static MultipleVersionRange parseMultipleVersionRange(String intersection); static VersionRange intersection(VersionRange... ranges); static VersionRange intersection(Collection<VersionRange> ranges); static boolean isSnapshot(Version version); static Version getSpecificationVersionFor(Class<?> type); static Version getImplementationVersionFor(Class<?> type); }### Answer: @Test public void testIsApiCompatible0() throws Exception { Assert.assertTrue(Versions.isApiCompatible( SingleVersion.valueOf("2.18.2-SNAPSHOT"), SingleVersion.valueOf("2.16.1.Final"))); } @Test public void testIsApiCompatible1() throws Exception { Assert.assertTrue(Versions.isApiCompatible( SingleVersion.valueOf("2.18.2.Final"), SingleVersion.valueOf("2.16.1.Final"))); }
### Question: SingleVersion implements Version { public static final SingleVersion valueOf(String version) { SingleVersion singleVersion = CACHE.get(version); if (singleVersion == null) { singleVersion = new SingleVersion(version); CACHE.put(version, singleVersion); } return singleVersion; } @Deprecated SingleVersion(String version); static final SingleVersion valueOf(String version); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version otherVersion); @Override int getMajorVersion(); @Override int getMinorVersion(); @Override int getIncrementalVersion(); @Override int getBuildNumber(); @Override String getQualifier(); @Override String toString(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testVersionMustNotBeNull() { SingleVersion.valueOf(null); }
### Question: Arrays { public static <ELEMENTTYPE> ELEMENTTYPE[] removeElementAtIndex(ELEMENTTYPE[] array, int index) { Assert.isTrue(array.length > 0, "Cannot remove an element from an already empty array."); ELEMENTTYPE[] result = java.util.Arrays.copyOf(array, array.length - 1); if (result.length > 0 && array.length + 1 != index && index != result.length) System.arraycopy(array, index + 1, result, index, array.length - (array.length - index)); return result; } @SafeVarargs static ELEMENTTYPE[] append(ELEMENTTYPE[] array, ELEMENTTYPE... elements); @SafeVarargs static ELEMENTTYPE[] prepend(ELEMENTTYPE[] array, ELEMENTTYPE... elements); static ELEMENTTYPE[] copy(ELEMENTTYPE[] source, ELEMENTTYPE[] target); static ELEMENTTYPE[] shiftLeft(ELEMENTTYPE[] source, ELEMENTTYPE[] target); static boolean contains(ELEMENTTYPE[] array, ELEMENTTYPE value); static int indexOf(ELEMENTTYPE[] array, ELEMENTTYPE value); static ELEMENTTYPE[] removeElementAtIndex(ELEMENTTYPE[] array, int index); }### Answer: @Test public void testSingleValue() { String[] data = new String[] { "a" }; int index = 0; String[] result = Arrays.removeElementAtIndex(data, index); Assert.assertEquals(1, data.length); Assert.assertEquals(0, result.length); } @Test public void testRemoveElementAtIndex() { String[] data = new String[] { "a", "b", "c", "d", "e" }; int index = 2; String[] result = Arrays.removeElementAtIndex(data, index); Assert.assertEquals(data[0], result[0]); Assert.assertEquals(data[1], result[1]); Assert.assertEquals(data[3], result[2]); Assert.assertEquals(data[4], result[3]); } @Test public void testRemoveElementAtLastIndex() { String[] data = new String[] { "a", "b", "c", "d", "e" }; int index = 4; String[] result = Arrays.removeElementAtIndex(data, index); Assert.assertEquals(data[0], result[0]); Assert.assertEquals(data[1], result[1]); Assert.assertEquals(data[2], result[2]); Assert.assertEquals(data[3], result[3]); Assert.assertEquals(4, result.length); }
### Question: ProxyTypeInspector { public static Class<?>[] getCompatibleClassHierarchy(ClassLoader loader, Class<?> origin) { Set<Class<?>> hierarchy = new LinkedHashSet<Class<?>>(); Class<?> baseClass = origin; while (baseClass != null && Modifier.isFinal(baseClass.getModifiers())) { baseClass = baseClass.getSuperclass(); } while (baseClass != null && !baseClass.isInterface() && baseClass.getSuperclass() != null && !baseClass.getSuperclass().equals(Object.class) && !Proxies.isInstantiable(baseClass)) { baseClass = baseClass.getSuperclass(); } if (baseClass != null && ClassLoaders.containsClass(loader, baseClass.getName()) && !Object.class.equals(baseClass) && (Proxies.isInstantiable(baseClass) || baseClass.isInterface())) { hierarchy.add(ClassLoaders.loadClass(loader, baseClass)); } baseClass = origin; while (baseClass != null) { for (Class<?> type : baseClass.getInterfaces()) { if (ClassLoaders.containsClass(loader, type.getName())) hierarchy.add(ClassLoaders.loadClass(loader, type)); else hierarchy.addAll(java.util.Arrays.asList(getCompatibleClassHierarchy(loader, type))); } baseClass = baseClass.getSuperclass(); } return hierarchy.toArray(new Class<?>[hierarchy.size()]); } static Class<?>[] getCompatibleClassHierarchy(ClassLoader loader, Class<?> origin); static boolean superclassHierarchyContains(Class<?> haystack, Class<?> needle); }### Answer: @Test public void testExceptionHierarchyFindsThrowable() throws Exception { Class<?>[] hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(getClass().getClassLoader(), MockException.class); Assert.assertEquals(2, hierarchy.length); Assert.assertEquals(Exception.class, hierarchy[0]); Assert.assertEquals(Serializable.class, hierarchy[1]); } @Test public void testClassWithInstantiableBaseClass() throws Exception { Class<?>[] hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(getClass().getClassLoader(), MockExtendsImplementsExternal.class); Assert.assertEquals(MockBaseClassExternal.class, hierarchy[0]); Assert.assertEquals(MockInterface.class, hierarchy[1]); Assert.assertEquals(MockNestedInterface.class, hierarchy[2]); } @Test public void testInnerClassWithNonInstantiableBaseClass() throws Exception { Class<?>[] hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(getClass().getClassLoader(), MockExtendsImplementsInternal.class); Assert.assertEquals(MockInterface.class, hierarchy[0]); Assert.assertEquals(MockNestedInterface.class, hierarchy[1]); }
### Question: OperatingSystemUtils { public static File createTempDir() throws IllegalStateException { File baseDir = getTempDirectory(); try { return Files.createTempDirectory(baseDir.toPath(), "tmpdir").toFile(); } catch (IOException e) { throw new IllegalStateException("Error while creating temporary directory", e); } } static String getOsName(); static boolean isWindows(); static boolean isOSX(); static boolean isLinux(); static File getWorkingDir(); static File getForgeHomeDir(); static File getUserHomeDir(); static String getUserHomePath(); static File getUserForgeDir(); static void setPretendWindows(boolean value); static String getLineSeparator(); static String getSafeFilename(String filename); static File createTempDir(); static File getTempDirectory(); static boolean isJava8(); }### Answer: @Test public void testCreateTempDir() { File tmpDir = OperatingSystemUtils.createTempDir(); tmpDir.deleteOnExit(); Assert.assertThat(tmpDir.isDirectory(), is(true)); }
### Question: StateMachine { public void nextCameraState() { switch (cameraState) { case BLOCKED: cameraState = CameraState.BLACK_PICTURE; jsonParser.setCameraState("softBlackPicture"); break; case BLACK_PICTURE: cameraState = CameraState.NEUTRAL_PICTURE; jsonParser.setCameraState("softNeutralPicture"); break; } } StateMachine(); MicrophoneState getMicrophoneState(); CameraState getCameraState(); void nextMicrophoneState(); void nextCameraState(); }### Answer: @Test public void nextCameraState() { assertEquals(CameraState.BLOCKED, stateMachine.getCameraState()); stateMachine.nextCameraState(); assertEquals(CameraState.BLACK_PICTURE, stateMachine.getCameraState()); stateMachine.nextCameraState(); assertEquals(CameraState.NEUTRAL_PICTURE, stateMachine.getCameraState()); stateMachine.nextCameraState(); assertEquals(CameraState.PIXEL_PERSONS, stateMachine.getCameraState()); stateMachine.nextCameraState(); }
### Question: StateMachine { public void nextMicrophoneState() { switch (getMicrophoneState()) { case BLOCKED: microphoneState = MicrophoneState.NO_SOUND; jsonParser.setMicrophoneState("softEmptyNoise"); break; case NO_SOUND: microphoneState = MicrophoneState.NEUTRAL_SOUND; jsonParser.setMicrophoneState("softSignalNoise"); break; } } StateMachine(); MicrophoneState getMicrophoneState(); CameraState getCameraState(); void nextMicrophoneState(); void nextCameraState(); }### Answer: @Test public void nextMicrophoneState() { assertEquals(MicrophoneState.BLOCKED, stateMachine.getMicrophoneState()); stateMachine.nextMicrophoneState(); assertEquals(MicrophoneState.NO_SOUND, stateMachine.getMicrophoneState()); stateMachine.nextMicrophoneState(); assertEquals(MicrophoneState.NEUTRAL_SOUND, stateMachine.getMicrophoneState()); stateMachine.nextMicrophoneState(); }
### Question: ClearanceService { public void cleanDatabase() { Calendar cal = GregorianCalendar.getInstance(Locale.GERMANY); cal.set(Calendar.DATE, cal.get(Calendar.DATE) - (30 * monthsBeforeDeletion)); System.out.println("************************************************"); System.out.println("\t Clearance-Prozess gestartet um " + GregorianCalendar.getInstance(Locale.GERMANY).getTime()); Iterable<Profile> unusedProfiles = profileRepository.findAllByLastProfileContactBefore(cal.getTime()); System.out.println("\t Anzahl geloeschter Profile: " + unusedProfiles.spliterator().getExactSizeIfKnown()); profileRepository.delete(unusedProfiles); try { RestTemplate restTemplate = new RestTemplate(); String url = adress + ":" + port + "/" + databaseName + "/" + "_compact"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>("", headers); restTemplate.exchange(url, HttpMethod.POST, entity, String.class); System.out.println("\t Compact-Befehl durchgeführt: true"); } catch (Exception e) { System.out.println("\t Compact-Befehl durchgeführt: false"); e.printStackTrace(); } System.out.println("\t Clearance-Prozess beendet um " + GregorianCalendar.getInstance(Locale.GERMANY).getTime()); System.out.println("************************************************"); } ClearanceService(); void cleanDatabase(); }### Answer: @Test public void testCleanDatabase() { assertThat(profileRepository.count()).isEqualTo(this.outdatedProfiles.length + this.upToDateProfiles.length); clearanceService.cleanDatabase(); assertThat(profileRepository.count()).isEqualTo(this.upToDateProfiles.length); Iterable<Profile> listUpToDateProfilesInDB = profileRepository.findAll(); assertThat(listUpToDateProfilesInDB.toString()).isEqualTo(Arrays.asList(this.upToDateProfiles).toString()); String[] outdatedProfilesIds = new String[outdatedProfiles.length]; for (int i = 0; i < outdatedProfiles.length; ++i) { outdatedProfilesIds[i] = outdatedProfiles[i].get_id(); } Iterable<Profile> listOutdatedProfilesInDB = profileRepository.findAll(Arrays.asList(outdatedProfilesIds)); assertThat(listOutdatedProfilesInDB).isNullOrEmpty(); }
### Question: Cookie { public static Cookie parse(String setCookie) { return parse(System.currentTimeMillis(), setCookie); } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void noEqualsSign() throws Exception { assertThat(Cookie.parse("foo")).isNull(); assertThat(Cookie.parse("foo; Path=/")).isNull(); } @Test public void emptyName() throws Exception { assertThat(Cookie.parse("=b")).isNull(); assertThat(Cookie.parse(" =b")).isNull(); assertThat(Cookie.parse("\r\t \n=b")).isNull(); } @Test public void invalidCharacters() throws Exception { assertThat(Cookie.parse("a\u0000b=cd")).isNull(); assertThat(Cookie.parse("ab=c\u0000d")).isNull(); assertThat(Cookie.parse("a\u0001b=cd")).isNull(); assertThat(Cookie.parse("ab=c\u0001d")).isNull(); assertThat(Cookie.parse("a\u0009b=cd")).isNull(); assertThat(Cookie.parse("ab=c\u0009d")).isNull(); assertThat(Cookie.parse("a\u001fb=cd")).isNull(); assertThat(Cookie.parse("ab=c\u001fd")).isNull(); assertThat(Cookie.parse("a\u007fb=cd")).isNull(); assertThat(Cookie.parse("ab=c\u007fd")).isNull(); assertThat(Cookie.parse("a\u0080b=cd")).isNull(); assertThat(Cookie.parse("ab=c\u0080d")).isNull(); assertThat(Cookie.parse("a\u00ffb=cd")).isNull(); assertThat(Cookie.parse("ab=c\u00ffd")).isNull(); }
### Question: Cookie { @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(name); result.append('='); result.append(value); if (persistent) { if (expiresAt == Long.MIN_VALUE) { result.append("; max-age=0"); } else { result.append("; expires=").append(STANDARD_DATE_FORMAT.format(new Date(expiresAt))); } } if (!hostOnly) { result.append("; domain="); result.append(domain); } result.append("; path=").append(path); if (secure) { result.append("; secure"); } if (httpOnly) { result.append("; httponly"); } return result.toString(); } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void builderExpiresAt() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .hostOnlyDomain("example.com") .expiresAt(date("1970-01-01T00:00:01.000+0000").getTime()) .build(); assertThat(cookie.toString()).isEqualTo( "a=b; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/"); } @Test public void builderClampsMinDate() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .hostOnlyDomain("example.com") .expiresAt(date("1970-01-01T00:00:00.000+0000").getTime()) .build(); assertThat(cookie.toString()).isEqualTo("a=b; max-age=0; path=/"); } @Test public void builderClampsMaxDate() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .hostOnlyDomain("example.com") .expiresAt(Long.MAX_VALUE) .build(); assertThat(cookie.toString()).isEqualTo( "a=b; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/"); }
### Question: Cookie { public String getPath() { return path; } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void builderPath() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .hostOnlyDomain("example.com") .path("/foo") .build(); assertThat(cookie.getPath()).isEqualTo("/foo"); }
### Question: Cookie { public boolean getSecure() { return secure; } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void builderSecure() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .hostOnlyDomain("example.com") .secure(true) .build(); assertThat(cookie.getSecure()).isTrue(); }
### Question: Cookie { public boolean getHttpOnly() { return httpOnly; } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void builderHttpOnly() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .hostOnlyDomain("example.com") .httpOnly(true) .build(); assertThat(cookie.getHttpOnly()).isTrue(); }
### Question: Cookie { public String getDomain() { return domain; } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void builderIpv6() throws Exception { Cookie cookie = new Cookie.Builder() .name("a") .value("b") .domain("0:0:0:0:0:0:0:1") .build(); assertThat(cookie.getDomain()).isEqualTo("0:0:0:0:0:0:0:1"); }
### Question: Cookie { public boolean getPersistent() { return persistent; } private Cookie(String name, String value, long expiresAt, String domain, String path, boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent); private Cookie(Builder builder); String getName(); String getValue(); boolean getPersistent(); long getExpiresAt(); boolean getHostOnly(); String getDomain(); String getPath(); boolean getHttpOnly(); boolean getSecure(); static List<Cookie> parseAll(List<String> cookieStrings); static Cookie parse(String setCookie); @Override String toString(); boolean similarTo(Cookie other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void maxAgeOrExpiresMakesCookiePersistent() throws Exception { assertThat(parseCookie(0L, "a=b").getPersistent()).isFalse(); assertThat(parseCookie(0L, "a=b; Max-Age=1").getPersistent()).isTrue(); assertThat(parseCookie(0L, "a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT").getPersistent()) .isTrue(); }
### Question: Ray2D { public Segment2D intersectionSegment(Ray2D other) { if(this.contains(other.getStart()) && other.contains(this.getStart())) { return new Segment2D(this.getStart(), other.getStart()); } else { return null; } } Ray2D(Vector2D start, Vector2D direction); Vector2D getStart(); void setStart(Vector2D start); Vector2D getDirection(); void setDirection(Vector2D direction); Vector2D intersectionPoint(Ray2D other); Ray2D intersectionRay(Ray2D other); Segment2D intersectionSegment(Ray2D other); boolean contains(Vector2D point); boolean isParallel(Ray2D other); boolean equals(Ray2D other); String toString(); }### Answer: @Test public void intersectionSegment() throws Exception { aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(5,0); bDirection = GeometryFactory.createVector(-1,0); b = GeometryFactory.createRay2D(bStart, bDirection); Segment2D intersectionSegment = a.intersectionSegment(b); Assert.assertEquals(0, intersectionSegment.getFirstPoint().getXComponent(), PRECISION); Assert.assertEquals(0, intersectionSegment.getFirstPoint().getYComponent(), PRECISION); Assert.assertEquals(5, intersectionSegment.getLastPoint().getXComponent(), PRECISION); Assert.assertEquals(0, intersectionSegment.getLastPoint().getYComponent(), PRECISION); aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(0,1); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(0,7); bDirection = GeometryFactory.createVector(0,-0.1); b = GeometryFactory.createRay2D(bStart, bDirection); intersectionSegment = a.intersectionSegment(b); Assert.assertEquals(0, intersectionSegment.getFirstPoint().getXComponent(), PRECISION); Assert.assertEquals(0, intersectionSegment.getFirstPoint().getYComponent(), PRECISION); Assert.assertEquals(0, intersectionSegment.getLastPoint().getXComponent(), PRECISION); Assert.assertEquals(7, intersectionSegment.getLastPoint().getYComponent(), PRECISION); bStart = GeometryFactory.createVector(5,5); bDirection = GeometryFactory.createVector(-1,0); b = GeometryFactory.createRay2D(bStart, bDirection); intersectionSegment = a.intersectionSegment(b); assertNull(intersectionSegment); }
### Question: Ellipse2D { public Vector2D closestPoint(Vector2D point) { return null; } Ellipse2D(Vector2D center, Vector2D direction, double majorAxis, double minorAxis); Vector2D closestPoint(Vector2D point); Vector2D vectorBetween(Vector2D point); Vector2D normal(Vector2D point); Vector2D getCenter(); void setCenter(Vector2D center); double getOrientation(); double getMajorAxis(); double getMinorAxis(); void translate(double x, double y); void translate(Vector2D vector); }### Answer: @Test public void closestPoint() throws Exception { F1 = GeometryFactory.createVector(0, 0); F2 = GeometryFactory.createVector(2, 0); minorAxis = 2; ellipse = GeometryFactory.createEllipse(F1, F2, minorAxis); point = GeometryFactory.createVector(1, 3); closestPoint = ellipse.closestPoint(point); Assert.assertEquals(1, closestPoint.getXComponent(), PRECISION); Assert.assertEquals(2, closestPoint.getYComponent(), PRECISION); ellipse = GeometryFactory.createEllipse(new Vector2D(10, 10), new Vector2D(1, 0), 1, 1); point = new Vector2D(12, 12); Assert.assertEquals(10+Math.sqrt(2)/2, ellipse.closestPoint(point).getXComponent(), PRECISION); Assert.assertEquals(10+Math.sqrt(2)/2, ellipse.closestPoint(point).getXComponent(), PRECISION); }
### Question: Ellipse2D { public Vector2D vectorBetween(Vector2D point) { Vector2D closestPoint = closestPoint(point); return point.subtract(closestPoint); } Ellipse2D(Vector2D center, Vector2D direction, double majorAxis, double minorAxis); Vector2D closestPoint(Vector2D point); Vector2D vectorBetween(Vector2D point); Vector2D normal(Vector2D point); Vector2D getCenter(); void setCenter(Vector2D center); double getOrientation(); double getMajorAxis(); double getMinorAxis(); void translate(double x, double y); void translate(Vector2D vector); }### Answer: @Test public void vectorBetween() throws Exception { Vector2D vectorBetween; F1 = GeometryFactory.createVector(0, 0); F2 = GeometryFactory.createVector(2, 0); minorAxis = 2; ellipse = GeometryFactory.createEllipse(F1, F2, minorAxis); point = GeometryFactory.createVector(1, 3); vectorBetween = ellipse.vectorBetween(point); Assert.assertEquals(0, vectorBetween.getXComponent(), PRECISION); Assert.assertEquals(1, vectorBetween.getYComponent(), PRECISION); ellipse = GeometryFactory.createEllipse(new Vector2D(10, 10), new Vector2D(1, 0), 1, 1); Assert.assertEquals(0, ellipse.getOrientation(), PRECISION); point = new Vector2D(12,12); closestPoint = ellipse.closestPoint(point); vectorBetween = ellipse.vectorBetween(point); Assert.assertEquals(2 - Math.sqrt(2)/2, vectorBetween.getXComponent(), PRECISION); Assert.assertEquals(2 - Math.sqrt(2)/2, vectorBetween.getYComponent(), PRECISION); }
### Question: Ellipse2D { public Vector2D normal(Vector2D point) { Vector2D pointOnEllipse = closestPoint(point); pointOnEllipse = pointOnEllipse.subtract(this.getCenter()).rotate(-this.getOrientation()); Vector2D normal = new Vector2D(pointOnEllipse.getXComponent() * getMinorAxis()/getMajorAxis(), pointOnEllipse.getYComponent() * getMajorAxis()/getMinorAxis()); return normal.rotate(this.getOrientation()).getNormalized(); } Ellipse2D(Vector2D center, Vector2D direction, double majorAxis, double minorAxis); Vector2D closestPoint(Vector2D point); Vector2D vectorBetween(Vector2D point); Vector2D normal(Vector2D point); Vector2D getCenter(); void setCenter(Vector2D center); double getOrientation(); double getMajorAxis(); double getMinorAxis(); void translate(double x, double y); void translate(Vector2D vector); }### Answer: @Test public void normal() throws Exception { center = GeometryFactory.createVector(1, 1); direction = GeometryFactory.createVector(1, 1); minorAxis = 2; majorAxis = 5; ellipse = GeometryFactory.createEllipse(center, direction, majorAxis, minorAxis); point = GeometryFactory.createVector(1-1/Math.sqrt(2), 1+1/Math.sqrt(2)); normal = ellipse.normal(point); Assert.assertEquals(-1/Math.sqrt(2), normal.getXComponent(), PRECISION); Assert.assertEquals(1/Math.sqrt(2), normal.getYComponent(), PRECISION); F1 = GeometryFactory.createVector(0, 0); F2 = GeometryFactory.createVector(2, 0); minorAxis = 2; ellipse = GeometryFactory.createEllipse(F1, F2, minorAxis); point = GeometryFactory.createVector(1, 3); normal = ellipse.normal(point); Assert.assertEquals(0, normal.getXComponent(), PRECISION); Assert.assertEquals(1, normal.getYComponent(), PRECISION); F1 = GeometryFactory.createVector(0, 0); F2 = GeometryFactory.createVector(2, 2); minorAxis = 1; ellipse = GeometryFactory.createEllipse(F1, F2, minorAxis); Assert.assertEquals(Math.sqrt(3), ellipse.getMajorAxis(), PRECISION); point = GeometryFactory.createVector(2.5, 2.5); normal = ellipse.normal(point); Assert.assertEquals(Math.sqrt(2)/2, normal.getXComponent(), PRECISION); Assert.assertEquals(Math.sqrt(2)/2, normal.getYComponent(), PRECISION); F1 = GeometryFactory.createVector(0, 0); F2 = GeometryFactory.createVector(2, 2); minorAxis = 1; ellipse = GeometryFactory.createEllipse(F1, F2, minorAxis); point = GeometryFactory.createVector(-1, -1); normal = ellipse.normal(point); Assert.assertEquals(-Math.sqrt(2)/2, normal.getXComponent(), PRECISION); Assert.assertEquals(-Math.sqrt(2)/2, normal.getYComponent(), PRECISION); center = GeometryFactory.createVector(1, 0); direction = GeometryFactory.createVector(1, 0); minorAxis = 2; majorAxis = 5; ellipse = GeometryFactory.createEllipse(center, direction, majorAxis, minorAxis); point = GeometryFactory.createVector(1, 5); normal = ellipse.normal(point); Assert.assertEquals(0, normal.getXComponent(), PRECISION); Assert.assertEquals(1, normal.getYComponent(), PRECISION); }
### Question: Rectangle2D extends Geometry2D { @Override public Vector2D vectorBetween(Vector2D point) { return this.rectangleAsSegments().vectorBetween(point); } Rectangle2D(Vector2D center, Vector2D direction, double width, double height); @Override double distanceBetween(Vector2D point); @Override double minimalDistanceBetween(List<Vector2D> points); @Override Vector2D vectorBetween(Vector2D point); @Override ArrayList<Vector2D> getIntersection(Segment2D segment); @Override ArrayList<Vector2D> getIntersection(Polygon2D polygon); @Override ArrayList<Vector2D> getIntersection(Cycle2D segment); @Override boolean isOnCorners(Vector2D vector, double precision); @Override boolean isOnLines(Vector2D vector, double precision); @Override List<Vector2D> getVertices(); synchronized Segment2D rectangleAsSegments(); @Override List<Segment2D> getSegments(); @Override Vector2D getPointClosestToVector(Vector2D toVector); @Override double area(); @Override boolean contains(Vector2D point); @Override boolean contains(Vector2D point, Transform transform); @Override Mass createMass(double density); @Override double getRadius(); @Override double getRadius(Vector2D vector); @Override Vector2D getCenter(); @Override void rotate(double theta); @Override void rotate(double theta, double x, double y); @Override void rotate(double theta, Vector2D vector); @Override void translate(double x, double y); @Override void translate(Vector2D vector); }### Answer: @Test public void vectorBetween() throws Exception { center = GeometryFactory.createVector(0, 0); direction = GeometryFactory.createVector(1, 0); width = 2; height = 6; rectangle = new Rectangle2D(center, direction, width, height); point = GeometryFactory.createVector(3, 2); Assert.assertEquals(1, rectangle.distanceBetween(point), PRECISION); point = GeometryFactory.createVector(-4, 2); Assert.assertEquals(Math.sqrt(2), rectangle.distanceBetween(point), PRECISION); point = GeometryFactory.createVector(3, 2); Vector2D between = rectangle.vectorBetween(point); Assert.assertEquals(0, between.getXComponent(), PRECISION); Assert.assertEquals(-1, between.getYComponent(), PRECISION); }
### Question: Ray2D { public Vector2D intersectionPoint(Ray2D other) { double dx = other.getStart().getXComponent() - this.getStart().getXComponent(); double dy = other.getStart().getYComponent() - this.getStart().getYComponent(); double det = other.getDirection().getXComponent() * this.getDirection().getYComponent() - other.getDirection().getYComponent() * this.getDirection().getXComponent(); if(det == 0) { return null; } double u = (dy * other.getDirection().getXComponent() - dx * other.getDirection().getYComponent()) / det; double v = (dy * this.getDirection().getXComponent() - dx * this.getDirection().getYComponent()) / det; if(u >= 0 && v >= 0) { return this.getStart().sum(this.getDirection().multiply(u)); } else { return null; } } Ray2D(Vector2D start, Vector2D direction); Vector2D getStart(); void setStart(Vector2D start); Vector2D getDirection(); void setDirection(Vector2D direction); Vector2D intersectionPoint(Ray2D other); Ray2D intersectionRay(Ray2D other); Segment2D intersectionSegment(Ray2D other); boolean contains(Vector2D point); boolean isParallel(Ray2D other); boolean equals(Ray2D other); String toString(); }### Answer: @Test public void intersectionPoint() throws Exception { aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(0,1); bDirection = GeometryFactory.createVector(1,0); b = GeometryFactory.createRay2D(bStart, bDirection); assertNull(a.intersectionPoint(b)); aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); b = GeometryFactory.createRay2D(aStart, aDirection); assertNull(a.intersectionPoint(b)); aStart = GeometryFactory.createVector(1,1); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(2,1); bDirection = GeometryFactory.createVector(1,0); b = GeometryFactory.createRay2D(bStart, bDirection); assertNull(a.intersectionPoint(b)); aStart = GeometryFactory.createVector(5,0); aDirection = GeometryFactory.createVector(-1,0); bStart = GeometryFactory.createVector(0,5); bDirection = GeometryFactory.createVector(0,-1); a = GeometryFactory.createRay2D(aStart, aDirection); b = GeometryFactory.createRay2D(bStart, bDirection); intersection = a.intersectionPoint(b); Assert.assertEquals(0, intersection.getXComponent(), PRECISION); Assert.assertEquals(0, intersection.getXComponent(), PRECISION); aStart = GeometryFactory.createVector(2,0); aDirection = GeometryFactory.createVector(1,2); bStart = GeometryFactory.createVector(0,2); bDirection = GeometryFactory.createVector(2,1); a = GeometryFactory.createRay2D(aStart, aDirection); b = GeometryFactory.createRay2D(bStart, bDirection); intersection = a.intersectionPoint(b); Assert.assertEquals(4, intersection.getXComponent(), PRECISION); Assert.assertEquals(4, intersection.getXComponent(), PRECISION); }
### Question: Ray2D { public boolean isParallel(Ray2D other) { return this.getDirection().cross(other.getDirection()) == 0; } Ray2D(Vector2D start, Vector2D direction); Vector2D getStart(); void setStart(Vector2D start); Vector2D getDirection(); void setDirection(Vector2D direction); Vector2D intersectionPoint(Ray2D other); Ray2D intersectionRay(Ray2D other); Segment2D intersectionSegment(Ray2D other); boolean contains(Vector2D point); boolean isParallel(Ray2D other); boolean equals(Ray2D other); String toString(); }### Answer: @Test public void isParallel() throws Exception { aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(1,1); bDirection = GeometryFactory.createVector(1,0); b = GeometryFactory.createRay2D(bStart, bDirection); assertTrue(a.isParallel(b)); bStart = GeometryFactory.createVector(1,1); bDirection = GeometryFactory.createVector(1,1.0001); b = GeometryFactory.createRay2D(bStart, bDirection); assertFalse(a.isParallel(b)); bStart = GeometryFactory.createVector(0,0); bDirection = GeometryFactory.createVector(0,1); b = GeometryFactory.createRay2D(bStart, bDirection); assertFalse(a.isParallel(b)); }
### Question: Ray2D { public boolean equals(Ray2D other) { return this.getStart().equals(other.getStart()) && this.getDirection().getNormalized().equals(other.getDirection().getNormalized()); } Ray2D(Vector2D start, Vector2D direction); Vector2D getStart(); void setStart(Vector2D start); Vector2D getDirection(); void setDirection(Vector2D direction); Vector2D intersectionPoint(Ray2D other); Ray2D intersectionRay(Ray2D other); Segment2D intersectionSegment(Ray2D other); boolean contains(Vector2D point); boolean isParallel(Ray2D other); boolean equals(Ray2D other); String toString(); }### Answer: @Test public void equals() throws Exception { aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(1,1); bDirection = GeometryFactory.createVector(1,0); b = GeometryFactory.createRay2D(bStart, bDirection); assertFalse(a.equals(b)); bStart = GeometryFactory.createVector(0,0); bDirection = GeometryFactory.createVector(2,0); b = GeometryFactory.createRay2D(bStart, bDirection); assertTrue(a.equals(b)); }
### Question: Ray2D { public boolean contains(Vector2D point) { Vector2D newNorm = point.subtract(this.getStart()).getNormalized(); double dotProduct = newNorm.dot(this.getDirection().getNormalized()); return Math.abs(1.0 - dotProduct) < EPSILON; } Ray2D(Vector2D start, Vector2D direction); Vector2D getStart(); void setStart(Vector2D start); Vector2D getDirection(); void setDirection(Vector2D direction); Vector2D intersectionPoint(Ray2D other); Ray2D intersectionRay(Ray2D other); Segment2D intersectionSegment(Ray2D other); boolean contains(Vector2D point); boolean isParallel(Ray2D other); boolean equals(Ray2D other); String toString(); }### Answer: @Test public void contains() throws Exception { aStart = GeometryFactory.createVector(5,5); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); point = GeometryFactory.createVector(7,0); assertFalse(a.contains(point)); point = GeometryFactory.createVector(7,5); assertTrue(a.contains(point)); point = GeometryFactory.createVector(4,5); assertFalse(a.contains(point)); aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(0,1); a = GeometryFactory.createRay2D(aStart, aDirection); point = GeometryFactory.createVector(0,1); assertTrue(a.contains(point)); point = GeometryFactory.createVector(0,-2); assertFalse(a.contains(point)); aStart = GeometryFactory.createVector(1,0); aDirection = GeometryFactory.createVector(1,1); a = GeometryFactory.createRay2D(aStart, aDirection); point = GeometryFactory.createVector(3,2); assertTrue(a.contains(point)); point = GeometryFactory.createVector(0,-1); assertFalse(a.contains(point)); }
### Question: Ray2D { public Ray2D intersectionRay(Ray2D other) { double dotProduct = this.getDirection().getNormalized().dot(other.getDirection().getNormalized()); if(this.contains(other.getStart()) && !other.contains(this.getStart()) && Math.abs(1.0 - dotProduct) < EPSILON) { return new Ray2D(other.getStart(), other.getDirection()); } else if(!this.contains(other.getStart()) && other.contains(this.getStart()) && Math.abs(1.0 - dotProduct) < EPSILON) { return new Ray2D(this.getStart(), this.getDirection()); } else { return null; } } Ray2D(Vector2D start, Vector2D direction); Vector2D getStart(); void setStart(Vector2D start); Vector2D getDirection(); void setDirection(Vector2D direction); Vector2D intersectionPoint(Ray2D other); Ray2D intersectionRay(Ray2D other); Segment2D intersectionSegment(Ray2D other); boolean contains(Vector2D point); boolean isParallel(Ray2D other); boolean equals(Ray2D other); String toString(); }### Answer: @Test public void intersectionRay() throws Exception { aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(5,0); bDirection = GeometryFactory.createVector(1,0); b = GeometryFactory.createRay2D(bStart, bDirection); Ray2D intersectionRay = a.intersectionRay(b); assertTrue(intersectionRay.equals(b)); intersectionRay = b.intersectionRay(a); assertTrue(intersectionRay.equals(b)); aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(0,5); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(0,3); bDirection = GeometryFactory.createVector(0,0.1); b = GeometryFactory.createRay2D(bStart, bDirection); intersectionRay = a.intersectionRay(b); assertTrue(intersectionRay.equals(b)); intersectionRay = b.intersectionRay(a); assertTrue(intersectionRay.equals(b)); aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(5,0); bDirection = GeometryFactory.createVector(-1,0); b = GeometryFactory.createRay2D(bStart, bDirection); assertNull(a.intersectionRay(b)); aStart = GeometryFactory.createVector(0,0); aDirection = GeometryFactory.createVector(1,0); a = GeometryFactory.createRay2D(aStart, aDirection); bStart = GeometryFactory.createVector(0,5); bDirection = GeometryFactory.createVector(0,-1); b = GeometryFactory.createRay2D(bStart, bDirection); assertNull(a.intersectionRay(b)); }
### Question: OpenAPIStyleValidatorGradlePlugin implements Plugin<Project> { public void apply(Project project) { project.getTasks().register("openAPIStyleValidator", OpenAPIStyleValidatorTask.class); } void apply(Project project); }### Answer: @Test public void pluginRegistersATask() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply("org.openapitools.openapistylevalidator"); assertNotNull(project.getTasks().findByName("openAPIStyleValidator")); }
### Question: OpenApiSpecStyleValidator { public List<StyleError> validate(ValidatorParameters parameters) { this.parameters = parameters; validateInfo(); validateOperations(); validateModels(); validateNaming(); return errorAggregator.getErrorList(); } OpenApiSpecStyleValidator(OpenAPI openApi); List<StyleError> validate(ValidatorParameters parameters); static final String INPUT_FILE; }### Answer: @Test void validatePingOpenAPI() { OpenAPI openAPI = createPingOpenAPI(); OpenApiSpecStyleValidator validator = new OpenApiSpecStyleValidator(openAPI); ValidatorParameters parameters = new ValidatorParameters(); List<StyleError> errors = validator.validate(parameters); assertTrue(errors.size() == 1); assertEquals("*ERROR* in Model 'Myobject', property 'name', field 'example' -> This field should be present and not empty", errors.get(0).toString()); } @Test void validatePingOpenAPI_without_ValidateModelPropertiesExample() { OpenAPI openAPI = createPingOpenAPI(); OpenApiSpecStyleValidator validator = new OpenApiSpecStyleValidator(openAPI); ValidatorParameters parameters = new ValidatorParameters(); parameters.setValidateModelPropertiesExample(false); List<StyleError> errors = validator.validate(parameters); assertTrue(errors.size() == 0); } @Test void validatePingOpenAPI_WithoutSchema_and_components() { OpenAPI openAPI = createSimplePingOpenAPI(); OpenApiSpecStyleValidator validator = new OpenApiSpecStyleValidator(openAPI); ValidatorParameters parameters = new ValidatorParameters(); List<StyleError> errors = validator.validate(parameters); assertTrue(errors.size() == 0); }
### Question: KmlUtil { public static String substituteProperties(String template, KmlPlacemark placemark) { StringBuffer sb = new StringBuffer(); Pattern pattern = Pattern.compile("\\$\\[(.+?)]"); Matcher matcher = pattern.matcher(template); while (matcher.find()) { String property = matcher.group(1); String value = placemark.getProperty(property); if (value != null) { matcher.appendReplacement(sb, value); } } matcher.appendTail(sb); return sb.toString(); } static String substituteProperties(String template, KmlPlacemark placemark); }### Answer: @Test public void testSubstituteProperties() { Map<String, String> properties = new HashMap<>(); properties.put("name", "Bruce Wayne"); properties.put("description", "Batman"); properties.put("Snippet", "I am the night"); KmlPlacemark placemark = new KmlPlacemark(null, null, null, properties); String result1 = KmlUtil.substituteProperties("$[name] is my name", placemark); assertEquals("Bruce Wayne is my name", result1); String result2 = KmlUtil.substituteProperties("Also known as $[description]", placemark); assertEquals("Also known as Batman", result2); String result3 = KmlUtil.substituteProperties("I say \"$[Snippet]\" often", placemark); assertEquals("I say \"I am the night\" often", result3); String result4 = KmlUtil.substituteProperties("My address is $[address]", placemark); assertEquals("When property doesn't exist, placeholder is left in place", "My address is $[address]", result4); }
### Question: KmlContainerParser { static KmlContainer createContainer(XmlPullParser parser) throws XmlPullParserException, IOException { return assignPropertiesToContainer(parser); } }### Answer: @Test public void testCreateContainerProperty() throws Exception { XmlPullParser xmlPullParser = createParser("amu_basic_folder.kml"); KmlContainer kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertTrue(kmlContainer.hasProperties()); assertEquals("Basic Folder", kmlContainer.getProperty("name")); xmlPullParser = createParser("amu_unknown_folder.kml"); kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertTrue(kmlContainer.hasProperty("name")); } @Test public void testCreateContainerPlacemark() throws Exception { XmlPullParser xmlPullParser = createParser("amu_basic_folder.kml"); KmlContainer kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertTrue(kmlContainer.hasPlacemarks()); assertEquals(1, kmlContainer.getPlacemarksHashMap().size()); xmlPullParser = createParser("amu_multiple_placemarks.kml"); kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertTrue(kmlContainer.hasPlacemarks()); assertEquals(2, kmlContainer.getPlacemarksHashMap().size()); } @Test public void testCreateContainerGroundOverlay() throws Exception { XmlPullParser xmlPullParser = createParser("amu_ground_overlay.kml"); KmlContainer kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertEquals(2, kmlContainer.getGroundOverlayHashMap().size()); } @Test public void testCreateContainerObjects() throws Exception { XmlPullParser xmlPullParser = createParser("amu_nested_folders.kml"); KmlContainer kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertNotNull(kmlContainer.getContainers()); int numberOfNestedContainers = 0; for (KmlContainer container : kmlContainer.getContainers()) { numberOfNestedContainers++; } assertEquals(2, numberOfNestedContainers); } @Test public void testCDataEntity() throws Exception { XmlPullParser xmlPullParser = createParser("amu_cdata.kml"); KmlContainer kmlContainer = KmlContainerParser.createContainer(xmlPullParser); assertEquals("TELEPORT", kmlContainer.getProperty("description")); }
### Question: KmlLineString extends LineString { public ArrayList<LatLng> getGeometryObject() { List<LatLng> coordinatesList = super.getGeometryObject(); return new ArrayList<>(coordinatesList); } KmlLineString(ArrayList<LatLng> coordinates); KmlLineString(ArrayList<LatLng> coordinates, ArrayList<Double> altitudes); ArrayList<Double> getAltitudes(); ArrayList<LatLng> getGeometryObject(); }### Answer: @Test public void testGetKmlGeometryObject() { KmlLineString kmlLineString = createSimpleLineString(); assertNotNull(kmlLineString); assertNotNull(kmlLineString.getGeometryObject()); assertEquals(3, kmlLineString.getGeometryObject().size()); assertEquals(0.0, kmlLineString.getGeometryObject().get(0).latitude, 0); assertEquals(50.0, kmlLineString.getGeometryObject().get(1).latitude, 0); assertEquals(90.0, kmlLineString.getGeometryObject().get(2).latitude, 0); kmlLineString = createLoopedLineString(); assertNotNull(kmlLineString); assertNotNull(kmlLineString.getGeometryObject()); assertEquals(3, kmlLineString.getGeometryObject().size()); assertEquals(0.0, kmlLineString.getGeometryObject().get(0).latitude, 0); assertEquals(50.0, kmlLineString.getGeometryObject().get(1).latitude, 0); assertEquals(0.0, kmlLineString.getGeometryObject().get(2).latitude, 0); }
### Question: KmlLineString extends LineString { public ArrayList<Double> getAltitudes() { return mAltitudes; } KmlLineString(ArrayList<LatLng> coordinates); KmlLineString(ArrayList<LatLng> coordinates, ArrayList<Double> altitudes); ArrayList<Double> getAltitudes(); ArrayList<LatLng> getGeometryObject(); }### Answer: @Test public void testLineStringAltitudes() { KmlLineString kmlLineString = createSimpleLineString(); assertNotNull(kmlLineString); assertNull(kmlLineString.getAltitudes()); kmlLineString = createSimpleLineStringWithAltitudes(); assertNotNull(kmlLineString); assertNotNull(kmlLineString.getAltitudes()); assertEquals(100.0, kmlLineString.getAltitudes().get(0), 0); assertEquals(200.0, kmlLineString.getAltitudes().get(1), 0); assertEquals(300.0, kmlLineString.getAltitudes().get(2), 0); }
### Question: KmlFeatureParser { static KmlPlacemark createPlacemark(XmlPullParser parser) throws IOException, XmlPullParserException { String styleId = null; KmlStyle inlineStyle = null; HashMap<String, String> properties = new HashMap<String, String>(); Geometry geometry = null; int eventType = parser.getEventType(); while (!(eventType == END_TAG && parser.getName().equals("Placemark"))) { if (eventType == START_TAG) { if (parser.getName().equals(STYLE_URL_TAG)) { styleId = parser.nextText(); } else if (parser.getName().matches(GEOMETRY_REGEX)) { geometry = createGeometry(parser, parser.getName()); } else if (parser.getName().matches(PROPERTY_REGEX)) { properties.put(parser.getName(), parser.nextText()); } else if (parser.getName().equals(EXTENDED_DATA)) { properties.putAll(setExtendedDataProperties(parser)); } else if (parser.getName().equals(STYLE_TAG)) { inlineStyle = KmlStyleParser.createStyle(parser); } } eventType = parser.next(); } return new KmlPlacemark(geometry, styleId, inlineStyle, properties); } }### Answer: @Test public void testPolygon() throws Exception { XmlPullParser xmlPullParser = createParser("amu_basic_placemark.kml"); KmlPlacemark placemark = KmlFeatureParser.createPlacemark(xmlPullParser); assertNotNull(placemark); assertEquals(placemark.getGeometry().getGeometryType(), "Polygon"); KmlPolygon polygon = ((KmlPolygon) placemark.getGeometry()); assertEquals(polygon.getInnerBoundaryCoordinates().size(), 2); assertEquals(polygon.getOuterBoundaryCoordinates().size(), 5); } @Test public void testMultiGeometry() throws Exception { XmlPullParser xmlPullParser = createParser("amu_multigeometry_placemarks.kml"); KmlPlacemark placemark = KmlFeatureParser.createPlacemark(xmlPullParser); assertNotNull(placemark); assertEquals(placemark.getGeometry().getGeometryType(), "MultiGeometry"); KmlMultiGeometry multiGeometry = ((KmlMultiGeometry) placemark.getGeometry()); assertEquals(multiGeometry.getGeometryObject().size(), 3); } @Test public void testProperties() throws Exception { XmlPullParser xmlPullParser = createParser("amu_multigeometry_placemarks.kml"); KmlPlacemark placemark = KmlFeatureParser.createPlacemark(xmlPullParser); assertTrue(placemark.hasProperties()); assertEquals(placemark.getProperty("name"), "Placemark Test"); assertNull(placemark.getProperty("description")); } @Test public void testExtendedData() throws Exception { XmlPullParser xmlPullParser = createParser("amu_multiple_placemarks.kml"); KmlPlacemark placemark = KmlFeatureParser.createPlacemark(xmlPullParser); assertNotNull(placemark.getProperty("holeNumber")); } @Test public void testMultiGeometries() throws Exception { XmlPullParser xmlPullParser = createParser("amu_nested_multigeometry.kml"); KmlPlacemark feature = KmlFeatureParser.createPlacemark(xmlPullParser); assertEquals(feature.getProperty("name"), "multiPointLine"); assertEquals(feature.getProperty("description"), "Nested MultiGeometry structure"); assertEquals(feature.getGeometry().getGeometryType(), "MultiGeometry"); List<Geometry> objects = (ArrayList<Geometry>) feature.getGeometry().getGeometryObject(); assertEquals(objects.get(0).getGeometryType(), "Point"); assertEquals(objects.get(1).getGeometryType(), "LineString"); assertEquals(objects.get(2).getGeometryType(), "MultiGeometry"); List<Geometry> subObjects = (ArrayList<Geometry>) objects.get(2).getGeometryObject(); assertEquals(subObjects.get(0).getGeometryType(), "Point"); assertEquals(subObjects.get(1).getGeometryType(), "LineString"); }
### Question: KmlTrack extends KmlLineString { public ArrayList<Long> getTimestamps() { return mTimestamps; } KmlTrack(ArrayList<LatLng> coordinates, ArrayList<Double> altitudes, ArrayList<Long> timestamps, HashMap<String, String> properties); ArrayList<Long> getTimestamps(); HashMap<String, String> getProperties(); }### Answer: @Test public void testTimestamps() { KmlTrack kmlTrack = createSimpleTrack(); assertNotNull(kmlTrack); assertNotNull(kmlTrack.getTimestamps()); assertEquals(kmlTrack.getTimestamps().size(), 3); assertEquals(kmlTrack.getTimestamps().get(0), Long.valueOf(1000L)); assertEquals(kmlTrack.getTimestamps().get(1), Long.valueOf(2000L)); assertEquals(kmlTrack.getTimestamps().get(2), Long.valueOf(3000L)); }
### Question: MultiGeometry implements Geometry { public String getGeometryType() { return geometryType; } MultiGeometry(List<? extends Geometry> geometries); String getGeometryType(); List<Geometry> getGeometryObject(); void setGeometryType(String type); @Override String toString(); }### Answer: @Test public void testGetGeometryType() { List<LineString> lineStrings = new ArrayList<>(); lineStrings.add( new LineString( new ArrayList<>(Arrays.asList(new LatLng(0, 0), new LatLng(50, 50))))); lineStrings.add( new LineString( new ArrayList<>(Arrays.asList(new LatLng(56, 65), new LatLng(23, 23))))); mg = new MultiGeometry(lineStrings); assertEquals("MultiGeometry", mg.getGeometryType()); List<GeoJsonPolygon> polygons = new ArrayList<>(); List<ArrayList<LatLng>> polygon = new ArrayList<>(); polygon.add( new ArrayList<>( Arrays.asList( new LatLng(0, 0), new LatLng(20, 20), new LatLng(60, 60), new LatLng(0, 0)))); polygons.add(new GeoJsonPolygon(polygon)); polygon = new ArrayList<>(); polygon.add( new ArrayList<>( Arrays.asList( new LatLng(0, 0), new LatLng(50, 80), new LatLng(10, 15), new LatLng(0, 0)))); polygon.add( new ArrayList<>( Arrays.asList( new LatLng(0, 0), new LatLng(20, 20), new LatLng(60, 60), new LatLng(0, 0)))); polygons.add(new GeoJsonPolygon(polygon)); mg = new MultiGeometry(polygons); assertEquals("MultiGeometry", mg.getGeometryType()); }
### Question: MultiGeometry implements Geometry { public void setGeometryType(String type) { geometryType = type; } MultiGeometry(List<? extends Geometry> geometries); String getGeometryType(); List<Geometry> getGeometryObject(); void setGeometryType(String type); @Override String toString(); }### Answer: @Test public void testSetGeometryType() { List<LineString> lineStrings = new ArrayList<>(); lineStrings.add( new LineString( new ArrayList<>(Arrays.asList(new LatLng(0, 0), new LatLng(50, 50))))); lineStrings.add( new LineString( new ArrayList<>(Arrays.asList(new LatLng(56, 65), new LatLng(23, 23))))); mg = new MultiGeometry(lineStrings); assertEquals("MultiGeometry", mg.getGeometryType()); mg.setGeometryType("MultiLineString"); assertEquals("MultiLineString", mg.getGeometryType()); }