src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
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(); B... | @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)); } |
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 Dou... | @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)); } |
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 ... | @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)... |
RollupService implements Runnable, RollupServiceMBean { public Collection<Integer> getManagedShards() { return new TreeSet<Integer>(shardStateManager.getManagedShards()); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context,
ShardStateManager shard... | @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(); assertEq... |
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.getSampleCoun... | @Test public void equalsOtherNullReturnsFalse() { BluefloodCounterRollup rollup = new BluefloodCounterRollup(); assertFalse(rollup.equals(null)); }
@Test public void equalsOtherNotRollupReturnsFalse() { BluefloodCounterRollup rollup = new BluefloodCounterRollup(); assertFalse(rollup.equals("")); } |
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<Simp... | @Test(expected = NullPointerException.class) public void rawSampleBuilderWithNullInputsThrowsException() throws IOException { BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromRawSamples(null); } |
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... | @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 = Blue... |
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... | @Test public void getRollupTypeReturnsCounter() { BluefloodCounterRollup rollup = new BluefloodCounterRollup(); assertEquals(RollupType.COUNTER, rollup.getRollupType()); } |
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... | @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.assertEq... |
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 tenant... | @Test public void testGetIndexesToSearch() throws IOException { String[] indices = elasticTokensIO.getIndexesToSearch(); assertEquals(1, indices.length); assertEquals("metric_tokens", indices[0]); } |
ElasticTokensIO implements TokenDiscoveryIO { protected String getRegexToHandleTokens(GlobPattern globPattern) { String[] queryRegexParts = globPattern.compiled().toString().split("\\\\."); return Arrays.stream(queryRegexParts) .map(this::convertRegexToCaptureUptoNextToken) .collect(joining(Locator.METRIC_TOKEN_SEPARAT... | @Test public void testRegexLevel0() { List<String> terms = Arrays.asList("", "foo", "bar", "b", "foo.bar", "foo.bar.baz", "foo.bar.baz.aux"); List<String> matchingTerms = new ArrayList<>(); Pattern patternToGet2Levels = Pattern.compile(elasticTokensIO.getRegexToHandleTokens(new GlobPattern("*"))); for (String term: ter... |
RollupService implements Runnable, RollupServiceMBean { public synchronized Collection<Integer> getRecentlyScheduledShards() { return context.getRecentlyScheduledShards(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context,
ShardStateManager shar... | @Test public void getRecentlyScheduledShardsGetsFromContext() { Collection<Integer> recent = service.getRecentlyScheduledShards(); assertNotNull(recent); verify(context).getRecentlyScheduledShards(); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); } |
EventElasticSearchIO implements EventsIO { @Override public List<Map<String, Object>> search(String tenant, Map<String, List<String>> query) { ArrayList<Map<String, Object>> searchResults = new ArrayList<>(); Timer.Context eventSearchTimerContext = eventSearchTimer.time(); try { String result = elasticsearchRestHelper.... | @Test public void testNonCrossTenantSearch() throws Exception { Map<String, List<String>> query = new HashMap<>(); query.put(Event.tagsParameterName, Arrays.asList("event")); List<Map<String, Object>> results = searchIO.search(TENANT_1, query); Assert.assertEquals(TENANT_1_EVENTS_NUM, results.size()); results = searchI... |
MetricIndexData { public void add(String metricIndex, long docCount) { final String[] tokens = metricIndex.split(METRIC_TOKEN_SEPARATOR_REGEX); switch (tokens.length - baseLevel) { case 1: if (baseLevel > 0) { metricNamesWithNextLevelSet.add(metricIndex.substring(0, metricIndex.lastIndexOf("."))); } else { metricNamesW... | @Test public void testMetricIndexesBuilderSingleMetricName() { ArrayList<String> metricNames = new ArrayList<String>() {{ add("foo.bar.baz"); }}; Map<String, Long> metricIndexMap = buildMetricIndexesSimilarToES(metricNames, "foo"); Set<String> expectedIndexes = new HashSet<String>() {{ add("foo.bar|1"); }}; verifyMetri... |
RollupService implements Runnable, RollupServiceMBean { public synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard) { final Set<String> results = new HashSet<String>(); for (Granularity g : Granularity.rollupGranularities()) { final Map<Integer, UpdateStamp> stateTimestamps = context.getSlotSt... | @Test public void getOldestWithNullStampsReturnsEmptyCollection() { doReturn(null).when(context).getSlotStamps(Matchers.<Granularity>any(), anyInt()); Collection<String> result = service.getOldestUnrolledSlotPerGranularity(0); assertNotNull(result); assertEquals(0, result.size()); }
@Test public void getOldestWithEmpty... |
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 isAcce... | @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 contentTypeJsonShouldBeVali... |
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 ... | @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 mockHeader... |
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 r... | @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);... |
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... | @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).g... |
HttpAggregatedIngestionHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); requestCount.inc(); final Timer.Context timerContext = handlerTimer.time(); String body = null; String submitterTenantId = request.heade... | @Test public void testEmptyRequest() throws IOException { String requestBody = ""; FullHttpRequest request = createIngestRequest(requestBody); ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, request); verify(channel).write(argument.capture()); String ... |
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 ... | @Test public void testEmptyButValidMultiJSON() { String badJson = "[]"; List<AggregatedPayload> bundle = HttpAggregatedMultiIngestionHandler.createBundleList(badJson); } |
HttpAggregatedMultiIngestionHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); requestCount.inc(); final Timer.Context timerContext = handlerTimer.time(); long ingestTime = clock.now().getMillis(); String body ... | @Test public void testEmptyRequest() throws IOException { String requestBody = ""; FullHttpRequest request = createIngestRequest(requestBody); ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, request); verify(channel).write(argument.capture()); String ... |
HttpEventsIngestionHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { final String tenantId = request.headers().get(Event.FieldLabels.tenantId.name()); String response = ""; ObjectMapper objectMapper = new ObjectMapper(); final Timer.Context httpEv... | @Test public void testElasticSearchInsertCalledWhenPut() throws Exception { Map<String, Object> event = createRandomEvent(); handler.handle(context, createPutOneEventRequest(event)); verify(searchIO).insert(TENANT, event); }
@Test public void testInvalidRequestBody() throws Exception { ArgumentCaptor<FullHttpResponse> ... |
HttpMetricsIngestionHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { try { requestsReceived.mark(); Tracker.getInstance().track(request); requestCount.inc(); final String tenantId = request.headers().get(HttpMetricsIngestionServer.TENANT_ID_HEADE... | @Test public void emptyRequest_shouldGenerateErrorResponse() throws IOException { String requestBody = ""; FullHttpRequest request = createIngestRequest(requestBody); ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, request); verify(channel).write(argu... |
RollupBatchWriter { public void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext) { rollupQueue.add(rollupWriteContext); context.incrementWriteCounter(); if (rollupQueue.size() >= ROLLUP_BATCH_MIN_SIZE) { if (executor.getActiveCount() < executor.getPoolSize() || rollupQueue.size() >= ROLLUP_BATCH_MAX_S... | @Test public void enqueueIncrementsWriterCounter() { SingleRollupWriteContext srwc = mock(SingleRollupWriteContext.class); rbw.enqueueRollupForWrite(srwc); verify(ctx).incrementWriteCounter(); verifyNoMoreInteractions(ctx); verifyZeroInteractions(srwc); }
@Test public void enqueuingLessThanMinSizeDoesNotTriggerBatching... |
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 seri... | @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); } |
HttpRollupsQueryHandler extends RollupHandler implements MetricDataQueryInterface<MetricData>, HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final String tenantId = request.headers().get("tenantId"); final String metricName ... | @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.g... |
HttpMultiRollupsQueryHandler extends RollupHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final String tenantId = request.headers().get("tenantId"); if (!(request instanceof HttpRequestWithDecodedQueryParam... | @Test public void testWithNoRequestBody() throws IOException { FullHttpRequest request = createQueryRequest("", ""); ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); handler.handle(context, request); verify(channel).write(argument.capture()); String errorResponseBody = argume... |
HttpMetricsIndexHandler implements HttpRequestHandler { @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final String tenantId = request.headers().get("tenantId"); HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryPa... | @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.g... |
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("tena... | @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()).getMetricN... |
HttpMetricNamesHandler implements HttpRequestHandler { public String getSerializedJSON(final List<MetricName> metricNames) { ArrayNode tokenInfoArrayNode = JsonNodeFactory.instance.arrayNode(); for (MetricName metricName : metricNames) { ObjectNode metricNameInfoNode = JsonNodeFactory.instance.objectNode(); metricNameI... | @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 ... |
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 Tim... | @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()).s... |
BatchedMetricsJSONOutputSerializer extends JSONBasicRollupsOutputSerializer implements BatchedMetricsOutputSerializer<JSONObject> { @Override public JSONObject transformRollupData(Map<Locator, MetricData> metricData, Set<MetricStat> filterStats) throws SerializationException { final JSONObject globalJSON = new JSONObje... | @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(F... |
DateTimeParser { public static DateTime parse(String dateTimeOffsetString) { String stringToParse = dateTimeOffsetString.replace(" ", "").replace(",", "").replace("_", ""); if (StringUtils.isNumeric(stringToParse) && !isLikelyDateTime(stringToParse)) return dateTimeFromTimestamp(stringToParse); DateTime dateTime = tryP... | @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 date... |
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().regis... | @Test public void testRegister() { tracker.register(); verify(loggerMock, times(1)).info("MBean registered as com.rackspacecloud.blueflood.tracker:type=Tracker"); } |
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 removeAl... | @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.contain... |
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 ... | @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 ) ... |
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... | @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("T... |
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 ... | @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 ); }
@... |
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); vo... | @Test public void testSetIsTrackingDelayedMetrics() { tracker.resetIsTrackingDelayedMetrics(); tracker.setIsTrackingDelayedMetrics(); Assert.assertTrue("isTrackingDelayedMetrics should be true from setIsTrackingDelayedMetrics", tracker.getIsTrackingDelayedMetrics()); } |
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 = respo... | @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 Arr... |
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 nowM... | @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 d... |
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.i... | @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.trackDelayedAggregat... |
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++) { SingleRollupWri... | @Test public void drainBatchWithNoItemsDoesNotTriggerBatching() { rbw.drainBatch(); verifyZeroInteractions(ctx); verifyZeroInteractions(executor); } |
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()... | @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",... |
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... | @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() { St... |
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); } | @Test public void testSlotFromStateCol() { Assert.assertEquals(1, serDes.slotFromStateCol("metrics_full,1,okay")); } |
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(); Stri... | @Test public void testNullShouldBeInterpretedAsBooleanFalse() { Assert.assertFalse(Configuration.booleanFromString(null)); }
@Test public void test_TRUE_ShouldBeInterpretedAsBooleanTrue() { Assert.assertTrue(Configuration.booleanFromString("TRUE")); } |
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 getStringPro... | @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) pu... |
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 getStringPro... | @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) pub... |
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 getStrin... | @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 ... |
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); } | @Test public void testStateFromStateCol() { Assert.assertEquals("okay", serDes.stateCodeFromStateCol("metrics_full,1,okay")); } |
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 ... | @Test public void testStringConversion() { Assert.assertEquals(s1 + ": ", ss1.toString()); Assert.assertEquals(s2 + ": " + time, ss2.toString()); Assert.assertEquals(s3 + ": " + time, ss3.toString()); } |
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(Obj... | @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(... |
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 getGranu... | @Test public void testGranularity() { Assert.assertEquals(Granularity.FULL, fromString(s1).getGranularity()); Assert.assertNull(fromString("FULL,1,X").getGranularity()); } |
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 seriali... | @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")); } |
BluefloodServiceStarter { public static void run() { Configuration config = Configuration.getInstance(); String log4jConfig = System.getProperty("log4j.configuration"); if (log4jConfig != null && log4jConfig.startsWith("file:")) { PropertyConfigurator.configureAndWatch(log4jConfig.substring("file:".length()), 5000); } ... | @Test public void testAllModesDisabled() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.INGEST_MODE, "false"); config.setProperty(CoreConfig.QUERY_MODE, "false"); config.setProperty(CoreConfig.ROLLUP_MODE, "false"); BluefloodServiceStarter.run(); }
@Test(expected = BluefloodServiceS... |
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, ... | @Test(expected = BluefloodServiceStarterException.class) public void testNoCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); BluefloodServiceStarter.validateCassandraHosts(); }
@Test(expected = BluefloodServiceStarterException.class... |
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 getMetric... | @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... |
ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } protected ShardStateManager(Collection<Integer> shards, Ticker ticker); protected ShardStateManager(Collection<Integer> shards, Ticker ticker, Clock ... | @Test public void testUpdateSlotsOnReadWithIncomingActiveState() { establishCurrentState(); final long lastRollupTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastRollupTimestamp(); final long lastCollectionTime = System.currentTimeMillis(); final long lastUpdatedTime = System.currentTimeMillis(); SlotState... |
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.decrementWriteCount... | @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; ... |
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 ... | @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.... |
LocatorFetchRunnable implements Runnable { public void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { executionContext.incrementReadCounter(); final SingleRollupReadContext singleRollupReadContext = new SingleRollupReadContext(locator, parentRang... | @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))... |
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 { execu... | @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 pu... |
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[]{parentSl... | @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()); ... |
LocatorFetchRunnable implements Runnable { protected RollupExecutionContext createRollupExecutionContext() { return new RollupExecutionContext(Thread.currentThread()); } LocatorFetchRunnable(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExe... | @Test public void createRollupExecutionContextReturnsValidObject() { RollupExecutionContext execCtx = lfr.createRollupExecutionContext(); assertNotNull(execCtx); } |
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... | @Test public void testMirrorCentralWithoutProfiles() throws Exception { SettingsBuilder settingsBuilder = new DefaultSettingsBuilderFactory().newInstance(); SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest(); settingsRequest.setUserSettingsFile(new File("src/test/resources/profiles/mirror-se... |
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()... | @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 testPars... |
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 Multip... | @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)); } |
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 r... | @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... |
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... | @Test(expected = IllegalArgumentException.class) public void testVersionMustNotBeNull() { SingleVersion.valueOf(null); } |
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 ... | @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"... |
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 ... | @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(Serializa... |
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 S... | @Test public void testCreateTempDir() { File tmpDir = OperatingSystemUtils.createTempDir(); tmpDir.deleteOnExit(); Assert.assertThat(tmpDir.isDirectory(), is(true)); } |
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(); Mi... | @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()); stateM... |
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; } ... | @Test public void nextMicrophoneState() { assertEquals(MicrophoneState.BLOCKED, stateMachine.getMicrophoneState()); stateMachine.nextMicrophoneState(); assertEquals(MicrophoneState.NO_SOUND, stateMachine.getMicrophoneState()); stateMachine.nextMicrophoneState(); assertEquals(MicrophoneState.NEUTRAL_SOUND, stateMachine.... |
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 " + G... | @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 = profileRepos... |
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 builde... | @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")).isNu... |
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(exp... | @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 ... |
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 getPersisten... | @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"); } |
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 getPers... | @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(); } |
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 get... | @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(); } |
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 getPersi... | @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"); } |
Cookie { public long getExpiresAt() { return expiresAt; } 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 getP... | @Test public void maxAge() throws Exception { assertThat(parseCookie(50000L, "a=b; Max-Age=1").getExpiresAt()) .isEqualTo(51000L); assertThat(parseCookie(50000L, "a=b; Max-Age=9223372036854724").getExpiresAt()) .isEqualTo(MAX_DATE); assertThat(parseCookie(50000L, "a=b; Max-Age=9223372036854725").getExpiresAt()) .isEqua... |
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... | @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(); } |
Segment2D extends Geometry2D { public ArrayList<Segment2D> getSegmentSplitByPolygon(Polygon2D polygon) { ArrayList<Segment2D> segmentList = new ArrayList<>(); ArrayList<Vector2D> segmentListPoints = new ArrayList<>(); segmentListPoints.add(this.getFirstPoint()); segmentListPoints.addAll(this.getIntersection(polygon)); ... | @Test public void getSegmentSplitByPolygon() throws Exception { Vector2D start = GeometryFactory.createVector(-5,0); Vector2D end = GeometryFactory.createVector(5,0); Segment2D segment = GeometryFactory.createSegment(start, end); ArrayList<Vector2D> nodeArray = new ArrayList<>(); nodeArray.add(GeometryFactory.createVec... |
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 ... | @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.cre... |
FromConfigurationOperation extends GraphOperation { @Override public void callPreProcessing(SimulationState simulationState) { Integer graphId = this.properties.getIntegerProperty(graphIdName); Double precisionSeed = this.properties.getDoubleProperty(precisionSeedName); Boolean insideAreaSeed = this.properties.getBoole... | @Test @Parameters({"/layout_graph_test/FromGraphConfigurationOperation_insideArea_test.xml"}) public void fromConfiguration_loadsSingleVertexInsideArea_WithSuccess(String configurationFile) throws Exception { createConfiguration(configurationFile); SimulationState state = mock(SimulationState.class); graphOperation.cal... |
ZengAdditionalComputations { public static Double calculateTimeToConflictPoint(Vector2D currentPosition, Vector2D currentVelocity, Vector2D otherPosition, Vector2D otherVelocity) { if(currentVelocity.isZero() || otherVelocity.isZero()) { return Double.POSITIVE_INFINITY; } Ray2D currentRay = GeometryFactory.createRay2D(... | @Test public void calculateTimeToConflictPoint() throws Exception { Vector2D curPosition, curVelocity, othPosition, othVelocity; curPosition = GeometryFactory.createVector(0, 0); curVelocity = GeometryFactory.createVector(0, 1); othPosition = GeometryFactory.createVector(2, 2); othVelocity = GeometryFactory.createVecto... |
SightConePerceptionModel extends PerceptionalModel { @Override public boolean isVisible(IPedestrian currentPedestrian, IPedestrian otherPedestrian) { return isVisible(currentPedestrian, otherPedestrian.getPosition()); } void setRadius(double radius); void setAngle(double angle); @Override void callPreProcessing(Simula... | @Test public void isVisible() throws Exception { SightConePerceptionModel sightConePerceptionModelModel = new SightConePerceptionModel(); sightConePerceptionModelModel.setAngle(90); sightConePerceptionModelModel.setRadius(30); Vector2D curPedPos, curPedHead, otherPedPos, otherPedHead; curPedPos = GeometryFactory.create... |
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 cent... | @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, ... |
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 norm... | @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(poin... |
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() * g... | @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(... |
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(Li... | @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.distanceBet... |
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.getDire... | @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.create... |
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 in... | @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(b... |
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(Ve... | @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(bStar... |
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(Vector2... | @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); assertTru... |
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()... | @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.createRa... |
OpenAPIStyleValidatorGradlePlugin implements Plugin<Project> { public void apply(Project project) { project.getTasks().register("openAPIStyleValidator", OpenAPIStyleValidatorTask.class); } void apply(Project project); } | @Test public void pluginRegistersATask() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply("org.openapitools.openapistylevalidator"); assertNotNull(project.getTasks().findByName("openAPIStyleValidator")); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.