target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testRequestWithSerializationException() throws IOException { FullHttpRequest request = createQueryRequest("?points=10&from=1&to=2", createRequestBody(1)); ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class); String message = "mock exception message"; when(serializer.transformRollupData(anyMap(), anySet())).thenThrow(new SerializationException(message)); 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", message, errorResponse.getErrors().get(0).getMessage()); assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId()); assertEquals("Invalid status", HttpResponseStatus.INTERNAL_SERVER_ERROR, argument.getValue().getStatus()); } | @Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { Tracker.getInstance().track(request); final String tenantId = request.headers().get("tenantId"); if (!(request instanceof HttpRequestWithDecodedQueryParams)) { DefaultHandler.sendErrorResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST); return; } final String body = request.content().toString(Constants.DEFAULT_CHARSET); if (body == null || body.isEmpty()) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid body. Expected JSON array of metrics.", HttpResponseStatus.BAD_REQUEST); return; } List<String> locators = new ArrayList<String>(); try { locators.addAll(getLocatorsFromJSONBody(tenantId, body)); } catch (Exception ex) { log.debug(ex.getMessage(), ex); sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); return; } if (locators.size() > maxMetricsPerRequest) { DefaultHandler.sendErrorResponse(ctx, request, "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".", HttpResponseStatus.BAD_REQUEST); return; } HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time(); try { RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams()); Map<Locator, MetricData> results = getRollupByGranularity(tenantId, locators, params.getRange().getStart(), params.getRange().getStop(), params.getGranularity(tenantId)); JSONObject metrics = serializer.transformRollupData(results, params.getStats()); final JsonElement element = parser.parse(metrics.toString()); final String jsonStringRep = gson.toJson(element); sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK); } catch (InvalidRequestException e) { log.debug(e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (SerializationException e) { log.debug(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { log.error(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpBatchMetricsFetchTimerContext.stop(); } } | 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 HttpRequestWithDecodedQueryParams)) { DefaultHandler.sendErrorResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST); return; } final String body = request.content().toString(Constants.DEFAULT_CHARSET); if (body == null || body.isEmpty()) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid body. Expected JSON array of metrics.", HttpResponseStatus.BAD_REQUEST); return; } List<String> locators = new ArrayList<String>(); try { locators.addAll(getLocatorsFromJSONBody(tenantId, body)); } catch (Exception ex) { log.debug(ex.getMessage(), ex); sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); return; } if (locators.size() > maxMetricsPerRequest) { DefaultHandler.sendErrorResponse(ctx, request, "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".", HttpResponseStatus.BAD_REQUEST); return; } HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time(); try { RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams()); Map<Locator, MetricData> results = getRollupByGranularity(tenantId, locators, params.getRange().getStart(), params.getRange().getStop(), params.getGranularity(tenantId)); JSONObject metrics = serializer.transformRollupData(results, params.getStats()); final JsonElement element = parser.parse(metrics.toString()); final String jsonStringRep = gson.toJson(element); sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK); } catch (InvalidRequestException e) { log.debug(e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (SerializationException e) { log.debug(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { log.error(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpBatchMetricsFetchTimerContext.stop(); } } } | 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 HttpRequestWithDecodedQueryParams)) { DefaultHandler.sendErrorResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST); return; } final String body = request.content().toString(Constants.DEFAULT_CHARSET); if (body == null || body.isEmpty()) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid body. Expected JSON array of metrics.", HttpResponseStatus.BAD_REQUEST); return; } List<String> locators = new ArrayList<String>(); try { locators.addAll(getLocatorsFromJSONBody(tenantId, body)); } catch (Exception ex) { log.debug(ex.getMessage(), ex); sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); return; } if (locators.size() > maxMetricsPerRequest) { DefaultHandler.sendErrorResponse(ctx, request, "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".", HttpResponseStatus.BAD_REQUEST); return; } HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time(); try { RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams()); Map<Locator, MetricData> results = getRollupByGranularity(tenantId, locators, params.getRange().getStart(), params.getRange().getStop(), params.getGranularity(tenantId)); JSONObject metrics = serializer.transformRollupData(results, params.getStats()); final JsonElement element = parser.parse(metrics.toString()); final String jsonStringRep = gson.toJson(element); sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK); } catch (InvalidRequestException e) { log.debug(e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (SerializationException e) { log.debug(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { log.error(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpBatchMetricsFetchTimerContext.stop(); } } HttpMultiRollupsQueryHandler(); @VisibleForTesting HttpMultiRollupsQueryHandler(BatchedMetricsOutputSerializer<JSONObject> serializer); } | 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 HttpRequestWithDecodedQueryParams)) { DefaultHandler.sendErrorResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST); return; } final String body = request.content().toString(Constants.DEFAULT_CHARSET); if (body == null || body.isEmpty()) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid body. Expected JSON array of metrics.", HttpResponseStatus.BAD_REQUEST); return; } List<String> locators = new ArrayList<String>(); try { locators.addAll(getLocatorsFromJSONBody(tenantId, body)); } catch (Exception ex) { log.debug(ex.getMessage(), ex); sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); return; } if (locators.size() > maxMetricsPerRequest) { DefaultHandler.sendErrorResponse(ctx, request, "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".", HttpResponseStatus.BAD_REQUEST); return; } HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time(); try { RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams()); Map<Locator, MetricData> results = getRollupByGranularity(tenantId, locators, params.getRange().getStart(), params.getRange().getStop(), params.getGranularity(tenantId)); JSONObject metrics = serializer.transformRollupData(results, params.getStats()); final JsonElement element = parser.parse(metrics.toString()); final String jsonStringRep = gson.toJson(element); sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK); } catch (InvalidRequestException e) { log.debug(e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (SerializationException e) { log.debug(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { log.error(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpBatchMetricsFetchTimerContext.stop(); } } HttpMultiRollupsQueryHandler(); @VisibleForTesting HttpMultiRollupsQueryHandler(BatchedMetricsOutputSerializer<JSONObject> serializer); @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); } | 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 HttpRequestWithDecodedQueryParams)) { DefaultHandler.sendErrorResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST); return; } final String body = request.content().toString(Constants.DEFAULT_CHARSET); if (body == null || body.isEmpty()) { DefaultHandler.sendErrorResponse(ctx, request, "Invalid body. Expected JSON array of metrics.", HttpResponseStatus.BAD_REQUEST); return; } List<String> locators = new ArrayList<String>(); try { locators.addAll(getLocatorsFromJSONBody(tenantId, body)); } catch (Exception ex) { log.debug(ex.getMessage(), ex); sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); return; } if (locators.size() > maxMetricsPerRequest) { DefaultHandler.sendErrorResponse(ctx, request, "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".", HttpResponseStatus.BAD_REQUEST); return; } HttpRequestWithDecodedQueryParams requestWithParams = (HttpRequestWithDecodedQueryParams) request; final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time(); try { RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams()); Map<Locator, MetricData> results = getRollupByGranularity(tenantId, locators, params.getRange().getStart(), params.getRange().getStop(), params.getGranularity(tenantId)); JSONObject metrics = serializer.transformRollupData(results, params.getStats()); final JsonElement element = parser.parse(metrics.toString()); final String jsonStringRep = gson.toJson(element); sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK); } catch (InvalidRequestException e) { log.debug(e.getMessage()); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (SerializationException e) { log.debug(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { log.error(e.getMessage(), e); DefaultHandler.sendErrorResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { httpBatchMetricsFetchTimerContext.stop(); } } HttpMultiRollupsQueryHandler(); @VisibleForTesting HttpMultiRollupsQueryHandler(BatchedMetricsOutputSerializer<JSONObject> serializer); @Override void handle(ChannelHandlerContext ctx, FullHttpRequest request); } |
@Test public void enqueuingLessThanMinSizeDoesNotTriggerBatching() { SingleRollupWriteContext srwc1 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc2 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc3 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc4 = mock(SingleRollupWriteContext.class); rbw.enqueueRollupForWrite(srwc1); rbw.enqueueRollupForWrite(srwc2); rbw.enqueueRollupForWrite(srwc3); rbw.enqueueRollupForWrite(srwc4); verify(ctx, times(4)).incrementWriteCounter(); verifyNoMoreInteractions(ctx); verifyZeroInteractions(srwc1); verifyZeroInteractions(srwc2); verifyZeroInteractions(srwc3); verifyZeroInteractions(srwc4); verifyZeroInteractions(executor); } | 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_SIZE) { drainBatch(); } } } | 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_SIZE) { drainBatch(); } } } } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } |
@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()); } | @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); } } | 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); } } } | 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); } } } | 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); } | 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); } |
@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()); } | @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 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 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); } | 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); } | 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; } |
@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()); } | @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 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 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); } | 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); } | 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; } |
@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()); } | @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 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 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); } | 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); } | 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; } |
@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)); } | 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 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 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); } | 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); } | 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; } |
@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()); } | 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 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 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); } | 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); } | 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; } |
@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()); } | @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 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 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); } | 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); } | 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); } |
@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); } } | @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; } | 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; } } | 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; } } | 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); } | 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); } |
@Test public void testFromUnixTimestamp() { long unixTimestamp = nowDateTime().getMillis() / 1000; Assert.assertEquals(DateTimeParser.parse(Long.toString(unixTimestamp)), nowDateTime()); } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@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("_", "")))); } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@Test public void enqueuingMinSizeTriggersCheckOnExecutor() { doReturn(1).when(executor).getActiveCount(); doReturn(1).when(executor).getPoolSize(); SingleRollupWriteContext srwc1 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc2 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc3 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc4 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc5 = mock(SingleRollupWriteContext.class); rbw.enqueueRollupForWrite(srwc1); rbw.enqueueRollupForWrite(srwc2); rbw.enqueueRollupForWrite(srwc3); rbw.enqueueRollupForWrite(srwc4); rbw.enqueueRollupForWrite(srwc5); verify(ctx, times(5)).incrementWriteCounter(); verifyNoMoreInteractions(ctx); verifyZeroInteractions(srwc1); verifyZeroInteractions(srwc2); verifyZeroInteractions(srwc3); verifyZeroInteractions(srwc4); verifyZeroInteractions(srwc5); verify(executor).getActiveCount(); verify(executor).getPoolSize(); verifyNoMoreInteractions(executor); } | 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_SIZE) { drainBatch(); } } } | 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_SIZE) { drainBatch(); } } } } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } |
@Test public void testNowKeyword() { String nowTimestamp = "now"; Assert.assertEquals(DateTimeParser.parse(nowTimestamp), nowDateTime()); } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@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)); } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@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)); } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@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)); } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@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); } } | 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()); } | 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()); } } | 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()); } } | 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); } | 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); } |
@Test public void testRegister() { tracker.register(); verify(loggerMock, times(1)).info("MBean registered as com.rackspacecloud.blueflood.tracker:type=Tracker"); } | 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); } } | 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); } } } | 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(); } | 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); } | 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; } |
@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 ) ); } | public void addTenant(String tenantId) { tenantIds.add(tenantId); log.info("[TRACKER] tenantId " + tenantId + " added."); } | Tracker implements TrackerMBean { public void addTenant(String tenantId) { tenantIds.add(tenantId); log.info("[TRACKER] tenantId " + tenantId + " added."); } } | Tracker implements TrackerMBean { public void addTenant(String tenantId) { tenantIds.add(tenantId); log.info("[TRACKER] tenantId " + tenantId + " added."); } private 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 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); } | 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; } |
@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 ) ); } | public void removeTenant(String tenantId) { tenantIds.remove(tenantId); log.info("[TRACKER] tenantId " + tenantId + " removed."); } | Tracker implements TrackerMBean { public void removeTenant(String tenantId) { tenantIds.remove(tenantId); log.info("[TRACKER] tenantId " + tenantId + " removed."); } } | Tracker implements TrackerMBean { public void removeTenant(String tenantId) { tenantIds.remove(tenantId); log.info("[TRACKER] tenantId " + tenantId + " removed."); } private Tracker(); } | 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); } | 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; } |
@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")); } | public void removeAllMetricNames() { metricNames.clear(); log.info("[TRACKER] All metric names removed."); } | Tracker implements TrackerMBean { public void removeAllMetricNames() { metricNames.clear(); log.info("[TRACKER] All metric names removed."); } } | Tracker implements TrackerMBean { public void removeAllMetricNames() { metricNames.clear(); log.info("[TRACKER] All metric names removed."); } private Tracker(); } | 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); } | 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; } |
@Test public void testFindTidFound() { assertEquals( tracker.findTid( "/v2.0/6000/views" ), "6000" ); } | String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } private Tracker(); } | 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); } | 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; } |
@Test public void enqueuingMinSizeAndThreadPoolNotSaturatedTriggersBatching() throws Exception { doReturn(0).when(executor).getActiveCount(); doReturn(1).when(executor).getPoolSize(); SingleRollupWriteContext srwc1 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc2 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc3 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc4 = mock(SingleRollupWriteContext.class); SingleRollupWriteContext srwc5 = mock(SingleRollupWriteContext.class); Points<SimpleNumber> points = new Points<SimpleNumber>(); Rollup rollup = Rollup.BasicFromRaw.compute(points); doReturn(rollup).when(srwc1).getRollup(); doReturn(rollup).when(srwc2).getRollup(); doReturn(rollup).when(srwc3).getRollup(); doReturn(rollup).when(srwc4).getRollup(); doReturn(rollup).when(srwc5).getRollup(); rbw.enqueueRollupForWrite(srwc1); rbw.enqueueRollupForWrite(srwc2); rbw.enqueueRollupForWrite(srwc3); rbw.enqueueRollupForWrite(srwc4); rbw.enqueueRollupForWrite(srwc5); verify(ctx, times(5)).incrementWriteCounter(); verifyNoMoreInteractions(ctx); verify(executor).getActiveCount(); verify(executor).getPoolSize(); verify(executor).execute(Matchers.<Runnable>any()); verifyNoMoreInteractions(executor); } | 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_SIZE) { drainBatch(); } } } | 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_SIZE) { drainBatch(); } } } } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } |
@Test public void testTrackTenantNoVersion() { assertEquals( tracker.findTid( "/6000/views" ), null ); } | String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } private Tracker(); } | 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); } | 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; } |
@Test public void testTrackTenantBadVersion() { assertEquals( tracker.findTid( "blah/6000/views" ), null ); } | String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } private Tracker(); } | 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); } | 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; } |
@Test public void testTrackTenantTrailingSlash() { assertEquals( tracker.findTid( "/v2.0/6000/views/" ), "6000" ); } | String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } } | Tracker implements TrackerMBean { String findTid( String uri ) { Matcher m = patternGetTid.matcher( uri ); if( m.matches() ) return m.group( 1 ); else return null; } private Tracker(); } | 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); } | 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; } |
@Test public void testSetIsTrackingDelayedMetrics() { tracker.resetIsTrackingDelayedMetrics(); tracker.setIsTrackingDelayedMetrics(); Assert.assertTrue("isTrackingDelayedMetrics should be true from setIsTrackingDelayedMetrics", tracker.getIsTrackingDelayedMetrics()); } | public void setIsTrackingDelayedMetrics() { isTrackingDelayedMetrics = true; log.info("[TRACKER] Tracking delayed metrics started"); } | Tracker implements TrackerMBean { public void setIsTrackingDelayedMetrics() { isTrackingDelayedMetrics = true; log.info("[TRACKER] Tracking delayed metrics started"); } } | Tracker implements TrackerMBean { public void setIsTrackingDelayedMetrics() { isTrackingDelayedMetrics = true; log.info("[TRACKER] Tracking delayed metrics started"); } private Tracker(); } | 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); } | 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; } |
@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); } | 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); } } | 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); } } } | 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(); } | 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); } | 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; } |
@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")); } | 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); } } } | 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); } } } } | 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(); } | 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); } | 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; } |
@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")); } | 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); } } | 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); } } } | 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(); } | 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); } | 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; } |
@Test public void enqueuingMaxSizeTriggersBatching() throws Exception { doReturn(1).when(executor).getActiveCount(); doReturn(1).when(executor).getPoolSize(); SingleRollupWriteContext[] srwcs = new SingleRollupWriteContext[100]; int i; for (i = 0; i < 100; i++) { srwcs[i] = mock(SingleRollupWriteContext.class); Points<SimpleNumber> points = new Points<SimpleNumber>(); Rollup rollup = Rollup.BasicFromRaw.compute(points); doReturn(rollup).when(srwcs[i]).getRollup(); } for (i = 0; i < 100; i++) { rbw.enqueueRollupForWrite(srwcs[i]); } verify(ctx, times(100)).incrementWriteCounter(); verifyNoMoreInteractions(ctx); verify(executor, times(96)).getActiveCount(); verify(executor, times(96)).getPoolSize(); verify(executor).execute(Matchers.<Runnable>any()); verifyNoMoreInteractions(executor); } | 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_SIZE) { drainBatch(); } } } | 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_SIZE) { drainBatch(); } } } } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } | 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_SIZE) { drainBatch(); } } } RollupBatchWriter(ThreadPoolExecutor executor, RollupExecutionContext context); void enqueueRollupForWrite(SingleRollupWriteContext rollupWriteContext); synchronized void drainBatch(); } |
@Test public void drainBatchWithNoItemsDoesNotTriggerBatching() { rbw.drainBatch(); verifyZeroInteractions(ctx); verifyZeroInteractions(executor); } | 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 { 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 { 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); } | 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(); } | 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(); } |
@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"); } } | private Configuration() { try { init(); } catch (IOException ex) { throw new RuntimeException(ex); } } | Configuration { private Configuration() { try { init(); } catch (IOException ex) { throw new RuntimeException(ex); } } } | Configuration { private Configuration() { try { init(); } catch (IOException ex) { throw new RuntimeException(ex); } } private Configuration(); } | 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); } | 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); } |
@Test public void testMultipleCommaSeparatedItemsShouldYieldTheSameNumberOfElements() { String[] expected = { "a", "b", "c" }; List<String> actual = Configuration.stringListFromString("a,b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } | public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } | Configuration { public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } } | 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(); } | 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); } | 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); } |
@Test public void testWhitespaceBetweenElementsIsNotSignificant() { String[] expected = { "a", "b", "c" }; List<String> actual = Configuration.stringListFromString("a, b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } | public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } | Configuration { public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } } | 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(); } | 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); } | 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); } |
@Test public void testLeadingWhitespaceIsKept() { String[] expected = { " a", "b", "c" }; List<String> actual = Configuration.stringListFromString(" a,b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } | public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } | Configuration { public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } } | 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(); } | 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); } | 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); } |
@Test public void testTrailingWhitespaceIsKept() { String[] expected = { "a", "b", "c " }; List<String> actual = Configuration.stringListFromString("a,b,c "); Assert.assertArrayEquals(expected, actual.toArray()); } | public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } | Configuration { public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } } | 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(); } | 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); } | 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); } |
@Test public void testSlotFromStateCol() { Assert.assertEquals(1, serDes.slotFromStateCol("metrics_full,1,okay")); } | protected static int slotFromStateCol(String s) { return Integer.parseInt(s.split(",", -1)[1]); } | SlotStateSerDes { protected static int slotFromStateCol(String s) { return Integer.parseInt(s.split(",", -1)[1]); } } | SlotStateSerDes { protected static int slotFromStateCol(String s) { return Integer.parseInt(s.split(",", -1)[1]); } } | 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); } | 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 testConsecutiveCommasDontProduceEmptyElements() { String[] expected = { "a", "b", "c" }; List<String> actual = Configuration.stringListFromString("a,,,b,c"); Assert.assertArrayEquals(expected, actual.toArray()); } | public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } | Configuration { public static List<String> stringListFromString(String value) { List<String> list = Lists.newArrayList(value.split("\\s*,\\s*")); list.removeAll(Arrays.asList("", null)); return list; } } | 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(); } | 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); } | 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); } |
@Test public void testNullShouldBeInterpretedAsBooleanFalse() { Assert.assertFalse(Configuration.booleanFromString(null)); } | public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } | Configuration { public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } } | Configuration { public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } private Configuration(); } | 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); } | 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); } |
@Test public void test_TRUE_ShouldBeInterpretedAsBooleanTrue() { Assert.assertTrue(Configuration.booleanFromString("TRUE")); } | public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } | Configuration { public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } } | Configuration { public static boolean booleanFromString(String value) { return "true".equalsIgnoreCase(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testIntegerOneShouldBeInterpretedAsOne() { Assert.assertEquals(1, Configuration.intFromString("1")); } | public static int intFromString(String value) { return Integer.parseInt(value); } | Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } } | Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testIntegerLeadingWhitespaceShouldBeIgnored() { int value = Configuration.intFromString(" 1"); } | public static int intFromString(String value) { return Integer.parseInt(value); } | Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } } | Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testIntegerTrailingWhitespaceShouldBeIgnored() { int value = Configuration.intFromString("1 "); } | public static int intFromString(String value) { return Integer.parseInt(value); } | Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } } | Configuration { public static int intFromString(String value) { return Integer.parseInt(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testLongOneShouldBeInterpretedAsOne() { Assert.assertEquals(1L, Configuration.longFromString("1")); } | public static long longFromString(String value) { return Long.parseLong(value); } | Configuration { public static long longFromString(String value) { return Long.parseLong(value); } } | Configuration { public static long longFromString(String value) { return Long.parseLong(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testLongLeadingWhitespaceShouldBeRejected() { long value = Configuration.longFromString(" 1"); } | public static long longFromString(String value) { return Long.parseLong(value); } | Configuration { public static long longFromString(String value) { return Long.parseLong(value); } } | Configuration { public static long longFromString(String value) { return Long.parseLong(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testLongTrailingWhitespaceShouldBeRejected() { long value = Configuration.longFromString("1 "); } | public static long longFromString(String value) { return Long.parseLong(value); } | Configuration { public static long longFromString(String value) { return Long.parseLong(value); } } | Configuration { public static long longFromString(String value) { return Long.parseLong(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testFloatOneShouldBeInterpretedAsOne() { Assert.assertEquals(1.0f, Configuration.floatFromString("1"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testStateFromStateCol() { Assert.assertEquals("okay", serDes.stateCodeFromStateCol("metrics_full,1,okay")); } | protected static String stateCodeFromStateCol(String s) { return s.split(",", -1)[2]; } | SlotStateSerDes { protected static String stateCodeFromStateCol(String s) { return s.split(",", -1)[2]; } } | SlotStateSerDes { protected static String stateCodeFromStateCol(String s) { return s.split(",", -1)[2]; } } | 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); } | 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 testFloatExtendedFormat() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1.1e3"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceBeforeDotIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1 .1e3"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceAfterDotIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1. 1e3"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceBeforeExponentMarkerIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1.1 e3"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test(expected=NumberFormatException.class) public void testFloatExtendedFormatSpaceAfterExponentMarkerIsInvalid() { Assert.assertEquals(-1100.0f, Configuration.floatFromString("-1.1e 3"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testFloatLeadingWhitespaceShouldBeIgnored() { Assert.assertEquals(1.0f, Configuration.floatFromString(" 1"), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testFloatTrailingWhitespaceShouldBeIgnored() { Assert.assertEquals(1.0f, Configuration.floatFromString("1 "), 0.00001f); } | public static float floatFromString(String value) { return Float.parseFloat(value); } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } } | Configuration { public static float floatFromString(String value) { return Float.parseFloat(value); } private Configuration(); } | 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); } | 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); } |
@Test public void testStringConversion() { Assert.assertEquals(s1 + ": ", ss1.toString()); Assert.assertEquals(s2 + ": " + time, ss2.toString()); Assert.assertEquals(s3 + ": " + time, ss3.toString()); } | 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 { 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 { 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 { 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(); } | 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(); } |
@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)); } | public SlotState withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } | SlotState { public SlotState withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } } | SlotState { public SlotState withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } SlotState(Granularity g, int slot, UpdateStamp.State state); SlotState(); } | 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(); } | 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(); } |
@Test public void testGranularity() { Assert.assertEquals(Granularity.FULL, fromString(s1).getGranularity()); Assert.assertNull(fromString("FULL,1,X").getGranularity()); } | public Granularity getGranularity() { return granularity; } | SlotState { public Granularity getGranularity() { return granularity; } } | SlotState { public Granularity getGranularity() { return granularity; } SlotState(Granularity g, int slot, UpdateStamp.State state); 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 getGranularity(); int getSlot(); UpdateStamp.State getState(); Long getTimestamp(); long getLastUpdatedTimestamp(); } | 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(); } |
@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")); } | protected static UpdateStamp.State stateFromCode(String stateCode) { if (stateCode.equals(UpdateStamp.State.Rolled.code())) { return UpdateStamp.State.Rolled; } else { return UpdateStamp.State.Active; } } | SlotStateSerDes { protected static UpdateStamp.State stateFromCode(String stateCode) { if (stateCode.equals(UpdateStamp.State.Rolled.code())) { return UpdateStamp.State.Rolled; } else { return UpdateStamp.State.Active; } } } | SlotStateSerDes { protected static UpdateStamp.State stateFromCode(String stateCode) { if (stateCode.equals(UpdateStamp.State.Rolled.code())) { return UpdateStamp.State.Rolled; } else { return UpdateStamp.State.Active; } } } | 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); } | 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); } |
@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(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@Test(expected = BluefloodServiceStarterException.class) public void testNoCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); BluefloodServiceStarter.validateCassandraHosts(); } | 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>"); } } } | 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>"); } } } } | 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>"); } } } } | 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(); } | 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(); } |
@Test(expected = BluefloodServiceStarterException.class) public void testInvalidCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "something"); BluefloodServiceStarter.validateCassandraHosts(); } | 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>"); } } } | 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>"); } } } } | 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>"); } } } } | 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(); } | 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(); } |
@Test(expected = BluefloodServiceStarterException.class) public void testCassandraHostWithoutPortFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "127.0.0.1"); BluefloodServiceStarter.validateCassandraHosts(); } | 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>"); } } } | 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>"); } } } } | 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>"); } } } } | 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(); } | 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(); } |
@Test public void testCassandraHostWithHyphenSucceedsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "my-hostname:9160"); BluefloodServiceStarter.validateCassandraHosts(); } | 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>"); } } } | 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>"); } } } } | 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>"); } } } } | 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(); } | 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(); } |
@Test public void testCassandraHostWithUnderscoreSucceedsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "my_hostname:9160"); BluefloodServiceStarter.validateCassandraHosts(); } | 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>"); } } } | 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>"); } } } } | 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>"); } } } } | 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(); } | 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(); } |
@Test(expected = BluefloodServiceStarterException.class) public void testIngestModeEnabledWithoutModules() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.INGEST_MODE, "true"); config.setProperty(CoreConfig.INGESTION_MODULES, ""); BluefloodServiceStarter.run(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@Test public void testIngestModeEnabledWithModules() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.INGEST_MODE, "true"); config.setProperty(CoreConfig.INGESTION_MODULES, "com.rackspacecloud.blueflood.service.DummyIngestionService"); BluefloodServiceStarter.run(); assertNotNull(DummyIngestionService.getInstances()); assertEquals(1, DummyIngestionService.getInstances().size()); assertNotNull(DummyIngestionService.getMostRecentInstance()); assertTrue(DummyIngestionService.getMostRecentInstance().getStartServiceCalled()); assertFalse(DummyIngestionService.getMostRecentInstance().getShutdownServiceCalled()); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@Test(expected = BluefloodServiceStarterException.class) public void testQueryModeEnabledWithoutModules() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.QUERY_MODE, "true"); config.setProperty(CoreConfig.QUERY_MODULES, ""); BluefloodServiceStarter.run(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@Test public void testQueryModeEnabledWithDummyModule() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.QUERY_MODE, "true"); config.setProperty(CoreConfig.QUERY_MODULES, "com.rackspacecloud.blueflood.service.DummyQueryService"); BluefloodServiceStarter.run(); assertNotNull(DummyQueryService.getInstances()); assertEquals(1, DummyQueryService.getInstances().size()); assertNotNull(DummyQueryService.getMostRecentInstance()); assertTrue(DummyQueryService.getMostRecentInstance().getStartServiceCalled()); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@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)); } | 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 { 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 { 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); } | 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); } | 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); } |
@Test public void testRollupModeEnabled() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.ROLLUP_MODE, "true"); BluefloodServiceStarter.run(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@Test public void testEventListenerServiceEnabledWithDummyModule() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.EVENT_LISTENER_MODULES, "com.rackspacecloud.blueflood.service.DummyEventListenerService"); BluefloodServiceStarter.run(); assertNotNull(DummyEventListenerService.getInstances()); assertEquals(1, DummyEventListenerService.getInstances().size()); assertNotNull(DummyEventListenerService.getMostRecentInstance()); assertTrue(DummyEventListenerService.getMostRecentInstance().getStartServiceCalled()); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } | 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); } validateCassandraHosts(); boolean usePersistedCache = Configuration.getInstance().getBooleanProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_ENABLED); if (usePersistedCache) { String path = Configuration.getInstance().getStringProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PATH); final File cacheLocation = new File(path); if (cacheLocation.exists()) { try { DataInputStream in = new DataInputStream(new FileInputStream(cacheLocation)); MetadataCache.getInstance().load(in); in.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } else { log.info("Wanted to load metadata cache, but it did not exist: " + path); } Timer cachePersistenceTimer = new Timer("Metadata-Cache-Persistence"); int savePeriodMins = Configuration.getInstance().getIntegerProperty(CoreConfig.METADATA_CACHE_PERSISTENCE_PERIOD_MINS); cachePersistenceTimer.schedule(new TimerTask() { @Override public void run() { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(cacheLocation, false)); MetadataCache.getInstance().save(out); out.close(); } catch (IOException ex) { log.error(ex.getMessage(), ex); } } }, TimeUnit.MINUTES.toMillis(savePeriodMins), TimeUnit.MINUTES.toMillis(savePeriodMins)); } new RestartGauge(getRegistry(), RollupService.class); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final boolean rollupMode = config.getBooleanProperty(CoreConfig.ROLLUP_MODE); final ScheduleContext rollupContext = !"NONE".equals(zkCluster) && rollupMode ? new ScheduleContext(System.currentTimeMillis(), shards, zkCluster) : new ScheduleContext(System.currentTimeMillis(), shards); log.info("Starting blueflood services"); startShardStateServices(rollupContext); startIngestServices(rollupContext); startQueryServices(); startRollupService(rollupContext); startEventListenerModules(); log.info("All blueflood services started"); } static void validateCassandraHosts(); static void main(String args[]); static void run(); static MetricRegistry getRegistry(); } |
@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 newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Active, lastCollectionTime, lastUpdatedTime); slotStateManager.updateSlotOnRead(newUpdateForActiveSlot); Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps(); UpdateStamp updateStamp = slotStamps.get(TEST_SLOT); assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState()); assertEquals("Last collection timestamp is incorrect", lastCollectionTime, updateStamp.getTimestamp()); assertEquals("Last rollup timestamp is incorrect", lastRollupTime, updateStamp.getLastRollupTimestamp()); assertEquals("Last ingest timestamp is incorrect", lastUpdatedTime, updateStamp.getLastIngestTimestamp()); } | public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } | ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } } | 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 clock); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); static final long REROLL_TIME_SPAN_ASSUMED_VALUE; } |
@Test public void testUpdateSlotsOnReadWithIncomingActiveStateButOlderData() { establishCurrentState(); final long lastRollupTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastRollupTimestamp(); final long existingLastCollectionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp(); final long existingLastIngestTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastIngestTimestamp(); long lastCollectionTime = existingLastCollectionTime - 60 * 1000; long lastUpdatedTime = System.currentTimeMillis(); SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Active, lastCollectionTime, lastUpdatedTime); slotStateManager.updateSlotOnRead(newUpdateForActiveSlot); Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps(); UpdateStamp updateStamp = slotStamps.get(TEST_SLOT); assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState()); assertEquals("Last collection timestamp is incorrect", existingLastCollectionTime, updateStamp.getTimestamp()); assertEquals("Last rollup timestamp is incorrect", lastRollupTime, updateStamp.getLastRollupTimestamp()); assertEquals("Dirty flag is incorrect", true, updateStamp.isDirty()); assertEquals("Last ingest timestamp is incorrect", existingLastIngestTime, updateStamp.getLastIngestTimestamp()); } | public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } | ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } } | 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 clock); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); static final long REROLL_TIME_SPAN_ASSUMED_VALUE; } |
@Test public void testUpdateSlotsOnReadWithIncomingActiveStateButInMemoryDirtyData() { establishCurrentState(); final long lastRollupTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastRollupTimestamp(); final long existingLastCollectionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp(); final long existingLastIngestTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastIngestTimestamp(); slotStateManager.getSlotStamps().get(TEST_SLOT).setDirty(true); long lastCollectionTime = existingLastCollectionTime + 60 * 1000; long lastUpdatedTime = System.currentTimeMillis(); SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Active, lastCollectionTime, lastUpdatedTime); slotStateManager.updateSlotOnRead(newUpdateForActiveSlot); Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps(); UpdateStamp updateStamp = slotStamps.get(TEST_SLOT); assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState()); assertEquals("Last collection timestamp is incorrect", existingLastCollectionTime, updateStamp.getTimestamp()); assertEquals("Last rollup timestamp is incorrect", lastRollupTime, updateStamp.getLastRollupTimestamp()); assertEquals("Dirty flag is incorrect", true, updateStamp.isDirty()); assertEquals("Last ingest timestamp is incorrect", existingLastIngestTime, updateStamp.getLastIngestTimestamp()); } | public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } | ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } } | 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 clock); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); static final long REROLL_TIME_SPAN_ASSUMED_VALUE; } |
@Test public void testUpdateSlotsOnReadIncomingRolledStateSameTimestamp() { establishCurrentState(); final long existingLastCollectionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp(); final long existingLastIngestTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastIngestTimestamp(); final long newRolledSlotLastUpdatedTime = System.currentTimeMillis(); SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Rolled, existingLastCollectionTime, newRolledSlotLastUpdatedTime); slotStateManager.updateSlotOnRead(newUpdateForActiveSlot); Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps(); UpdateStamp updateStamp = slotStamps.get(TEST_SLOT); assertEquals("Unexpected state", UpdateStamp.State.Rolled, updateStamp.getState()); assertEquals("Last collection timestamp is incorrect", existingLastCollectionTime, updateStamp.getTimestamp()); assertEquals("Last rollup timestamp is incorrect", newRolledSlotLastUpdatedTime, updateStamp.getLastRollupTimestamp()); assertEquals("Last ingest timestamp is incorrect", existingLastIngestTime, updateStamp.getLastIngestTimestamp()); } | public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } | ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } } | 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 clock); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); static final long REROLL_TIME_SPAN_ASSUMED_VALUE; } |
@Test public void testUpdateSlotsOnReadIncomingRolledStateDifferentTimestamp() { establishCurrentState(); final long existingLastCollectionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp(); final long existingLastIngestTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastIngestTimestamp(); final long newLastRolledCollectionTime = existingLastCollectionTime - 1; final long newRolledSlotLastUpdatedTime = System.currentTimeMillis(); SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Rolled, newLastRolledCollectionTime, newRolledSlotLastUpdatedTime); slotStateManager.updateSlotOnRead(newUpdateForActiveSlot); Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps(); UpdateStamp updateStamp = slotStamps.get(TEST_SLOT); assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState()); assertEquals("Last collection timestamp is incorrect", existingLastCollectionTime, updateStamp.getTimestamp()); assertEquals("Last rollup timestamp is incorrect", newRolledSlotLastUpdatedTime, updateStamp.getLastRollupTimestamp()); assertEquals("Last ingest timestamp is incorrect", existingLastIngestTime, updateStamp.getLastIngestTimestamp()); } | public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } | ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } } | 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 clock); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); static final long REROLL_TIME_SPAN_ASSUMED_VALUE; } |
@Test public void testUpdateSlotsOnReadIncomingOldRolledState() { establishCurrentState(); final long existingLastCollectionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp(); final long existingLastRollupTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastRollupTimestamp(); final long existingLastIngestTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastIngestTimestamp(); final long oldLastRolledCollectionTime = existingLastCollectionTime - 1; final long oldRolledSlotLastUpdatedTime = System.currentTimeMillis() - 14 * 24 * 60 * 60 * 1000; SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Rolled, oldLastRolledCollectionTime, oldRolledSlotLastUpdatedTime); slotStateManager.updateSlotOnRead(newUpdateForActiveSlot); Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps(); UpdateStamp updateStamp = slotStamps.get(TEST_SLOT); assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState()); assertEquals("Last collection timestamp is incorrect", existingLastCollectionTime, updateStamp.getTimestamp()); assertEquals("Last rollup timestamp is incorrect", existingLastRollupTime, updateStamp.getLastRollupTimestamp()); assertEquals("Last ingest timestamp is incorrect", existingLastIngestTime, updateStamp.getLastIngestTimestamp()); } | public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } | ShardStateManager { public void updateSlotOnRead(int shard, SlotState slotState) { getSlotStateManager(shard, slotState.getGranularity()).updateSlotOnRead(slotState); } } | 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 clock); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); } | 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 clock); SlotStateManager getSlotStateManager(int shard, Granularity granularity); void updateSlotOnRead(int shard, SlotState slotState); void setAllCoarserSlotsDirtyForSlot(SlotKey slotKey); static final long REROLL_TIME_SPAN_ASSUMED_VALUE; } |
@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); } | @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 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 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); } | 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(); } | 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(); } |
@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); } | @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 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 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); } | 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(); } | 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(); } |
@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); } | @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 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 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); } | 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(); } | 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(); } |
@Test public void getLocatorsReturnsLocators() throws IOException { Set<Locator> expected = new HashSet<Locator>(locators); when(locatorIO.getLocators(TEST_SHARD)).thenReturn(locators); Set<Locator> actual = lfr.getLocators(executionContext); verify(locatorIO, times(1)).getLocators(TEST_SHARD); verifyNoMoreInteractions(locatorIO); verifyZeroInteractions(executionContext); Assert.assertEquals(expected, actual); } | protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } LocatorFetchRunnable(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExecutor,
ThreadPoolExecutor rollupWriteExecutor); } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } 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); } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } 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); } |
@Test public void getLocatorsExceptionYieldsEmptySet() throws IOException { when(locatorIO.getLocators(TEST_SHARD)).thenThrow(new RuntimeException("")); Set<Locator> actual = lfr.getLocators(executionContext); verify(locatorIO, times(1)).getLocators(TEST_SHARD); verifyNoMoreInteractions(locatorIO); verify(executionContext, times(1)).markUnsuccessful(Matchers.<Throwable>any()); verifyNoMoreInteractions(executionContext); assertNotNull(actual); Assert.assertEquals(0, actual.size()); } | protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } LocatorFetchRunnable(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExecutor,
ThreadPoolExecutor rollupWriteExecutor); } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } 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); } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } 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); } |
@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); } | 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 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 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); } | 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); } | 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); } |
@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(); } | 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 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 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); } | 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); } | 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); } |
@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(); } | 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 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 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); } | 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); } | 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); } |
@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(); } | 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 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 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); } | 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); } | 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); } |
@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); } | 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 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 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); } | 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); } | 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); } |
@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); } | 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 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 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); } | 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); } | 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); } |
@Test public void createRollupExecutionContextReturnsValidObject() { RollupExecutionContext execCtx = lfr.createRollupExecutionContext(); assertNotNull(execCtx); } | protected RollupExecutionContext createRollupExecutionContext() { return new RollupExecutionContext(Thread.currentThread()); } | LocatorFetchRunnable implements Runnable { protected RollupExecutionContext createRollupExecutionContext() { return new RollupExecutionContext(Thread.currentThread()); } } | LocatorFetchRunnable implements Runnable { protected RollupExecutionContext createRollupExecutionContext() { return new RollupExecutionContext(Thread.currentThread()); } LocatorFetchRunnable(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExecutor,
ThreadPoolExecutor rollupWriteExecutor); } | 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); } | 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); } |
@Test public void testGetLocatorsForRegularRollup() throws IOException { boolean isReroll = false; SlotKey destSlotKey = SlotKey.of(Granularity.MIN_20, 0, TEST_SHARD); Granularity delayedMetricsRerollGranularity = Granularity.MIN_20; Granularity delayedMetricsStorageGranularity = Granularity.MIN_20; LocatorFetchRunnable lfrunnable = new LocatorFetchRunnable(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor); when(scheduleCtx.isReroll(any(SlotKey.class))).thenReturn(isReroll); when(locatorIO.getLocators(anyInt())).thenReturn(locators); Set<Locator> locatorsForRollup = lfrunnable.getLocators(executionContext, isReroll, delayedMetricsRerollGranularity, delayedMetricsStorageGranularity); assertEquals(locators.size(), locatorsForRollup.size()); } | protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } LocatorFetchRunnable(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExecutor,
ThreadPoolExecutor rollupWriteExecutor); } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } 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); } | LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } 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); } |
@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); } | @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 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 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); } | 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(); } | 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(); } |
@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: } | 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); } | 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); } } | 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); } } | 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); } | 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); } |
@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()); } | 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; } | 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; } } | 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; } } | 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); } | 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); } |
@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)); } | public static boolean isSnapshot(Version version) { Assert.notNull(version, "Version must not be null."); return version.toString().endsWith(SNAPSHOT_SUFFIX); } | Versions { public static boolean isSnapshot(Version version) { Assert.notNull(version, "Version must not be null."); return version.toString().endsWith(SNAPSHOT_SUFFIX); } } | Versions { public static boolean isSnapshot(Version version) { Assert.notNull(version, "Version must not be null."); return version.toString().endsWith(SNAPSHOT_SUFFIX); } } | 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); } | 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); } |
@Test public void testIsApiCompatible0() throws Exception { Assert.assertTrue(Versions.isApiCompatible( SingleVersion.valueOf("2.18.2-SNAPSHOT"), SingleVersion.valueOf("2.16.1.Final"))); } | 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); } | 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); } } | 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); } } | 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); } | 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); } |
@Test public void testIsApiCompatible1() throws Exception { Assert.assertTrue(Versions.isApiCompatible( SingleVersion.valueOf("2.18.2.Final"), SingleVersion.valueOf("2.16.1.Final"))); } | 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); } | 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); } } | 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); } } | 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); } | 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); } |
@Test(expected = IllegalArgumentException.class) public void testVersionMustNotBeNull() { SingleVersion.valueOf(null); } | 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; } | 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; } } | 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); } | 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(); } | 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(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.