focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public double calculateAveragePercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) { int skippedResourceTypes = 0; double total = 0.0; if (usedMemoryMb > totalMemoryMb) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } if (totalMemoryMb != 0.0) { total += usedMemoryMb / totalMemoryMb; } else { skippedResourceTypes++; } double totalCpu = getTotalCpu(); if (used.getTotalCpu() > getTotalCpu()) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } if (totalCpu != 0.0) { total += used.getTotalCpu() / getTotalCpu(); } else { skippedResourceTypes++; } if (used.otherResources.length > otherResources.length) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } for (int i = 0; i < otherResources.length; i++) { double totalValue = otherResources[i]; double usedValue; if (i >= used.otherResources.length) { //Resources missing from used are using none of that resource usedValue = 0.0; } else { usedValue = used.otherResources[i]; } if (usedValue > totalValue) { throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb); } if (totalValue == 0.0) { //Skip any resources where the total is 0, the percent used for this resource isn't meaningful. //We fall back to prioritizing by cpu, memory and any other resources by ignoring this value skippedResourceTypes++; continue; } total += usedValue / totalValue; } //Adjust the divisor for the average to account for any skipped resources (those where the total was 0) int divisor = 2 + otherResources.length - skippedResourceTypes; if (divisor == 0) { /* * This is an arbitrary choice to make the result consistent with calculateMin. Any value would be valid here, becase there are * no (non-zero) resources in the total set of resources, so we're trying to average 0 values. */ return 100.0; } else { return (total * 100.0) / divisor; } }
@Test public void testCalculateAvgUsageWithNoResourcesInTotal() { NormalizedResources resources = new NormalizedResources(normalize(Collections.emptyMap())); NormalizedResources usedResources = new NormalizedResources(normalize(Collections.emptyMap())); double avg = resources.calculateAveragePercentageUsedBy(usedResources, 0, 0); assertThat(avg, is(100.0)); }
public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ((GetJobReportResponse) invoke("getJobReport", GetJobReportRequest.class, request)).getJobReport(); JobStatus jobStatus = null; if (report != null) { if (StringUtils.isEmpty(report.getJobFile())) { String jobFile = MRApps.getJobFile(conf, report.getUser(), oldJobID); report.setJobFile(jobFile); } String historyTrackingUrl = report.getTrackingUrl(); String url = StringUtils.isNotEmpty(historyTrackingUrl) ? historyTrackingUrl : trackingUrl; jobStatus = TypeConverter.fromYarn(report, url); } return jobStatus; }
@Test public void testRetriesOnConnectionFailure() throws Exception { MRClientProtocol historyServerProxy = mock(MRClientProtocol.class); when(historyServerProxy.getJobReport(getJobReportRequest())).thenThrow( new RuntimeException("1")).thenThrow(new RuntimeException("2")) .thenReturn(getJobReportResponse()); ResourceMgrDelegate rm = mock(ResourceMgrDelegate.class); when(rm.getApplicationReport(TypeConverter.toYarn(oldJobId).getAppId())) .thenReturn(null); ClientServiceDelegate clientServiceDelegate = getClientServiceDelegate( historyServerProxy, rm); JobStatus jobStatus = clientServiceDelegate.getJobStatus(oldJobId); Assert.assertNotNull(jobStatus); verify(historyServerProxy, times(3)).getJobReport( any(GetJobReportRequest.class)); }
static String isHostParam(final String given) { final String hostUri = StringHelper.notEmpty(given, "host"); final Matcher matcher = HOST_PATTERN.matcher(given); if (!matcher.matches()) { throw new IllegalArgumentException( "host must be an absolute URI (e.g. http://api.example.com), given: `" + hostUri + "`"); } return hostUri; }
@Test public void shouldReturnUriParameter() { assertThat(RestOpenApiHelper.isHostParam("http://api.example.com")).isEqualTo("http://api.example.com"); }
public void printStreamedRow(final StreamedRow row) { row.getErrorMessage().ifPresent(this::printErrorMessage); row.getFinalMessage().ifPresent(finalMsg -> writer().println(finalMsg)); row.getHeader().ifPresent(this::printRowHeader); if (row.getRow().isPresent()) { switch (outputFormat) { case JSON: printAsJson(row.getRow().get()); break; case TABULAR: printAsTable(row.getRow().get()); break; default: throw new RuntimeException(String.format( "Unexpected output format: '%s'", outputFormat.name() )); } } }
@Test public void testPrintDataRow() { // Given: final StreamedRow row = StreamedRow.pushRow(genericRow("col_1", "col_2")); // When: console.printStreamedRow(row); // Then: assertThat(terminal.getOutputString(), containsString("col_1")); assertThat(terminal.getOutputString(), containsString("col_2")); }
public static String nullifyIfEmptyTrimmed(final String input) { if (input == null) { return null; } String trimmed = input.trim(); if (trimmed.length() == 0) { return null; } return trimmed; }
@Test public void testNullifyIfEmptyTrimmed() { assertNull(JOrphanUtils.nullifyIfEmptyTrimmed(null)); assertNull(JOrphanUtils.nullifyIfEmptyTrimmed("\u0001")); assertEquals("1234", JOrphanUtils.nullifyIfEmptyTrimmed("1234")); }
public synchronized LogAction record(double... values) { return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values); }
@Test public void testLoggingWithMultipleValues() { assertTrue(helper.record(1).shouldLog()); for (int i = 0; i < 4; i++) { timer.advance(LOG_PERIOD / 5); int base = i % 2 == 0 ? 0 : 1; assertFalse(helper.record(base, base * 2).shouldLog()); } timer.advance(LOG_PERIOD); LogAction action = helper.record(0.5, 1.0); assertTrue(action.shouldLog()); assertEquals(5, action.getCount()); for (int i = 1; i <= 2; i++) { assertEquals(0.5 * i, action.getStats(i - 1).getMean(), 0.01); assertEquals(1.0 * i, action.getStats(i - 1).getMax(), 0.01); assertEquals(0.0, action.getStats(i - 1).getMin(), 0.01); } }
@Override public double getStdDev() { // two-pass algorithm for variance, avoids numeric overflow if (values.length <= 1) { return 0; } final double mean = getMean(); double sum = 0; for (long value : values) { final double diff = value - mean; sum += diff * diff; } final double variance = sum / (values.length - 1); return Math.sqrt(variance); }
@Test public void calculatesAStdDevOfZeroForASingletonSnapshot() { final Snapshot singleItemSnapshot = new UniformSnapshot(new long[]{1}); assertThat(singleItemSnapshot.getStdDev()) .isZero(); }
@Override public SchemaAndValue get(final ProcessingLogConfig config) { final Struct struct = new Struct(ProcessingLogMessageSchema.PROCESSING_LOG_SCHEMA) .put(ProcessingLogMessageSchema.TYPE, MessageType.SERIALIZATION_ERROR.getTypeId()) .put(ProcessingLogMessageSchema.SERIALIZATION_ERROR, serializationError(config)); return new SchemaAndValue(ProcessingLogMessageSchema.PROCESSING_LOG_SCHEMA, struct); }
@Test public void shouldBuildErrorWithKeyComponent() { // Given: final SerializationError<GenericRow> serError = new SerializationError<>(ERROR, Optional.of(RECORD), TOPIC, true); // When: final SchemaAndValue msg = serError.get(LOGGING_CONFIG); // Then: final Struct struct = (Struct) msg.value(); final Struct serializationError = struct.getStruct(SERIALIZATION_ERROR); assertThat( serializationError.get(SERIALIZATION_ERROR_FIELD_TARGET), equalTo("key") ); }
public static SupportLevel defaultSupportLevel(String firstVersion, String currentVersion) { if (firstVersion == null || firstVersion.isEmpty()) { throw new IllegalArgumentException( "FirstVersion is not specified. This can be done in @UriEndpoint or in pom.xml file."); } // we only want major/minor (strip patch) Version v1 = new Version(firstVersion); v1 = new Version(v1.getMajor() + "." + v1.getMinor()); Version v2 = new Version(currentVersion); v2 = new Version(v2.getMajor() + "." + v2.getMinor()); boolean justNew = CamelVersionHelper.isGE(v2.toString(), v1.toString()); boolean prevNew = CamelVersionHelper.isGE(CamelVersionHelper.prevMinor(v2.toString()), v1.toString()); if (justNew || prevNew) { // its a new component (2 releases back) that is added to this version so lets mark it as preview by default return SupportLevel.Preview; } else { return SupportLevel.Stable; } }
@Test public void testStable() { Assertions.assertNotEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.20.0")); Assertions.assertEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.21.0")); Assertions.assertEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.21.1")); Assertions.assertEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.22.0")); Assertions.assertEquals(SupportLevel.Stable, SupportLevelHelper.defaultSupportLevel("3.19.0", "3.22.3")); }
@Override public String name() { return name; }
@Test public void testValidDomainNameUmlaut() { String name = "ä"; AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { }; assertEquals("xn--4ca.", record.name()); }
@Override public int actionSave(String fileName, String appName, Long lifetime, String queue) throws IOException, YarnException { int result = EXIT_SUCCESS; try { Service service = loadAppJsonFromLocalFS(fileName, appName, lifetime, queue); service.setState(ServiceState.STOPPED); String buffer = jsonSerDeser.toJson(service); ClientResponse response = getApiClient() .post(ClientResponse.class, buffer); result = processResponse(response); } catch (Exception e) { LOG.error("Fail to save application: ", e); result = EXIT_EXCEPTION_THROWN; } return result; }
@Test void testSave() { String fileName = "target/test-classes/example-app.json"; String appName = "example-app"; long lifetime = 3600L; String queue = "default"; try { int result = asc.actionSave(fileName, appName, lifetime, queue); assertEquals(EXIT_SUCCESS, result); } catch (IOException | YarnException e) { fail(); } }
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KSTREAM: return windowed ? buildWindowedStream( buildContext, dataSource, contextStacker ) : buildStream( buildContext, dataSource, contextStacker ); case KTABLE: return windowed ? buildWindowedTable( buildContext, dataSource, contextStacker ) : buildTable( buildContext, dataSource, contextStacker ); default: throw new UnsupportedOperationException("Source type:" + dataSource.getDataSourceType()); } }
@Test public void shouldCreateWindowedStreamSourceWithNewPseudoColumnVersionIfNoOldQuery() { // Given: givenWindowedStream(); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSource, contextStacker ); // Then: assertThat(((WindowedStreamSource) result.getSourceStep()).getPseudoColumnVersion(), equalTo(CURRENT_PSEUDOCOLUMN_VERSION_NUMBER)); assertValidSchema(result); }
@Description("Given a geometry and a zoom level, returns the minimum set of Bing tiles of that zoom level that fully covers that geometry") @ScalarFunction("geometry_to_bing_tiles") @SqlType("array(" + BingTileType.NAME + ")") public static Block geometryToBingTiles(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(StandardTypes.INTEGER) long zoomLevelInput) { Envelope envelope = deserializeEnvelope(input); if (envelope.isEmpty()) { return EMPTY_TILE_ARRAY; } int zoomLevel = toIntExact(zoomLevelInput); GeometrySerializationType type = deserializeType(input); List<BingTile> covering; if (type == GeometrySerializationType.POINT || type == GeometrySerializationType.ENVELOPE) { covering = findMinimalTileCovering(envelope, zoomLevel); } else { OGCGeometry ogcGeometry = deserialize(input); if (isPointOrRectangle(ogcGeometry, envelope)) { covering = findMinimalTileCovering(envelope, zoomLevel); } else { covering = findMinimalTileCovering(ogcGeometry, zoomLevel); } } BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, covering.size()); for (BingTile tile : covering) { BIGINT.writeLong(blockBuilder, tile.encode()); } return blockBuilder.build(); }
@Test public void testGeometryToBingTiles() throws Exception { // Geometries at boundaries of tiles assertGeometryToBingTiles("POINT (0 0)", 1, ImmutableList.of("3")); assertGeometryToBingTiles(format("POINT (%s 0)", MIN_LONGITUDE), 1, ImmutableList.of("2")); assertGeometryToBingTiles(format("POINT (%s 0)", MAX_LONGITUDE), 1, ImmutableList.of("3")); assertGeometryToBingTiles(format("POINT (0 %s)", MIN_LATITUDE), 1, ImmutableList.of("3")); assertGeometryToBingTiles(format("POINT (0 %s)", MAX_LATITUDE), 1, ImmutableList.of("1")); assertGeometryToBingTiles(format("POINT (%s %s)", MIN_LONGITUDE, MIN_LATITUDE), 1, ImmutableList.of("2")); assertGeometryToBingTiles(format("POINT (%s %s)", MIN_LONGITUDE, MAX_LATITUDE), 1, ImmutableList.of("0")); assertGeometryToBingTiles(format("POINT (%s %s)", MAX_LONGITUDE, MAX_LATITUDE), 1, ImmutableList.of("1")); assertGeometryToBingTiles(format("POINT (%s %s)", MAX_LONGITUDE, MIN_LATITUDE), 1, ImmutableList.of("3")); assertGeometryToBingTiles("LINESTRING (-1 0, -2 0)", 1, ImmutableList.of("2")); assertGeometryToBingTiles("LINESTRING (1 0, 2 0)", 1, ImmutableList.of("3")); assertGeometryToBingTiles("LINESTRING (0 -1, 0 -2)", 1, ImmutableList.of("3")); assertGeometryToBingTiles("LINESTRING (0 1, 0 2)", 1, ImmutableList.of("1")); assertGeometryToBingTiles(format("LINESTRING (%s 1, %s 2)", MIN_LONGITUDE, MIN_LONGITUDE), 1, ImmutableList.of("0")); assertGeometryToBingTiles(format("LINESTRING (%s -1, %s -2)", MIN_LONGITUDE, MIN_LONGITUDE), 1, ImmutableList.of("2")); assertGeometryToBingTiles(format("LINESTRING (%s 1, %s 2)", MAX_LONGITUDE, MAX_LONGITUDE), 1, ImmutableList.of("1")); assertGeometryToBingTiles(format("LINESTRING (%s -1, %s -2)", MAX_LONGITUDE, MAX_LONGITUDE), 1, ImmutableList.of("3")); // Make sure corners are included assertPointInCovering("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", 6, 0, 0); assertPointInCovering("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", 6, 0, 10); assertPointInCovering("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", 6, 10, 10); assertPointInCovering("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", 6, 10, 0); // General geometries assertGeometryToBingTiles("POINT (60 30.12)", 0, ImmutableList.of("")); assertGeometryToBingTiles("POINT (60 30.12)", 10, ImmutableList.of("1230301230")); assertGeometryToBingTiles("POINT (60 30.12)", 15, ImmutableList.of("123030123010121")); assertGeometryToBingTiles("POINT (60 30.12)", 16, ImmutableList.of("1230301230101212")); assertGeometryToBingTiles("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", 6, ImmutableList.of("122220", "122222", "122221", "122223", "300000", "300001")); assertGeometryToBingTiles("POLYGON ((0 0, 0 10, 10 10, 0 0))", 6, ImmutableList.of("122220", "122222", "122221", "300000")); assertGeometryToBingTiles( "POLYGON ((10 10, -10 10, -20 -15, 10 10))", 3, ImmutableList.of("033", "211", "122")); assertGeometryToBingTiles( "POLYGON ((10 10, -10 10, -20 -15, 10 10))", 6, ImmutableList.of("211102", "211120", "033321", "033323", "211101", "211103", "211121", "033330", "033332", "211110", "211112", "033331", "033333", "211111", "122220", "122222", "122221")); assertGeometryToBingTiles("GEOMETRYCOLLECTION (POINT (60 30.12))", 10, ImmutableList.of("1230301230")); assertGeometryToBingTiles("GEOMETRYCOLLECTION (POINT (60 30.12))", 15, ImmutableList.of("123030123010121")); assertGeometryToBingTiles("GEOMETRYCOLLECTION (POLYGON ((10 10, -10 10, -20 -15, 10 10)))", 3, ImmutableList.of("033", "211", "122")); assertGeometryToBingTiles("GEOMETRYCOLLECTION (POINT (60 30.12), POLYGON ((10 10, -10 10, -20 -15, 10 10)))", 3, ImmutableList.of("033", "211", "122", "123")); assertGeometryToBingTiles( "GEOMETRYCOLLECTION (POINT (60 30.12), LINESTRING (61 31, 61.01 31.01), POLYGON EMPTY)", 15, ImmutableList.of("123030123010121", "123030112310200", "123030112310202", "123030112310201")); assertToBingTiles("bing_tile_polygon(bing_tile('1230301230'))", 10, ImmutableList.of("1230301230", "1230301231", "1230301232", "1230301233")); assertToBingTiles("bing_tile_polygon(bing_tile('1230301230'))", 11, ImmutableList.of("12303012300", "12303012302", "12303012301", "12303012303", "12303012310", "12303012312", "12303012320", "12303012321", "12303012330")); assertToBingTiles("ST_Envelope(ST_GeometryFromText('LINESTRING (59.765625 29.84064389983442, 60.2 30.14512718337612)'))", 10, ImmutableList.of("1230301230", "1230301231", "1230301232", "1230301233")); // Empty geometries assertGeometryToBingTiles("POINT EMPTY", 10, emptyList()); assertGeometryToBingTiles("POLYGON EMPTY", 10, emptyList()); assertGeometryToBingTiles("GEOMETRYCOLLECTION EMPTY", 10, emptyList()); // Geometries at MIN_LONGITUDE/MAX_LATITUDE assertGeometryToBingTiles("LINESTRING (-180 -79.19245, -180 -79.17133464081945)", 8, ImmutableList.of("22200000")); assertGeometryToBingTiles(format("POINT (%s 0)", MIN_LONGITUDE), 5, ImmutableList.of("20000")); assertGeometryToBingTiles(format("POINT (0 %s)", MAX_LATITUDE), 5, ImmutableList.of("10000")); assertGeometryToBingTiles(format("POINT (%s %s)", MIN_LONGITUDE, MAX_LATITUDE), 5, ImmutableList.of("00000")); // Invalid input // Longitude out of range assertInvalidFunction( "geometry_to_bing_tiles(ST_Point(600, 30.12), 10)", "Longitude span for the geometry must be in [-180.00, 180.00] range"); assertInvalidFunction( "geometry_to_bing_tiles(ST_GeometryFromText('POLYGON ((1000 10, -10 10, -20 -15, 1000 10))'), 10)", "Longitude span for the geometry must be in [-180.00, 180.00] range"); // Latitude out of range assertInvalidFunction( "geometry_to_bing_tiles(ST_Point(60, 300.12), 10)", "Latitude span for the geometry must be in [-85.05, 85.05] range"); assertInvalidFunction( "geometry_to_bing_tiles(ST_GeometryFromText('POLYGON ((10 1000, -10 10, -20 -15, 10 1000))'), 10)", "Latitude span for the geometry must be in [-85.05, 85.05] range"); // Invalid zoom levels assertInvalidFunction("geometry_to_bing_tiles(ST_Point(60, 30.12), -1)", "Zoom level must be >= 0"); assertInvalidFunction("geometry_to_bing_tiles(ST_Point(60, 30.12), 40)", "Zoom level must be <= 23"); // Input rectangle too large assertInvalidFunction( "geometry_to_bing_tiles(ST_Envelope(ST_GeometryFromText('LINESTRING (0 0, 80 80)')), 16)", "The zoom level is too high or the geometry is too large to compute a set of covering Bing tiles. Please use a lower zoom level, or tile only a section of the geometry."); assertFunction( "cardinality(geometry_to_bing_tiles(ST_Envelope(ST_GeometryFromText('LINESTRING (0 0, 80 80)')), 5))", BIGINT, 112L); // Complex input polygon String filePath = getResourceFile("too_large_polygon.txt").getAbsolutePath(); String largeWkt = Files.lines(Paths.get(filePath)).findFirst().get(); assertFunction( "cardinality(geometry_to_bing_tiles(ST_GeometryFromText('" + largeWkt + "'), 16))", BIGINT, 9043L); assertFunction( "cardinality(geometry_to_bing_tiles(ST_Envelope(ST_GeometryFromText('" + largeWkt + "')), 16))", BIGINT, 19939L); // Zoom level is too high assertInvalidFunction( "geometry_to_bing_tiles(ST_GeometryFromText('POLYGON ((0 0, 0 20, 20 20, 0 0))'), 20)", "The zoom level is too high or the geometry is too large to compute a set of covering Bing tiles. Please use a lower zoom level, or tile only a section of the geometry."); assertFunction( "cardinality(geometry_to_bing_tiles(ST_GeometryFromText('POLYGON ((0 0, 0 20, 20 20, 0 0))'), 14))", BIGINT, 428788L); }
public List<PluginConfiguration> getSecretsConfigMetadata(String pluginId) { return getVersionedSecretsExtension(pluginId).getSecretsConfigMetadata(pluginId); }
@Test void getSecretsConfigMetadata_shouldDelegateToVersionedExtension() { SecretsExtensionV1 secretsExtensionV1 = mock(SecretsExtensionV1.class); Map<String, VersionedSecretsExtension> secretsExtensionMap = Map.of("1.0", secretsExtensionV1); extension = new SecretsExtension(pluginManager, extensionsRegistry, secretsExtensionMap); when(pluginManager.resolveExtensionVersion(PLUGIN_ID, SECRETS_EXTENSION, SUPPORTED_VERSIONS)).thenReturn(SecretsExtensionV1.VERSION); this.extension.getSecretsConfigMetadata(PLUGIN_ID); verify(secretsExtensionV1).getSecretsConfigMetadata(PLUGIN_ID); }
void runOnce() { processApplicationEvents(); final long currentTimeMs = time.milliseconds(); final long pollWaitTimeMs = requestManagers.entries().stream() .filter(Optional::isPresent) .map(Optional::get) .map(rm -> rm.poll(currentTimeMs)) .map(networkClientDelegate::addAll) .reduce(MAX_POLL_TIMEOUT_MS, Math::min); networkClientDelegate.poll(pollWaitTimeMs, currentTimeMs); cachedMaximumTimeToWait = requestManagers.entries().stream() .filter(Optional::isPresent) .map(Optional::get) .map(rm -> rm.maximumTimeToWait(currentTimeMs)) .reduce(Long.MAX_VALUE, Math::min); reapExpiredApplicationEvents(currentTimeMs); }
@Test public void testRunOnceInvokesReaper() { consumerNetworkThread.runOnce(); verify(applicationEventReaper).reap(any(Long.class)); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore .store(QueryableStoreTypes.timestampedWindowStore(), partition); final Instant lower = calculateLowerBound(windowStartBounds, windowEndBounds); final Instant upper = calculateUpperBound(windowStartBounds, windowEndBounds); try (WindowStoreIterator<ValueAndTimestamp<GenericRow>> it = cacheBypassFetcher.fetch(store, key, lower, upper)) { final Builder<WindowedRow> builder = ImmutableList.builder(); while (it.hasNext()) { final KeyValue<Long, ValueAndTimestamp<GenericRow>> next = it.next(); final Instant windowStart = Instant.ofEpochMilli(next.key); if (!windowStartBounds.contains(windowStart)) { continue; } final Instant windowEnd = windowStart.plus(windowSize); if (!windowEndBounds.contains(windowEnd)) { continue; } final TimeWindow window = new TimeWindow(windowStart.toEpochMilli(), windowEnd.toEpochMilli()); final WindowedRow row = WindowedRow.of( stateStore.schema(), new Windowed<>(key, window), next.value.value(), next.value.timestamp() ); builder.add(row); } return KsMaterializedQueryResult.rowIterator(builder.build().iterator()); } } catch (final Exception e) { throw new MaterializationException("Failed to get value from materialized table", e); } }
@Test public void shouldFetchWithOnlyStartBounds_fetchAll() { // When: table.get(PARTITION, WINDOW_START_BOUNDS, Range.all()); // Then: verify(cacheBypassFetcherAll).fetchAll( eq(tableStore), eq(WINDOW_START_BOUNDS.lowerEndpoint()), eq(WINDOW_START_BOUNDS.upperEndpoint()) ); }
@Override public Object convert(String value) { if (value == null || value.isEmpty()) { return value; } return p.matcher(value).replaceAll(REPLACEMENT); }
@Test public void testConvert() throws Exception { Converter hc = new IPAnonymizerConverter(new HashMap<String, Object>()); assertNull(hc.convert(null)); assertEquals("", hc.convert("")); assertEquals("lol no IP in here", hc.convert("lol no IP in here")); assertEquals("127.0.1", hc.convert("127.0.1")); assertEquals("127.0.0.xxx", hc.convert("127.0.0.xxx")); assertEquals("127.0.0.xxx", hc.convert("127.0.0.1")); assertEquals("127.0.0.xxx foobar 192.168.1.xxx test", hc.convert("127.0.0.1 foobar 192.168.1.100 test")); }
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) { return decorateTextWithHtml(text, decorationDataHolder, null, null); }
@Test public void should_decorate_multiple_lines_characters_range() { String firstCommentLine = "/*"; String secondCommentLine = " * Test"; String thirdCommentLine = " */"; String blockComment = firstCommentLine + LF_END_OF_LINE + secondCommentLine + LF_END_OF_LINE + thirdCommentLine + LF_END_OF_LINE; DecorationDataHolder decorationData = new DecorationDataHolder(); decorationData.loadSyntaxHighlightingData("0,14,cppd;"); HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator(); List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(blockComment, decorationData); assertThat(htmlOutput).containsExactly( "<span class=\"cppd\">" + firstCommentLine + "</span>", "<span class=\"cppd\">" + secondCommentLine + "</span>", "<span class=\"cppd\">" + thirdCommentLine + "</span>", "" ); }
@Override public boolean createEmptyObject(String key) { try { ObjectMetadata objMeta = new ObjectMetadata(); objMeta.setContentLength(0); mClient.putObject(mBucketNameInternal, key, new ByteArrayInputStream(new byte[0]), objMeta); return true; } catch (CosClientException e) { LOG.error("Failed to create object: {}", key, e); return false; } }
@Test public void testCreateEmptyObject() { // test successful create empty object Mockito.when(mClient.putObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(InputStream.class), ArgumentMatchers.any(ObjectMetadata.class))) .thenReturn(null); boolean result = mCOSUnderFileSystem.createEmptyObject(KEY); Assert.assertTrue(result); // test create empty object exception Mockito.when(mClient.putObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(InputStream.class), ArgumentMatchers.any(ObjectMetadata.class))) .thenThrow(CosClientException.class); try { mCOSUnderFileSystem.createEmptyObject(KEY); } catch (Exception e) { Assert.assertTrue(e instanceof CosClientException); } }
@VisibleForTesting Optional<Method> getGetContainersFromPreviousAttemptsMethod() { return getContainersFromPreviousAttemptsMethod; }
@Test void testGetContainersFromPreviousAttemptsMethodReflectiveHadoop22() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG); assertThat( registerApplicationMasterResponseReflector .getGetContainersFromPreviousAttemptsMethod()) .isPresent(); }
public Blob build() throws IOException { UniqueTarArchiveEntries uniqueTarArchiveEntries = new UniqueTarArchiveEntries(); // Adds all the layer entries as tar entries. for (FileEntry layerEntry : layerEntries) { // Adds the entries to uniqueTarArchiveEntries, which makes sure all entries are unique and // adds parent directories for each extraction path. TarArchiveEntry entry = new TarArchiveEntry( layerEntry.getSourceFile(), layerEntry.getExtractionPath().toString()); // Sets the entry's permissions by masking out the permission bits from the entry's mode (the // lowest 9 bits) then using a bitwise OR to set them to the layerEntry's permissions. entry.setMode((entry.getMode() & ~0777) | layerEntry.getPermissions().getPermissionBits()); setUserAndGroup(entry, layerEntry); clearTimeHeaders(entry, layerEntry.getModificationTime()); uniqueTarArchiveEntries.add(entry); } // Gets the entries sorted by extraction path. List<TarArchiveEntry> sortedFilesystemEntries = uniqueTarArchiveEntries.getSortedEntries(); Set<String> names = new HashSet<>(); // Adds all the files to a tar stream. TarStreamBuilder tarStreamBuilder = new TarStreamBuilder(); for (TarArchiveEntry entry : sortedFilesystemEntries) { Verify.verify(!names.contains(entry.getName())); names.add(entry.getName()); tarStreamBuilder.addTarArchiveEntry(entry); } return Blobs.from(tarStreamBuilder::writeAsTarArchiveTo, false); }
@Test public void testBuild_permissions() throws IOException { Path testRoot = temporaryFolder.getRoot().toPath(); Path folder = Files.createDirectories(testRoot.resolve("files1")); Path fileA = createFile(testRoot, "fileA", "abc", 54321); Path fileB = createFile(testRoot, "fileB", "def", 54321); Blob blob = new ReproducibleLayerBuilder( ImmutableList.of( defaultLayerEntry(fileA, AbsoluteUnixPath.get("/somewhere/fileA")), new FileEntry( fileB, AbsoluteUnixPath.get("/somewhere/fileB"), FilePermissions.fromOctalString("123"), FileEntriesLayer.DEFAULT_MODIFICATION_TIME), new FileEntry( folder, AbsoluteUnixPath.get("/somewhere/folder"), FilePermissions.fromOctalString("456"), FileEntriesLayer.DEFAULT_MODIFICATION_TIME))) .build(); Path tarFile = temporaryFolder.newFile().toPath(); try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(tarFile))) { blob.writeTo(out); } try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(tarFile))) { // Root folder (default folder permissions) assertThat(in.getNextTarEntry().getMode()).isEqualTo(040755); // fileA (default file permissions) assertThat(in.getNextTarEntry().getMode()).isEqualTo(0100644); // fileB (custom file permissions) assertThat(in.getNextTarEntry().getMode()).isEqualTo(0100123); // folder (custom folder permissions) assertThat(in.getNextTarEntry().getMode()).isEqualTo(040456); } }
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException e) { return null; } catch (JMException e) { return null; } }
@Test public void returnsJmxAttribute() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); assertThat(gauge.getValue()).isInstanceOf(Integer.class); assertThat((Integer) gauge.getValue()).isGreaterThan(0); }
@NonNull public Client authenticate(@NonNull Request request) { // https://datatracker.ietf.org/doc/html/rfc7521#section-4.2 try { if (!CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT.equals(request.clientAssertionType())) { throw new AuthenticationException( "unsupported client_assertion_type='%s', expected '%s'" .formatted(request.clientAssertionType(), CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT)); } var processor = new DefaultJWTProcessor<>(); var keySelector = new JWSVerificationKeySelector<>( Set.of(JWSAlgorithm.RS256, JWSAlgorithm.ES256), jwkSource); processor.setJWSKeySelector(keySelector); processor.setJWTClaimsSetVerifier( new DefaultJWTClaimsVerifier<>( new JWTClaimsSet.Builder().audience(baseUri.toString()).build(), Set.of( JWTClaimNames.JWT_ID, JWTClaimNames.EXPIRATION_TIME, JWTClaimNames.ISSUER, JWTClaimNames.SUBJECT))); var claims = processor.process(request.clientAssertion(), null); var clientId = clientIdFromAssertion(request.clientId(), claims); return new Client(clientId); } catch (ParseException e) { throw new AuthenticationException("failed to parse client assertion", e); } catch (BadJOSEException | JOSEException e) { throw new AuthenticationException("failed to verify client assertion", e); } }
@Test void authenticate_badSubject() throws JOSEException { var key = generateKey(); var jwkSource = new StaticJwkSource<>(key); var claims = new JWTClaimsSet.Builder() .audience(RP_ISSUER.toString()) .subject("not the right client") .issuer(CLIENT_ID) .expirationTime(Date.from(Instant.now().plusSeconds(60))) .jwtID(UUID.randomUUID().toString()) .build(); var signed = signJwt(claims, key); var authenticator = new ClientAuthenticator(jwkSource, RP_ISSUER); // when & then assertThrows( AuthenticationException.class, () -> authenticator.authenticate( new Request( CLIENT_ID, ClientAuthenticator.CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT, signed))); }
@Override public void close() throws IOException { this.closed = true; writer.close(); }
@TestTemplate public void testRollingManifestWriterNoRecords() throws IOException { RollingManifestWriter<DataFile> writer = newRollingWriteManifest(SMALL_FILE_SIZE); writer.close(); assertThat(writer.toManifestFiles()).isEmpty(); writer.close(); assertThat(writer.toManifestFiles()).isEmpty(); }
protected long getCurrentTimeMillis() { return System.currentTimeMillis(); }
@Test void givenActivityHappened_whenRecordActivity_thenShouldDelegateToOnActivity() { // GIVEN TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder() .setSessionIdMSB(SESSION_ID.getMostSignificantBits()) .setSessionIdLSB(SESSION_ID.getLeastSignificantBits()) .build(); doCallRealMethod().when(transportServiceMock).recordActivity(sessionInfo); when(transportServiceMock.toSessionId(sessionInfo)).thenReturn(SESSION_ID); long expectedTime = 123L; when(transportServiceMock.getCurrentTimeMillis()).thenReturn(expectedTime); // WHEN transportServiceMock.recordActivity(sessionInfo); // THEN verify(transportServiceMock).onActivity(SESSION_ID, sessionInfo, expectedTime); }
@Override public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) { selectedBundlesCache.clear(); final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0; final Map<String, Long> recentlyUnloadedBundles = loadData.getRecentlyUnloadedBundles(); // Check every broker and select loadData.getBrokerData().forEach((broker, brokerData) -> { final LocalBrokerData localData = brokerData.getLocalData(); final double currentUsage = localData.getMaxResourceUsageWithWeight( conf.getLoadBalancerCPUResourceWeight(), conf.getLoadBalancerDirectMemoryResourceWeight(), conf.getLoadBalancerBandwidthInResourceWeight(), conf.getLoadBalancerBandwidthOutResourceWeight()); if (currentUsage < overloadThreshold) { if (log.isDebugEnabled()) { log.debug("[{}] Broker is not overloaded, ignoring at this point ({})", broker, localData.printResourceUsage()); } return; } // We want to offload enough traffic such that this broker will go below the overload threshold // Also, add a small margin so that this broker won't be very close to the threshold edge. double percentOfTrafficToOffload = currentUsage - overloadThreshold + ADDITIONAL_THRESHOLD_PERCENT_MARGIN; double brokerCurrentThroughput = localData.getMsgThroughputIn() + localData.getMsgThroughputOut(); double minimumThroughputToOffload = brokerCurrentThroughput * percentOfTrafficToOffload; log.info( "Attempting to shed load on {}, which has resource usage {}% above threshold {}%" + " -- Offloading at least {} MByte/s of traffic ({})", broker, 100 * currentUsage, 100 * overloadThreshold, minimumThroughputToOffload / 1024 / 1024, localData.printResourceUsage()); MutableDouble trafficMarkedToOffload = new MutableDouble(0); MutableBoolean atLeastOneBundleSelected = new MutableBoolean(false); if (localData.getBundles().size() > 1) { // Sort bundles by throughput, then pick the biggest N which combined // make up for at least the minimum throughput to offload loadData.getBundleDataForLoadShedding().entrySet().stream() .filter(e -> localData.getBundles().contains(e.getKey())) .map((e) -> { // Map to throughput value // Consider short-term byte rate to address system resource burden String bundle = e.getKey(); BundleData bundleData = e.getValue(); TimeAverageMessageData shortTermData = bundleData.getShortTermData(); double throughput = shortTermData.getMsgThroughputIn() + shortTermData .getMsgThroughputOut(); return Pair.of(bundle, throughput); }).filter(e -> { // Only consider bundles that were not already unloaded recently return !recentlyUnloadedBundles.containsKey(e.getLeft()); }).sorted((e1, e2) -> { // Sort by throughput in reverse order return Double.compare(e2.getRight(), e1.getRight()); }).forEach(e -> { if (trafficMarkedToOffload.doubleValue() < minimumThroughputToOffload || atLeastOneBundleSelected.isFalse()) { selectedBundlesCache.put(broker, e.getLeft()); trafficMarkedToOffload.add(e.getRight()); atLeastOneBundleSelected.setTrue(); } }); } else if (localData.getBundles().size() == 1) { log.warn( "HIGH USAGE WARNING : Sole namespace bundle {} is overloading broker {}. " + "No Load Shedding will be done on this broker", localData.getBundles().iterator().next(), broker); } else { log.warn("Broker {} is overloaded despite having no bundles", broker); } }); return selectedBundlesCache; }
@Test public void testBrokerNotOverloaded() { LoadData loadData = new LoadData(); LocalBrokerData broker1 = new LocalBrokerData(); broker1.setBandwidthIn(new ResourceUsage(500, 1000)); broker1.setBandwidthOut(new ResourceUsage(500, 1000)); broker1.setBundles(Sets.newHashSet("bundle-1")); BundleData bundle1 = new BundleData(); TimeAverageMessageData db1 = new TimeAverageMessageData(); db1.setMsgThroughputIn(1000); db1.setMsgThroughputOut(1000); bundle1.setShortTermData(db1); loadData.getBundleData().put("bundle-1", bundle1); loadData.getBrokerData().put("broker-1", new BrokerData(broker1)); assertTrue(os.findBundlesForUnloading(loadData, conf).isEmpty()); }
DistCh(Configuration conf) { super(createJobConf(conf)); }
@Test public void testDistCh() throws Exception { final Configuration conf = new Configuration(); conf.set(CapacitySchedulerConfiguration.PREFIX+CapacitySchedulerConfiguration.ROOT+"."+CapacitySchedulerConfiguration.QUEUES, "default"); conf.set(CapacitySchedulerConfiguration.PREFIX+CapacitySchedulerConfiguration.ROOT+".default."+CapacitySchedulerConfiguration.CAPACITY, "100"); final MiniDFSCluster cluster= new MiniDFSCluster.Builder(conf).numDataNodes(2).format(true).build(); final FileSystem fs = cluster.getFileSystem(); final FsShell shell = new FsShell(conf); try { final FileTree tree = new FileTree(fs, "testDistCh"); final FileStatus rootstatus = fs.getFileStatus(tree.rootdir); runLsr(shell, tree.root, 0); final String[] args = new String[NUN_SUBS]; final ChPermissionStatus[] newstatus = new ChPermissionStatus[NUN_SUBS]; args[0]="/test/testDistCh/sub0:sub1::"; newstatus[0] = new ChPermissionStatus(rootstatus, "sub1", "", ""); args[1]="/test/testDistCh/sub1::sub2:"; newstatus[1] = new ChPermissionStatus(rootstatus, "", "sub2", ""); args[2]="/test/testDistCh/sub2:::437"; newstatus[2] = new ChPermissionStatus(rootstatus, "", "", "437"); args[3]="/test/testDistCh/sub3:sub1:sub2:447"; newstatus[3] = new ChPermissionStatus(rootstatus, "sub1", "sub2", "447"); args[4]="/test/testDistCh/sub4::sub5:437"; newstatus[4] = new ChPermissionStatus(rootstatus, "", "sub5", "437"); args[5]="/test/testDistCh/sub5:sub1:sub5:"; newstatus[5] = new ChPermissionStatus(rootstatus, "sub1", "sub5", ""); args[6]="/test/testDistCh/sub6:sub3::437"; newstatus[6] = new ChPermissionStatus(rootstatus, "sub3", "", "437"); System.out.println("args=" + Arrays.asList(args).toString().replace(",", ",\n ")); System.out.println("newstatus=" + Arrays.asList(newstatus).toString().replace(",", ",\n ")); //run DistCh new DistCh(MiniMRClientClusterFactory.create(this.getClass(), 2, conf).getConfig()).run(args); runLsr(shell, tree.root, 0); //check results for(int i = 0; i < NUN_SUBS; i++) { Path sub = new Path(tree.root + "/sub" + i); checkFileStatus(newstatus[i], fs.getFileStatus(sub)); for(FileStatus status : fs.listStatus(sub)) { checkFileStatus(newstatus[i], status); } } } finally { cluster.shutdown(); } }
public static String createJobName(String prefix) { return createJobName(prefix, 0); }
@Test public void testCreateJobNameWithUppercase() { assertThat(createJobName("testWithUpperCase")).matches("test-with-upper-case-\\d{17}"); }
public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length) { checkNotNull(a, "a"); checkNotNull(b, "b"); // All indexes and lengths must be non-negative checkPositiveOrZero(aStartIndex, "aStartIndex"); checkPositiveOrZero(bStartIndex, "bStartIndex"); checkPositiveOrZero(length, "length"); if (a.writerIndex() - length < aStartIndex || b.writerIndex() - length < bStartIndex) { return false; } final int longCount = length >>> 3; final int byteCount = length & 7; if (a.order() == b.order()) { for (int i = longCount; i > 0; i --) { if (a.getLong(aStartIndex) != b.getLong(bStartIndex)) { return false; } aStartIndex += 8; bStartIndex += 8; } } else { for (int i = longCount; i > 0; i --) { if (a.getLong(aStartIndex) != swapLong(b.getLong(bStartIndex))) { return false; } aStartIndex += 8; bStartIndex += 8; } } for (int i = byteCount; i > 0; i --) { if (a.getByte(aStartIndex) != b.getByte(bStartIndex)) { return false; } aStartIndex ++; bStartIndex ++; } return true; }
@Test public void equalsBufferSubsections() { byte[] b1 = new byte[128]; byte[] b2 = new byte[256]; Random rand = new Random(); rand.nextBytes(b1); rand.nextBytes(b2); final int iB1 = b1.length / 2; final int iB2 = iB1 + b1.length; final int length = b1.length - iB1; System.arraycopy(b1, iB1, b2, iB2, length); assertTrue(ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, length)); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } return results; }
@Test public void macosFailedToFindServicePortForDisplay() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/macos_failed_to_find_service_port_for_display.txt")), CrashReportAnalyzer.Rule.MACOS_FAILED_TO_FIND_SERVICE_PORT_FOR_DISPLAY); }
@Override public KTable<Windowed<K>, V> reduce(final Reducer<V> reducer) { return reduce(reducer, NamedInternal.empty()); }
@Test public void shouldMaterializeReduced() { windowedStream.reduce( MockReducer.STRING_ADDER, Materialized.<String, String, WindowStore<Bytes, byte[]>>as("reduced") .withKeySerde(Serdes.String()) .withValueSerde(Serdes.String())); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { processData(driver); { final WindowStore<String, String> windowStore = driver.getWindowStore("reduced"); final List<KeyValue<Windowed<String>, String>> data = StreamsTestUtils.toList(windowStore.fetch("1", "2", ofEpochMilli(0), ofEpochMilli(1000L))); assertThat(data, equalTo(Arrays.asList( KeyValue.pair(new Windowed<>("1", new TimeWindow(0, 100)), "1"), KeyValue.pair(new Windowed<>("1", new TimeWindow(50, 150)), "1+2"), KeyValue.pair(new Windowed<>("1", new TimeWindow(101, 201)), "2"), KeyValue.pair(new Windowed<>("1", new TimeWindow(400, 500)), "3"), KeyValue.pair(new Windowed<>("2", new TimeWindow(50, 150)), "20"), KeyValue.pair(new Windowed<>("2", new TimeWindow(100, 200)), "10+20"), KeyValue.pair(new Windowed<>("2", new TimeWindow(151, 251)), "10")))); } { final WindowStore<String, ValueAndTimestamp<Long>> windowStore = driver.getTimestampedWindowStore("reduced"); final List<KeyValue<Windowed<String>, ValueAndTimestamp<Long>>> data = StreamsTestUtils.toList(windowStore.fetch("1", "2", ofEpochMilli(0), ofEpochMilli(1000L))); assertThat(data, equalTo(Arrays.asList( KeyValue.pair(new Windowed<>("1", new TimeWindow(0, 100)), ValueAndTimestamp.make("1", 100L)), KeyValue.pair(new Windowed<>("1", new TimeWindow(50, 150)), ValueAndTimestamp.make("1+2", 150L)), KeyValue.pair(new Windowed<>("1", new TimeWindow(101, 201)), ValueAndTimestamp.make("2", 150L)), KeyValue.pair(new Windowed<>("1", new TimeWindow(400, 500)), ValueAndTimestamp.make("3", 500L)), KeyValue.pair(new Windowed<>("2", new TimeWindow(50, 150)), ValueAndTimestamp.make("20", 150L)), KeyValue.pair(new Windowed<>("2", new TimeWindow(100, 200)), ValueAndTimestamp.make("10+20", 200L)), KeyValue.pair(new Windowed<>("2", new TimeWindow(151, 251)), ValueAndTimestamp.make("10", 200L))))); } } }
public static IntStream allLinesFor(DefaultIssue issue, String componentUuid) { DbIssues.Locations locations = issue.getLocations(); if (locations == null) { return IntStream.empty(); } Stream<DbCommons.TextRange> textRanges = Stream.concat( locations.hasTextRange() ? Stream.of(locations.getTextRange()) : Stream.empty(), locations.getFlowList().stream() .flatMap(f -> f.getLocationList().stream()) .filter(l -> Objects.equals(componentIdOf(issue, l), componentUuid)) .map(DbIssues.Location::getTextRange)); return textRanges.flatMapToInt(range -> IntStream.rangeClosed(range.getStartLine(), range.getEndLine())); }
@Test public void allLinesFor_filters_lines_for_specified_component() { DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); locations.addFlowBuilder() .addLocation(newLocation("file1", 5, 5)) .addLocation(newLocation("file1", 10, 12)) .addLocation(newLocation("file1", 15, 15)) .addLocation(newLocation("file2", 10, 11)) .build(); DefaultIssue issue = new DefaultIssue().setLocations(locations.build()); assertThat(IssueLocations.allLinesFor(issue, "file1")).containsExactlyInAnyOrder(5, 10, 11, 12, 15); assertThat(IssueLocations.allLinesFor(issue, "file2")).containsExactlyInAnyOrder(10, 11); assertThat(IssueLocations.allLinesFor(issue, "file3")).isEmpty(); }
public DataConnectionConfig load(DataConnectionConfig dataConnectionConfig) { // Make a copy to preserve the original configuration DataConnectionConfig loadedConfig = new DataConnectionConfig(dataConnectionConfig); // Try XML file first if (loadConfig(loadedConfig, HazelcastDataConnection.CLIENT_XML_PATH, HazelcastDataConnection.CLIENT_XML)) { return loadedConfig; } // Try YML file loadConfig(loadedConfig, HazelcastDataConnection.CLIENT_YML_PATH, HazelcastDataConnection.CLIENT_YML); return loadedConfig; }
@Test public void testLoadXml() { DataConnectionConfig dataConnectionConfig = new DataConnectionConfig(); Path path = Paths.get("src", "test", "resources", "hazelcast-client-test-external.xml"); dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_XML_PATH, path.toString()); HazelcastDataConnectionConfigLoader loader = new HazelcastDataConnectionConfigLoader(); DataConnectionConfig loadedConfig = loader.load(dataConnectionConfig); assertNotNull(loadedConfig.getProperty(HazelcastDataConnection.CLIENT_XML)); assertNull(loadedConfig.getProperty(HazelcastDataConnection.CLIENT_YML)); }
public static void processEnvVariables(Map<String, String> inputProperties) { processEnvVariables(inputProperties, System.getenv()); }
@Test void ignoreEmptyValueForJsonEnv() { var inputProperties = new HashMap<String, String>(); EnvironmentConfig.processEnvVariables(inputProperties, Map.of("SONAR_SCANNER_JSON_PARAMS", "")); assertThat(inputProperties).isEmpty(); }
public static double minimize(DifferentiableMultivariateFunction func, double[] x, double gtol, int maxIter) { if (gtol <= 0.0) { throw new IllegalArgumentException("Invalid gradient tolerance: " + gtol); } if (maxIter <= 0) { throw new IllegalArgumentException("Invalid maximum number of iterations: " + maxIter); } double den, fac, fad, fae, sumdg, sumxi, temp, test; int n = x.length; double[] dg = new double[n]; double[] g = new double[n]; double[] hdg = new double[n]; double[] xnew = new double[n]; double[] xi = new double[n]; double[][] hessin = new double[n][n]; // Calculate starting function value and gradient and initialize the // inverse Hessian to the unit matrix. double f = func.g(x, g); logger.info(String.format("BFGS: initial function value: %.5f", f)); for (int i = 0; i < n; i++) { hessin[i][i] = 1.0; // Initialize line direction. xi[i] = -g[i]; } double stpmax = STPMX * max(norm(x), n); for (int iter = 1; iter <= maxIter; iter++) { // The new function evaluation occurs in line search. f = linesearch(func, x, f, g, xi, xnew, stpmax); if (iter % 100 == 0) { logger.info(String.format("BFGS: the function value after %3d iterations: %.5f", iter, f)); } // update the line direction and current point. for (int i = 0; i < n; i++) { xi[i] = xnew[i] - x[i]; x[i] = xnew[i]; } // Test for convergence on x. test = 0.0; for (int i = 0; i < n; i++) { temp = abs(xi[i]) / max(abs(x[i]), 1.0); if (temp > test) { test = temp; } } if (test < TOLX) { logger.info(String.format("BFGS converges on x after %d iterations: %.5f", iter, f)); return f; } System.arraycopy(g, 0, dg, 0, n); func.g(x, g); // Test for convergence on zero gradient. den = max(f, 1.0); test = 0.0; for (int i = 0; i < n; i++) { temp = abs(g[i]) * max(abs(x[i]), 1.0) / den; if (temp > test) { test = temp; } } if (test < gtol) { logger.info(String.format("BFGS converges on gradient after %d iterations: %.5f", iter, f)); return f; } for (int i = 0; i < n; i++) { dg[i] = g[i] - dg[i]; } for (int i = 0; i < n; i++) { hdg[i] = 0.0; for (int j = 0; j < n; j++) { hdg[i] += hessin[i][j] * dg[j]; } } fac = fae = sumdg = sumxi = 0.0; for (int i = 0; i < n; i++) { fac += dg[i] * xi[i]; fae += dg[i] * hdg[i]; sumdg += dg[i] * dg[i]; sumxi += xi[i] * xi[i]; } // Skip update if fac is not sufficiently positive. if (fac > sqrt(EPSILON * sumdg * sumxi)) { fac = 1.0 / fac; fad = 1.0 / fae; // The vector that makes BFGS different from DFP. for (int i = 0; i < n; i++) { dg[i] = fac * xi[i] - fad * hdg[i]; } // BFGS updating formula. for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { hessin[i][j] += fac * xi[i] * xi[j] - fad * hdg[i] * hdg[j] + fae * dg[i] * dg[j]; hessin[j][i] = hessin[i][j]; } } } // Calculate the next direction to go. Arrays.fill(xi, 0.0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { xi[i] -= hessin[i][j] * g[j]; } } } logger.warn(String.format("BFGS reaches maximum %d iterations: %.5f", maxIter, f)); return f; }
@Test public void testBFGS() { System.out.println("BFGS"); double[] x = new double[100]; for (int j = 1; j <= x.length; j += 2) { x[j - 1] = -1.2; x[j] = 1.2; } double result = BFGS.minimize(func, x, 1E-5, 500); System.out.println(Arrays.toString(x)); assertEquals(3.448974035627997E-10, result, 1E-15); }
public T value() { return value; }
@Test public final void testValue() { final Integer n = 42; Timestamped<Integer> tsv = new Timestamped<>(n, TS_1_1); assertSame(n, tsv.value()); }
public static double GroundResolution(final double latitude, final int levelOfDetail) { return GroundResolution(latitude, (double) levelOfDetail); }
@Test public void test_groundResolution() { final double delta = 1e-4; for (int zoomLevel = mMinZoomLevel; zoomLevel <= mMaxZoomLevel; zoomLevel++) { Assert.assertEquals(156543.034 / (1 << zoomLevel), TileSystem.GroundResolution(0, zoomLevel), delta); } }
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest req) { var now = clock.instant(); var bearerToken = requestBearerToken(req).orElse(null); if (bearerToken == null) { log.fine("Missing bearer token"); return Optional.of(new ErrorResponse(Response.Status.UNAUTHORIZED, "Unauthorized")); } var permission = Permission.getRequiredPermission(req).orElse(null); if (permission == null) return Optional.of(new ErrorResponse(Response.Status.FORBIDDEN, "Forbidden")); var requestTokenHash = requestTokenHash(bearerToken); var clientIds = new TreeSet<String>(); var permissions = EnumSet.noneOf(Permission.class); var matchedTokens = new HashSet<TokenVersion>(); for (Client c : allowedClients) { if (!c.permissions().contains(permission)) continue; var matchedToken = c.tokens().get(requestTokenHash); if (matchedToken == null) continue; var expiration = matchedToken.expiration().orElse(null); if (expiration != null && now.isAfter(expiration)) continue; matchedTokens.add(matchedToken); clientIds.add(c.id()); permissions.addAll(c.permissions()); } if (clientIds.isEmpty()) return Optional.of(new ErrorResponse(Response.Status.FORBIDDEN, "Forbidden")); if (matchedTokens.size() > 1) { log.warning("Multiple tokens matched for request %s" .formatted(matchedTokens.stream().map(TokenVersion::id).toList())); return Optional.of(new ErrorResponse(Response.Status.FORBIDDEN, "Forbidden")); } var matchedToken = matchedTokens.stream().findAny().get(); addAccessLogEntry(req, "token.id", matchedToken.id()); addAccessLogEntry(req, "token.hash", matchedToken.fingerprint().toDelimitedHexString()); addAccessLogEntry(req, "token.exp", matchedToken.expiration().map(Instant::toString).orElse("<none>")); ClientPrincipal.attachToRequest(req, clientIds, permissions); return Optional.empty(); }
@Test void fails_for_unknown_token() { var req = FilterTestUtils.newRequestBuilder() .withMethod(Method.GET) .withHeader("Authorization", "Bearer " + UNKNOWN_TOKEN.secretTokenString()) .build(); var responseHandler = new MockResponseHandler(); newFilterWithClientsConfig().filter(req, responseHandler); assertNotNull(responseHandler.getResponse()); assertEquals(FORBIDDEN, responseHandler.getResponse().getStatus()); }
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldParseArbitraryExpressions() { // Given: final String statementString = "INSERT INTO ADDRESS VALUES (2 + 1);"; final Statement statement = KsqlParserTestUtil.buildSingleAst(statementString, metaStore).getStatement(); // When: final String result = SqlFormatter.formatSql(statement); // Then: assertThat(result, is("INSERT INTO ADDRESS VALUES ((2 + 1))")); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBuildSourceStreamWithCorrectParamsWhenBuildingTable() { // Given: givenNodeWithMockSource(); // When: node.buildStream(buildContext); // Then: verify(schemaKStreamFactory).create( same(buildContext), same(dataSource), stackerCaptor.capture() ); assertThat( stackerCaptor.getValue().getQueryContext().getContext(), equalTo(ImmutableList.of("0", "Source")) ); }
public String getNextId() { return String.format("%s-%d-%d", prefix, generatorInstanceId, counter.getAndIncrement()); }
@Test public void simple() throws Exception { DistributedIdGenerator gen1 = new DistributedIdGenerator(coordinationService, "/my/test/simple", "p"); assertEquals(gen1.getNextId(), "p-0-0"); assertEquals(gen1.getNextId(), "p-0-1"); assertEquals(gen1.getNextId(), "p-0-2"); assertEquals(gen1.getNextId(), "p-0-3"); DistributedIdGenerator gen2 = new DistributedIdGenerator(coordinationService, "/my/test/simple", "p"); assertEquals(gen2.getNextId(), "p-1-0"); assertEquals(gen2.getNextId(), "p-1-1"); assertEquals(gen1.getNextId(), "p-0-4"); assertEquals(gen2.getNextId(), "p-1-2"); }
@Override public void filter(ContainerRequestContext req) throws IOException { TrackedByGauge trackedByGauge = _resourceInfo.getResourceMethod().getAnnotation(TrackedByGauge.class); if (trackedByGauge != null) { _controllerMetrics.addValueToGlobalGauge(trackedByGauge.gauge(), 1L); } }
@Test public void testContainerRequestFilterIncrementsGauge() throws Exception { Method methodOne = TrackedClass.class.getDeclaredMethod("trackedMethod"); when(_resourceInfo.getResourceMethod()).thenReturn(methodOne); _interceptor.filter(_containerRequestContext); verify(_controllerMetrics) .addValueToGlobalGauge(ControllerGauge.SEGMENT_DOWNLOADS_IN_PROGRESS, 1L); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void banChatSenderChat() { BaseResponse response = bot.execute(new BanChatSenderChat(channelName, memberBot)); assertTrue(response.isOk()); }
public static void stopProxy(Object proxy) { if (proxy == null) { throw new HadoopIllegalArgumentException( "Cannot close proxy since it is null"); } try { if (proxy instanceof Closeable) { ((Closeable) proxy).close(); return; } else { InvocationHandler handler = Proxy.getInvocationHandler(proxy); if (handler instanceof Closeable) { ((Closeable) handler).close(); return; } } } catch (IOException e) { LOG.error("Closing proxy or invocation handler caused exception", e); } catch (IllegalArgumentException e) { LOG.error("RPC.stopProxy called on non proxy: class=" + proxy.getClass().getName(), e); } // If you see this error on a mock object in a unit test you're // developing, make sure to use MockitoUtil.mockProtocol() to // create your mock. throw new HadoopIllegalArgumentException( "Cannot close proxy - is not Closeable or " + "does not provide closeable invocation handler " + proxy.getClass()); }
@Test public void testStopProxy() throws IOException { RPC.setProtocolEngine(conf, StoppedProtocol.class, StoppedRpcEngine.class); StoppedProtocol proxy = RPC.getProxy(StoppedProtocol.class, StoppedProtocol.versionID, null, conf); StoppedInvocationHandler invocationHandler = (StoppedInvocationHandler) Proxy.getInvocationHandler(proxy); assertEquals(0, invocationHandler.getCloseCalled()); RPC.stopProxy(proxy); assertEquals(1, invocationHandler.getCloseCalled()); }
@Override public LocalResourceId resolve(String other, ResolveOptions resolveOptions) { checkState(isDirectory(), "Expected the path is a directory, but had [%s].", pathString); checkArgument( resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) || resolveOptions.equals(StandardResolveOptions.RESOLVE_DIRECTORY), "ResolveOptions: [%s] is not supported.", resolveOptions); checkArgument( !(resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) && other.endsWith("/")), "The resolved file: [%s] should not end with '/'.", other); if (SystemUtils.IS_OS_WINDOWS) { return resolveLocalPathWindowsOS(other, resolveOptions); } else { return resolveLocalPath(other, resolveOptions); } }
@Test public void testResolveInvalidNotDirectory() { // TODO: Java core test failing on windows, https://github.com/apache/beam/issues/20477 assumeFalse(SystemUtils.IS_OS_WINDOWS); ResourceId tmp = toResourceIdentifier("/root/").resolve("tmp", StandardResolveOptions.RESOLVE_FILE); thrown.expect(IllegalStateException.class); thrown.expectMessage("Expected the path is a directory, but had [/root/tmp]."); tmp.resolve("aa", StandardResolveOptions.RESOLVE_FILE); }
public static boolean isPlainHttp(NetworkService networkService) { checkNotNull(networkService); var isWebService = isWebService(networkService); var isKnownServiceName = IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey( Ascii.toLowerCase(networkService.getServiceName())); var doesNotSupportAnySslVersion = networkService.getSupportedSslVersionsCount() == 0; if (!isKnownServiceName) { return isWebService && doesNotSupportAnySslVersion; } var isKnownPlainHttpService = IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.getOrDefault( Ascii.toLowerCase(networkService.getServiceName()), false); return isKnownPlainHttpService && doesNotSupportAnySslVersion; }
@Test public void isPlainHttp_whenHttpServiceFromHttpMethodsWithoutSslVersions_returnsTrue() { assertThat( NetworkServiceUtils.isPlainHttp( NetworkService.newBuilder() .setServiceName("ssh") .addSupportedHttpMethods("GET") .build())) .isTrue(); }
public static String createErrorMessage(HttpException exception) { String json = tryParseAsJsonError(exception.content()); if (json != null) { return json; } String msg = "HTTP code " + exception.code(); if (isHtml(exception.content())) { return msg; } return msg + ": " + StringUtils.left(exception.content(), MAX_ERROR_MSG_LEN); }
@Test public void createErrorMessage_whenHtml_shouldCreateErrorMsg() { String content = "<!DOCTYPE html><html>something</html>"; assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).isEqualTo("HTTP code 400"); }
public List<Stream> match(Message message) { final Set<Stream> result = Sets.newHashSet(); final Set<String> blackList = Sets.newHashSet(); for (final Rule rule : rulesList) { if (blackList.contains(rule.getStreamId())) { continue; } final StreamRule streamRule = rule.getStreamRule(); final StreamRuleType streamRuleType = streamRule.getType(); final Stream.MatchingType matchingType = rule.getMatchingType(); if (!ruleTypesNotNeedingFieldPresence.contains(streamRuleType) && !message.hasField(streamRule.getField())) { if (matchingType == Stream.MatchingType.AND) { result.remove(rule.getStream()); // blacklist stream because it can't match anymore blackList.add(rule.getStreamId()); } continue; } final Stream stream; if (streamRuleType != StreamRuleType.REGEX) { stream = rule.match(message); } else { stream = rule.matchWithTimeOut(message, streamProcessingTimeout, TimeUnit.MILLISECONDS); } if (stream == null) { if (matchingType == Stream.MatchingType.AND) { result.remove(rule.getStream()); // blacklist stream because it can't match anymore blackList.add(rule.getStreamId()); } } else { result.add(stream); if (matchingType == Stream.MatchingType.OR) { // blacklist stream because it is already matched blackList.add(rule.getStreamId()); } } } final Stream defaultStream = defaultStreamProvider.get(); boolean alreadyRemovedDefaultStream = false; for (Stream stream : result) { if (stream.getRemoveMatchesFromDefaultStream()) { if (alreadyRemovedDefaultStream || message.removeStream(defaultStream)) { alreadyRemovedDefaultStream = true; if (LOG.isTraceEnabled()) { LOG.trace("Successfully removed default stream <{}> from message <{}>", defaultStream.getId(), message.getId()); } } else { // A previously executed message processor (or Illuminate) has likely already removed the // default stream from the message. Now, the message has matched a stream in the Graylog // MessageFilterChain, and the matching stream is also set to remove the default stream. // This is usually from user-defined stream rules, and is generally not a problem. cannotRemoveDefaultMeter.inc(); if (LOG.isTraceEnabled()) { LOG.trace("Couldn't remove default stream <{}> from message <{}>", defaultStream.getId(), message.getId()); } } } } return ImmutableList.copyOf(result); }
@Test public void testContainsMatch() throws Exception { final StreamMock stream = getStreamMock("test"); final StreamRuleMock rule = new StreamRuleMock(ImmutableMap.of( "_id", new ObjectId(), "field", "testfield", "value", "testvalue", "type", StreamRuleType.CONTAINS.toInteger(), "stream_id", stream.getId() )); stream.setStreamRules(Lists.newArrayList(rule)); final StreamRouterEngine engine = newEngine(Lists.newArrayList(stream)); final Message message = getMessage(); // Without the field assertTrue(engine.match(message).isEmpty()); // With wrong value for field. message.addField("testfield", "no-foobar"); assertTrue(engine.match(message).isEmpty()); // With matching value for field. message.addField("testfield", "hello testvalue"); assertEquals(Lists.newArrayList(stream), engine.match(message)); }
public void onNotify(String tag, int id, final Notification notification) { if (this.customizeEnable) { try { if (notification.contentIntent != null) { SALog.i(TAG, "onNotify, tag: " + tag + ", id=" + id); final NotificationInfo push = getNotificationInfo(notification); if (push != null) { mPushHandler.post(new Runnable() { @Override public void run() { checkAndStoreNotificationInfo(notification.contentIntent, push); } }); } } } catch (Exception e) { SALog.printStackTrace(e); } } }
@Test public void onNotify() { SAHelper.initSensors(mApplication); Notification notification = new Notification(); notification.contentIntent = MockDataTest.mockPendingIntent(); // notification.extras.putString("android.title", "notifyTitle"); // notification.extras.putString("android.text", "notifyText"); PushProcess.getInstance().onNotify("TAG",123, notification); }
public static BlendMode getInstance(COSBase cosBlendMode) { BlendMode result = null; if (cosBlendMode instanceof COSName) { result = BLEND_MODES.get(cosBlendMode); } else if (cosBlendMode instanceof COSArray) { COSArray cosBlendModeArray = (COSArray) cosBlendMode; for (int i = 0; i < cosBlendModeArray.size(); i++) { COSBase cosBase = cosBlendModeArray.getObject(i); if (cosBase instanceof COSName) { result = BLEND_MODES.get(cosBase); if (result != null) { break; } } } } return result != null ? result : BlendMode.NORMAL; }
@Test void testInstances() { assertEquals(BlendMode.NORMAL, BlendMode.getInstance(COSName.NORMAL)); assertEquals(BlendMode.NORMAL, BlendMode.getInstance(COSName.COMPATIBLE)); assertEquals(BlendMode.MULTIPLY, BlendMode.getInstance(COSName.MULTIPLY)); assertEquals(BlendMode.SCREEN, BlendMode.getInstance(COSName.SCREEN)); assertEquals(BlendMode.OVERLAY, BlendMode.getInstance(COSName.OVERLAY)); assertEquals(BlendMode.DARKEN, BlendMode.getInstance(COSName.DARKEN)); assertEquals(BlendMode.LIGHTEN, BlendMode.getInstance(COSName.LIGHTEN)); assertEquals(BlendMode.COLOR_DODGE, BlendMode.getInstance(COSName.COLOR_DODGE)); assertEquals(BlendMode.COLOR_BURN, BlendMode.getInstance(COSName.COLOR_BURN)); assertEquals(BlendMode.HARD_LIGHT, BlendMode.getInstance(COSName.HARD_LIGHT)); assertEquals(BlendMode.SOFT_LIGHT, BlendMode.getInstance(COSName.SOFT_LIGHT)); assertEquals(BlendMode.DIFFERENCE, BlendMode.getInstance(COSName.DIFFERENCE)); assertEquals(BlendMode.EXCLUSION, BlendMode.getInstance(COSName.EXCLUSION)); assertEquals(BlendMode.HUE, BlendMode.getInstance(COSName.HUE)); assertEquals(BlendMode.SATURATION, BlendMode.getInstance(COSName.SATURATION)); assertEquals(BlendMode.LUMINOSITY, BlendMode.getInstance(COSName.LUMINOSITY)); assertEquals(BlendMode.COLOR, BlendMode.getInstance(COSName.COLOR)); COSArray cosArrayOverlay = new COSArray(); cosArrayOverlay.add(COSName.OVERLAY); assertEquals(BlendMode.OVERLAY, BlendMode.getInstance(cosArrayOverlay)); COSArray cosArrayInteger = new COSArray(); cosArrayInteger.add(COSInteger.get(0)); assertEquals(BlendMode.NORMAL, BlendMode.getInstance(cosArrayInteger)); }
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( MapHelper.toListMap( Map.Entry::getKey, p -> { ParamDefinition param = p.getValue(); if (param.getType() == ParamType.MAP) { MapParamDefinition mapParamDef = param.asMapParamDef(); if (mapParamDef.getValue() == null && (mapParamDef.getInternalMode() == InternalParamMode.OPTIONAL)) { return mapParamDef; } return MapParamDefinition.builder() .name(mapParamDef.getName()) .value(cleanupParams(mapParamDef.getValue())) .expression(mapParamDef.getExpression()) .name(mapParamDef.getName()) .validator(mapParamDef.getValidator()) .tags(mapParamDef.getTags()) .mode(mapParamDef.getMode()) .meta(mapParamDef.getMeta()) .build(); } else { return param; } })); Map<String, ParamDefinition> filtered = mapped.entrySet().stream() .filter( p -> { ParamDefinition param = p.getValue(); if (param.getInternalMode() == InternalParamMode.OPTIONAL) { if (param.getValue() == null && param.getExpression() == null) { return false; } else if (param.getType() == ParamType.MAP && param.asMapParamDef().getValue() != null && param.asMapParamDef().getValue().isEmpty()) { return false; } else { return true; } } else { Checks.checkTrue( param.getValue() != null || param.getExpression() != null, String.format( "[%s] is a required parameter (type=[%s])", p.getKey(), param.getType())); return true; } }) .collect(MapHelper.toListMap(Map.Entry::getKey, Map.Entry::getValue)); return cleanIntermediateMetadata(filtered); }
@Test public void testCleanupNoParams() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap("{}"); Map<String, ParamDefinition> cleanedParams = ParamsMergeHelper.cleanupParams(allParams); assertEquals(0, cleanedParams.size()); }
public void updateFileStore(FileStoreInfo fsInfo) throws DdlException { try { client.updateFileStore(fsInfo, serviceId); } catch (StarClientException e) { throw new DdlException("Failed to update file store, error: " + e.getMessage()); } }
@Test public void testUpdateFileStore() throws StarClientException, DdlException { S3FileStoreInfo s3FsInfo = S3FileStoreInfo.newBuilder() .setRegion("region").setEndpoint("endpoint").build(); FileStoreInfo fsInfo = FileStoreInfo.newBuilder().setFsKey("test-fskey") .setFsName("test-fsname").setFsType(FileStoreType.S3).setS3FsInfo(s3FsInfo).build(); new Expectations() { { client.updateFileStore(fsInfo, "1"); result = new StarClientException(StatusCode.INVALID_ARGUMENT, "mocked exception"); } }; Deencapsulation.setField(starosAgent, "serviceId", "1"); ExceptionChecker.expectThrowsWithMsg(DdlException.class, "Failed to update file store, error: INVALID_ARGUMENT:mocked exception", () -> starosAgent.updateFileStore(fsInfo)); }
public RunConfigurationExecutor getExecutor( String type ) { RunConfigurationProvider runConfigurationProvider = getProvider( type ); if ( runConfigurationProvider != null ) { return runConfigurationProvider.getExecutor(); } return null; }
@Test public void testGetExecutor() { DefaultRunConfigurationExecutor defaultRunConfigurationExecutor = (DefaultRunConfigurationExecutor) executionConfigurationManager.getExecutor( DefaultRunConfiguration.TYPE ); assertNotNull( defaultRunConfigurationExecutor ); }
public void cleanupOrphanedInternalTopics( final ServiceContext serviceContext, final Set<String> queryApplicationIds ) { final KafkaTopicClient topicClient = serviceContext.getTopicClient(); final Set<String> topicNames; try { topicNames = topicClient.listTopicNames(); } catch (KafkaResponseGetFailedException e) { LOG.error("Couldn't fetch topic names", e); return; } // Find any transient query topics final Set<String> orphanedQueryApplicationIds = topicNames.stream() .map(topicName -> queryApplicationIds.stream().filter(topicName::startsWith).findFirst()) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); for (final String queryApplicationId : orphanedQueryApplicationIds) { cleanupService.addCleanupTask( new QueryCleanupService.QueryCleanupTask( serviceContext, queryApplicationId, Optional.empty(), true, ksqlConfig.getKsqlStreamConfigProps() .getOrDefault( StreamsConfig.STATE_DIR_CONFIG, StreamsConfig.configDef().defaultValues().get(StreamsConfig.STATE_DIR_CONFIG)) .toString(), ksqlConfig.getString(KsqlConfig.KSQL_SERVICE_ID_CONFIG), ksqlConfig.getString(KsqlConfig.KSQL_PERSISTENT_QUERY_NAME_PREFIX_CONFIG))); } }
@Test public void skipNonMatchingTopics() { // Given when(topicClient.listTopicNames()).thenReturn(ImmutableSet.of(TOPIC1, TOPIC2, TOPIC3)); // When cleaner.cleanupOrphanedInternalTopics(serviceContext, ImmutableSet.of(APP_ID_2)); // Then verify(queryCleanupService, times(1)).addCleanupTask(taskCaptor.capture()); assertThat(taskCaptor.getAllValues().get(0).getAppId(), is(APP_ID_2)); }
@Override public Object toKsqlRow(final Schema connectSchema, final Object connectData) { if (connectData == null) { return null; } return toKsqlValue(schema, connectSchema, connectData, ""); }
@Test public void shouldReturnTimeType() { // Given: final ConnectDataTranslator connectToKsqlTranslator = new ConnectDataTranslator(Time.SCHEMA); // When: final Object row = connectToKsqlTranslator.toKsqlRow(Time.SCHEMA, new Date(100L)); // Then: assertTrue(row instanceof java.sql.Time); assertThat(((java.sql.Time) row).getTime(), is(100L)); }
long joinPosition() { long position = consumerPosition; for (final ReadablePosition subscriberPosition : subscriberPositions) { position = Math.min(subscriberPosition.getVolatile(), position); } return position; }
@Test void shouldHaveJoiningPositionZeroWhenNoSubscriptions() { assertThat(ipcPublication.joinPosition(), is(0L)); }
public List<CaseInsensitiveString> pathIncludingAncestor() { if (cachedPathIncludingAncestor == null) { cachedPathIncludingAncestor = Collections.unmodifiableList(pathToAncestor(-1)); } return cachedPathIncludingAncestor; }
@Test public void shouldReturnPath_includingActualAncestorNode() { PathFromAncestor path = new PathFromAncestor(new CaseInsensitiveString("grand-parent/parent/child")); assertThat(path.pathIncludingAncestor(), is(List.of(new CaseInsensitiveString("child"), new CaseInsensitiveString("parent"), new CaseInsensitiveString("grand-parent")))); }
public static String encodeOnionUrlV2(byte[] onionAddrBytes) { checkArgument(onionAddrBytes.length == 10); return BASE32.encode(onionAddrBytes) + ".onion"; }
@Test(expected = IllegalArgumentException.class) public void encodeOnionUrlV2_badLength() { TorUtils.encodeOnionUrlV2(new byte[11]); }
public static Coder<PublishResult> fullPublishResult() { return new PublishResultCoder( RESPONSE_METADATA_CODER, NullableCoder.of(AwsCoders.sdkHttpMetadata())); }
@Test public void testFullPublishResultIncludingHeadersDecodeEncodeEquals() throws Exception { CoderProperties.coderDecodeEncodeEqual( PublishResultCoders.fullPublishResult(), new PublishResult().withMessageId(UUID.randomUUID().toString())); PublishResult value = buildFullPublishResult(); PublishResult clone = CoderUtils.clone(PublishResultCoders.fullPublishResult(), value); assertThat( clone.getSdkResponseMetadata().getRequestId(), equalTo(value.getSdkResponseMetadata().getRequestId())); assertThat( clone.getSdkHttpMetadata().getHttpStatusCode(), equalTo(value.getSdkHttpMetadata().getHttpStatusCode())); assertThat( clone.getSdkHttpMetadata().getHttpHeaders(), equalTo(value.getSdkHttpMetadata().getHttpHeaders())); }
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null) { // We allow tombstones for anything; if there's garbage in the offsets for the connector, we don't // want to prevent users from being able to clean it up using the REST API continue; } Map<String, ?> sourcePartition = offsetEntry.getKey(); if (sourcePartition == null) { throw new ConnectException("Source partitions may not be null"); } MirrorUtils.validateSourcePartitionString(sourcePartition, CONSUMER_GROUP_ID_KEY); MirrorUtils.validateSourcePartitionString(sourcePartition, TOPIC_KEY); MirrorUtils.validateSourcePartitionPartition(sourcePartition); MirrorUtils.validateSourceOffset(sourcePartition, sourceOffset, true); } // We don't actually use these offsets in the task class, so no additional effort is required beyond just validating // the format of the user-supplied offsets return true; }
@Test public void testAlterOffsetsIncorrectPartitionKey() { MirrorCheckpointConnector connector = new MirrorCheckpointConnector(); assertThrows(ConnectException.class, () -> connector.alterOffsets(null, Collections.singletonMap( Collections.singletonMap("unused_partition_key", "unused_partition_value"), SOURCE_OFFSET ))); // null partitions are invalid assertThrows(ConnectException.class, () -> connector.alterOffsets(null, Collections.singletonMap( null, SOURCE_OFFSET ))); }
private Mono<Collection<TopicPartition>> filterPartitionsWithLeaderCheck(Collection<TopicPartition> partitions, boolean failOnUnknownLeader) { var targetTopics = partitions.stream().map(TopicPartition::topic).collect(Collectors.toSet()); return describeTopicsImpl(targetTopics) .map(descriptions -> filterPartitionsWithLeaderCheck( descriptions.values(), partitions::contains, failOnUnknownLeader)); }
@Test void filterPartitionsWithLeaderCheckThrowExceptionIfThereIsSomePartitionsWithoutLeaderAndFlagSet() { ThrowingCallable call = () -> ReactiveAdminClient.filterPartitionsWithLeaderCheck( List.of( // contains partitions with no leader new TopicDescription("t1", false, List.of( new TopicPartitionInfo(0, new Node(1, "n1", 9092), List.of(), List.of()), new TopicPartitionInfo(1, null, List.of(), List.of()))), new TopicDescription("t2", false, List.of( new TopicPartitionInfo(0, new Node(1, "n1", 9092), List.of(), List.of())) )), p -> true, // setting failOnNoLeader flag true ); assertThatThrownBy(call).isInstanceOf(ValidationException.class); }
@Override public Integer call() throws Exception { super.call(); try (var files = Files.walk(directory)) { List<Template> templates = files .filter(Files::isRegularFile) .filter(YamlFlowParser::isValidExtension) .map(path -> yamlFlowParser.parse(path.toFile(), Template.class)) .toList(); if (templates.isEmpty()) { stdOut("No template found on '{}'", directory.toFile().getAbsolutePath()); } try (DefaultHttpClient client = client()) { MutableHttpRequest<List<Template>> request = HttpRequest .POST(apiUri("/templates/") + namespace + "?delete=" + delete, templates); List<UpdateResult> updated = client.toBlocking().retrieve( this.requestOptions(request), Argument.listOf(UpdateResult.class) ); stdOut(updated.size() + " template(s) for namespace '" + namespace + "' successfully updated !"); updated.forEach(template -> stdOut("- " + template.getNamespace() + "." + template.getId())); } catch (HttpClientResponseException e) { TemplateValidateCommand.handleHttpException(e, "template"); return 1; } } catch (ConstraintViolationException e) { TemplateValidateCommand.handleException(e, "template"); return 1; } return 0; }
@Test void invalid() { URL directory = TemplateNamespaceUpdateCommandTest.class.getClassLoader().getResource("invalidsTemplates"); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.run(Map.of("kestra.templates.enabled", "true"), Environment.CLI, Environment.TEST)) { EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class); embeddedServer.start(); String[] args = { "--server", embeddedServer.getURL().toString(), "--user", "myuser:pass:word", "io.kestra.tests", directory.getPath(), }; Integer call = PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args); // assertThat(call, is(1)); assertThat(out.toString(), containsString("Unable to parse templates")); assertThat(out.toString(), containsString("must not be empty")); } }
@Override public void destroy() { if (this.snsClient != null) { try { this.snsClient.shutdown(); } catch (Exception e) { log.error("Failed to shutdown SNS client during destroy()", e); } } }
@Test void givenSnsClientIsNotNull_whenDestroy_thenShutdown() { node.destroy(); then(snsClientMock).should().shutdown(); }
public static UUnary create(Kind unaryOp, UExpression expression) { checkArgument( UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp); return new AutoValue_UUnary(unaryOp, expression); }
@Test public void rejectsNonUnaryOperations() { ULiteral sevenLit = ULiteral.intLit(7); assertThrows(IllegalArgumentException.class, () -> UUnary.create(Kind.PLUS, sevenLit)); }
@Override public void handle(final RoutingContext routingContext) { if (routingContext.request().isSSL()) { final String indicatedServerName = routingContext.request().connection() .indicatedServerName(); final String requestHost = routingContext.request().host(); if (indicatedServerName != null && requestHost != null) { // sometimes the port is present in the host header, remove it final String requestHostNoPort = requestHost.replaceFirst(":\\d+", ""); if (!requestHostNoPort.equals(indicatedServerName)) { log.error(String.format( "Sni check failed, host header: %s, sni value %s", requestHostNoPort, indicatedServerName) ); routingContext.fail(MISDIRECTED_REQUEST.code(), new KsqlApiException("This request was incorrectly sent to this ksqlDB server", Errors.ERROR_CODE_MISDIRECTED_REQUEST)); return; } } } routingContext.next(); }
@Test public void shouldNotCheckIfHostNull() { // Given: when(serverRequest.host()).thenReturn(null); // When: sniHandler.handle(routingContext); // Then: verify(routingContext, never()).fail(anyInt(), any()); verify(routingContext, times(1)).next(); }
@Override public void execute(SensorContext context) { FileSystem fs = context.fileSystem(); FilePredicates p = fs.predicates(); for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) { createIssues(file, context); } }
@Test public void execute_dataAndExecutionFlowsAreDetectedAndMessageIsFormatted() throws IOException { DefaultInputFile inputFile = newTestFile(IOUtils.toString(getClass().getResource("dataflow.xoo"), StandardCharsets.UTF_8)); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(fs.baseDir()); sensorContextTester.setFileSystem(fs); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); Issue issue = sensorContextTester.allIssues().iterator().next(); assertThat(issue.primaryLocation().messageFormattings()).isNotEmpty(); List<Issue.Flow> flows = issue.flows(); assertThat(flows).hasSize(2); List<DefaultIssueFlow> defaultIssueFlows = flows.stream().map(DefaultIssueFlow.class::cast).toList(); assertThat(defaultIssueFlows).extracting(DefaultIssueFlow::type).containsExactlyInAnyOrder(FlowType.DATA, FlowType.EXECUTION); assertThat(flows.get(0).locations()).extracting(IssueLocation::messageFormattings).isNotEmpty(); assertThat(flows.get(1).locations()).extracting(IssueLocation::messageFormattings).isNotEmpty(); }
@Override public long size() { return colIndex[n]; }
@Test public void testSize() { System.out.println("size"); assertEquals(7, sparse.size()); }
public boolean isScratch() { return "".equals(registry) && SCRATCH.equals(repository) && Strings.isNullOrEmpty(tag) && Strings.isNullOrEmpty(digest); }
@Test public void testIsScratch() throws InvalidImageReferenceException { Assert.assertTrue(ImageReference.parse("scratch").isScratch()); Assert.assertTrue(ImageReference.scratch().isScratch()); Assert.assertFalse(ImageReference.of("", "scratch", "").isScratch()); Assert.assertFalse(ImageReference.of(null, "scratch", null).isScratch()); }
@Override public String getDataSource() { return DataSourceConstant.MYSQL; }
@Test void testGetDataSource() { String dataSource = configInfoTagMapperByMySql.getDataSource(); assertEquals(DataSourceConstant.MYSQL, dataSource); }
public static String toJsonString(final Token<? extends TokenIdentifier> token ) throws IOException { return toJsonString(Token.class, toJsonMap(token)); }
@Test public void testHdfsFileStatusWithEcPolicy() throws IOException { final long now = Time.now(); final String parent = "/dir"; ErasureCodingPolicy dummyEcPolicy = new ErasureCodingPolicy("ecPolicy1", new ECSchema("EcSchema", 1, 1), 1024 * 2, (byte) 1); final HdfsFileStatus status = new HdfsFileStatus.Builder() .length(1001L) .replication(3) .blocksize(1L << 26) .mtime(now) .atime(now + 10) .perm(new FsPermission((short) 0644)) .owner("user") .group("group") .symlink(DFSUtil.string2Bytes("bar")) .path(DFSUtil.string2Bytes("foo")) .fileId(HdfsConstants.GRANDFATHER_INODE_ID) .ecPolicy(dummyEcPolicy) .flags(EnumSet.allOf(Flags.class)) .build(); final FileStatus fstatus = toFileStatus(status, parent); System.out.println("status = " + status); System.out.println("fstatus = " + fstatus); final String json = JsonUtil.toJsonString(status, true); System.out.println("json = " + json.replace(",", ",\n ")); final HdfsFileStatus s2 = JsonUtilClient.toFileStatus((Map<?, ?>) READER.readValue(json), true); final FileStatus fs2 = toFileStatus(s2, parent); System.out.println("s2 = " + s2); System.out.println("fs2 = " + fs2); Assert.assertEquals(status.getErasureCodingPolicy(), s2.getErasureCodingPolicy()); Assert.assertEquals(fstatus, fs2); }
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) { return index(keyFunction, Function.identity()); }
@Test public void index_supports_duplicate_keys() { ListMultimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId)); assertThat(multimap.keySet()).containsOnly(1, 2); assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C); assertThat(multimap.get(2)).containsOnly(MY_OBJ_2_B); }
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromString( result, forwarded, nonForwarded, readSet, inType, outType, false); }
@Test void testNonForwardedInvalidTypes1() { String[] nonForwardedFields = {"f1; f2"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsSingleFromString( sp, null, nonForwardedFields, null, threeIntTupleType, nestedPojoType)) .isInstanceOf(InvalidSemanticAnnotationException.class); }
public void putMap(Map<String, String> map) { if (map == null) { putNumber1(0); } else { Utils.checkArgument(map.size() < 256, "Map has to be smaller than 256 elements"); putNumber1(map.size()); for (Entry<String, String> entry : map.entrySet()) { if (entry.getKey().contains("=")) { throw new IllegalArgumentException("Keys cannot contain '=' sign. " + entry); } if (entry.getValue().contains("=")) { throw new IllegalArgumentException("Values cannot contain '=' sign. " + entry); } String val = entry.getKey() + "=" + entry.getValue(); putString(val); } } }
@Test(expected = IllegalArgumentException.class) public void testMapIncorrectValue() { ZFrame frame = new ZFrame(new byte[(1 + 10)]); ZNeedle needle = new ZNeedle(frame); Map<String, String> map = new HashMap<>(); map.put("key", "=alue"); needle.putMap(map); }
public boolean submitUnknownProcessingError(Message message, String details) { return submitProcessingErrorsInternal(message, ImmutableList.of(new Message.ProcessingError( ProcessingFailureCause.UNKNOWN, "Encountered an unrecognizable processing error", details))); }
@Test public void submitUnknownProcessingError_unknownProcessingErrorSubmittedToQueue() throws Exception { // given final Message msg = Mockito.mock(Message.class); when(msg.processingErrors()).thenReturn(List.of()); when(msg.supportsFailureHandling()).thenReturn(true); when(failureHandlingConfiguration.submitProcessingFailures()).thenReturn(true); when(failureHandlingConfiguration.keepFailedMessageDuplicate()).thenReturn(true); // when final boolean notFilterOut = underTest.submitUnknownProcessingError(msg, "Details of the unknown error!"); // then assertThat(notFilterOut).isTrue(); verify(failureSubmissionQueue, times(1)).submitBlocking(failureBatchCaptor.capture()); assertThat(failureBatchCaptor.getValue()).satisfies(fb -> { assertThat(fb.containsProcessingFailures()).isTrue(); assertThat(fb.size()).isEqualTo(1); assertThat(fb.getFailures().get(0)).satisfies(processingFailure -> { assertThat(processingFailure.failureType()).isEqualTo(FailureType.PROCESSING); assertThat(processingFailure.failureCause().label()).isEqualTo("UNKNOWN"); assertThat(processingFailure.message()).isEqualTo("Failed to process message with id 'UNKNOWN': Encountered an unrecognizable processing error"); assertThat(processingFailure.failureDetails()).isEqualTo("Details of the unknown error!"); assertThat(processingFailure.failureTimestamp()).isNotNull(); assertThat(processingFailure.failedMessage()).isEqualTo(msg); assertThat(processingFailure.targetIndex()).isNull(); assertThat(processingFailure.requiresAcknowledgement()).isFalse(); }); }); }
public static Serializable decode(final ByteBuf byteBuf) { int valueType = byteBuf.readUnsignedByte() & 0xff; StringBuilder result = new StringBuilder(); decodeValue(valueType, 1, byteBuf, result); return result.toString(); }
@Test void assertDecodeSmallJsonObjectWithUInt64() { List<JsonEntry> jsonEntries = new LinkedList<>(); jsonEntries.add(new JsonEntry(JsonValueTypes.UINT64, "key1", Long.MAX_VALUE)); jsonEntries.add(new JsonEntry(JsonValueTypes.UINT64, "key2", Long.MIN_VALUE)); ByteBuf payload = mockJsonObjectByteBuf(jsonEntries, true); String actual = (String) MySQLJsonValueDecoder.decode(payload); assertThat(actual, is("{\"key1\":9223372036854775807,\"key2\":9223372036854775808}")); }
RuleDto createNewRule(RulesRegistrationContext context, RulesDefinition.Rule ruleDef) { RuleDto newRule = createRuleWithSimpleFields(ruleDef, uuidFactory.create(), system2.now()); ruleDescriptionSectionsGeneratorResolver.generateFor(ruleDef).forEach(newRule::addRuleDescriptionSectionDto); context.created(newRule); return newRule; }
@Test public void from_whenRuleDefinitionDoesHaveCleanCodeAttribute_shouldReturnThisAttribute() { RulesDefinition.Rule ruleDef = getDefaultRule(CleanCodeAttribute.TESTED, RuleType.CODE_SMELL); RuleDto newRuleDto = underTest.createNewRule(context, ruleDef); assertThat(newRuleDto.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.TESTED); }
@Override public PageResult<FileDO> getFilePage(FilePageReqVO pageReqVO) { return fileMapper.selectPage(pageReqVO); }
@Test public void testGetFilePage() { // mock 数据 FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到 o.setPath("yunai"); o.setType("image/jpg"); o.setCreateTime(buildTime(2021, 1, 15)); }); fileMapper.insert(dbFile); // 测试 path 不匹配 fileMapper.insert(ObjectUtils.cloneIgnoreId(dbFile, o -> o.setPath("tudou"))); // 测试 type 不匹配 fileMapper.insert(ObjectUtils.cloneIgnoreId(dbFile, o -> { o.setType("image/png"); })); // 测试 createTime 不匹配 fileMapper.insert(ObjectUtils.cloneIgnoreId(dbFile, o -> { o.setCreateTime(buildTime(2020, 1, 15)); })); // 准备参数 FilePageReqVO reqVO = new FilePageReqVO(); reqVO.setPath("yunai"); reqVO.setType("jp"); reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 10), buildTime(2021, 1, 20)})); // 调用 PageResult<FileDO> pageResult = fileService.getFilePage(reqVO); // 断言 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); AssertUtils.assertPojoEquals(dbFile, pageResult.getList().get(0)); }
public static void main(String[] args) throws Exception { Tika tika = new Tika(); for (String file : args) { String type = tika.detect(new File(file)); System.out.println(file + ": " + type); } }
@Test public void testSimpleTypeDetector() throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PrintStream out = System.out; System.setOut(new PrintStream(buffer, true, UTF_8.name())); SimpleTypeDetector.main(new String[]{"pom.xml"}); System.setOut(out); assertContains("pom.xml: application/xml", buffer .toString(UTF_8.name()) .trim()); }
@Override public ProxyInvocationHandler parserInterfaceToProxy(Object target, String objectName) { // eliminate the bean without two phase annotation. Set<String> methodsToProxy = this.tccProxyTargetMethod(target); if (methodsToProxy.isEmpty()) { return null; } // register resource and enhance with interceptor DefaultResourceRegisterParser.get().registerResource(target, objectName); return new TccActionInterceptorHandler(target, methodsToProxy); }
@Test public void testNestTcc_should_commit() throws Exception { //given TccActionImpl tccAction = new TccActionImpl(); TccAction tccActionProxy = ProxyUtil.createProxy(tccAction, "oldtccAction"); Assertions.assertNotNull(tccActionProxy); NestTccActionImpl nestTccAction = new NestTccActionImpl(); nestTccAction.setTccAction(tccActionProxy); //when ProxyInvocationHandler proxyInvocationHandler = DefaultInterfaceParser.get().parserInterfaceToProxy(nestTccAction, nestTccAction.getClass().getName()); //then Assertions.assertNotNull(proxyInvocationHandler); //when NestTccAction nestTccActionProxy = ProxyUtil.createProxy(nestTccAction, "oldnestTccAction"); //then Assertions.assertNotNull(nestTccActionProxy); // transaction commit test GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate(); try { tx.begin(60000, "testBiz"); boolean result = nestTccActionProxy.prepare(null, 2); Assertions.assertTrue(result); if (result) { tx.commit(); } else { tx.rollback(); } } catch (Exception exx) { tx.rollback(); throw exx; } Assertions.assertTrue(nestTccAction.isCommit()); Assertions.assertTrue(tccAction.isCommit()); }
public static boolean compare(Object source, Object target) { if (source == target) { return true; } if (source == null || target == null) { return false; } if (source.equals(target)) { return true; } if (source instanceof Boolean) { return compare(((Boolean) source), target); } if (source instanceof Number) { return compare(((Number) source), target); } if (target instanceof Number) { return compare(((Number) target), source); } if (source instanceof Date) { return compare(((Date) source), target); } if (target instanceof Date) { return compare(((Date) target), source); } if (source instanceof String) { return compare(((String) source), target); } if (target instanceof String) { return compare(((String) target), source); } if (source instanceof Collection) { return compare(((Collection) source), target); } if (target instanceof Collection) { return compare(((Collection) target), source); } if (source instanceof Map) { return compare(((Map) source), target); } if (target instanceof Map) { return compare(((Map) target), source); } if (source.getClass().isEnum() || source instanceof Enum) { return compare(((Enum) source), target); } if (target.getClass().isEnum() || source instanceof Enum) { return compare(((Enum) target), source); } if (source.getClass().isArray()) { return compare(((Object[]) source), target); } if (target.getClass().isArray()) { return compare(((Object[]) target), source); } return compare(FastBeanCopier.copy(source, HashMap.class), FastBeanCopier.copy(target, HashMap.class)); }
@Test public void connectionTest() { Date date = new Date(); Assert.assertTrue(CompareUtils.compare(100, new BigDecimal("100"))); Assert.assertTrue(CompareUtils.compare(new BigDecimal("100"), 100.0D)); Assert.assertTrue(CompareUtils.compare(Arrays.asList(1, 2, 3), Arrays.asList("3", "2", "1"))); Assert.assertFalse(CompareUtils.compare(Arrays.asList(1, 2, 3), Arrays.asList("3", "3", "1"))); Assert.assertFalse(CompareUtils.compare(Arrays.asList(1, 2, 3), Arrays.asList("3", "1"))); Assert.assertFalse(CompareUtils.compare(Arrays.asList(1, 2, 3), Collections.emptyList())); Assert.assertFalse(CompareUtils.compare(Collections.emptyList(), Arrays.asList(1, 2, 3))); Assert.assertTrue(CompareUtils.compare(Arrays.asList(date, 3), Arrays.asList("3", DateFormatter.toString(date, "yyyy-MM-dd")))); }
public static URLArgumentPlaceholderType valueOf(final Properties queryProps) { try { return URLArgumentPlaceholderType.valueOf(queryProps.getProperty(KEY, URLArgumentPlaceholderType.NONE.name()).toUpperCase()); } catch (final IllegalArgumentException ex) { return URLArgumentPlaceholderType.NONE; } }
@Test void assertValueOfWithValidQueryProperties() { assertThat(URLArgumentPlaceholderTypeFactory.valueOf(PropertiesBuilder.build(new Property("placeholder-type", "environment"))), is(URLArgumentPlaceholderType.ENVIRONMENT)); }
public Path path() { return path; }
@Test void testPath() { Path path = Path.parse("foo/bar/baz", Name::of); List<String> expected = List.of("foo", "bar", "baz"); assertEquals(expected, path.segments()); assertEquals(expected.subList(1, 3), path.skip(1).segments()); assertEquals(expected.subList(0, 2), path.cut(1).segments()); assertEquals(expected.subList(1, 2), path.skip(1).cut(1).segments()); assertEquals("path '/foo/bar/baz/'", path.withTrailingSlash().toString()); assertEquals(path, path.withoutTrailingSlash().withoutTrailingSlash()); assertEquals(List.of("one", "foo", "bar", "baz", "two"), Path.empty().append(List.of("one")).append(path).append("two").segments()); assertEquals(List.of(expected.get(2), expected.get(0)), path.append(path).cut(2).skip(2).segments()); for (int i = 0; i < 3; i++) { assertEquals(path.head(i), path.cut(3 - i)); assertEquals(path.tail(i), path.skip(3 - i)); } assertThrows(NullPointerException.class, () -> path.append((String) null)); List<String> names = new ArrayList<>(); names.add(null); assertThrows(NullPointerException.class, () -> path.append(names)); assertEquals("name must match '[A-Za-z][A-Za-z0-9_-]{0,63}', but got: '???'", assertThrows(IllegalArgumentException.class, () -> path.append("???")).getMessage()); assertEquals("skip count must be at least '0' and at most '1', but got: '2'", assertThrows(IllegalArgumentException.class, () -> path.cut(2).skip(2)).getMessage()); assertEquals("path segment decoded cannot contain '/', but got: '/'", assertThrows(IllegalArgumentException.class, () -> Path.empty().append("%2525252525252525%2525252525253%25252532%252525%252534%36")).getMessage()); assertEquals("path segment decoded cannot contain '?', but got: '?'", assertThrows(IllegalArgumentException.class, () -> Path.empty().append("?")).getMessage()); assertEquals("path segment decoded cannot contain '#', but got: '#'", assertThrows(IllegalArgumentException.class, () -> Path.empty().append("#")).getMessage()); assertEquals("path segments cannot be \"\", \".\", or \"..\", but got: '..'", assertThrows(IllegalArgumentException.class, () -> Path.empty().append("%2E%25252E")).getMessage()); assertEquals("path segments cannot be \"\", \".\", or \"..\", but got: ''", assertThrows(IllegalArgumentException.class, () -> Path.parse("//")).getMessage()); }
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, Object> maMap = null; Map<String,Object> apMap = null; Map<Object, Object> footerMap = null; Section body = convertBody(message); if (message.isPersistent()) { if (header == null) { header = new Header(); } header.setDurable(true); } byte priority = message.getPriority(); if (priority != Message.DEFAULT_PRIORITY) { if (header == null) { header = new Header(); } header.setPriority(UnsignedByte.valueOf(priority)); } String type = message.getType(); if (type != null) { if (properties == null) { properties = new Properties(); } properties.setSubject(type); } MessageId messageId = message.getMessageId(); if (messageId != null) { if (properties == null) { properties = new Properties(); } properties.setMessageId(getOriginalMessageId(message)); } ActiveMQDestination destination = message.getDestination(); if (destination != null) { if (properties == null) { properties = new Properties(); } properties.setTo(destination.getQualifiedName()); if (maMap == null) { maMap = new HashMap<>(); } maMap.put(JMS_DEST_TYPE_MSG_ANNOTATION, destinationType(destination)); } ActiveMQDestination replyTo = message.getReplyTo(); if (replyTo != null) { if (properties == null) { properties = new Properties(); } properties.setReplyTo(replyTo.getQualifiedName()); if (maMap == null) { maMap = new HashMap<>(); } maMap.put(JMS_REPLY_TO_TYPE_MSG_ANNOTATION, destinationType(replyTo)); } String correlationId = message.getCorrelationId(); if (correlationId != null) { if (properties == null) { properties = new Properties(); } try { properties.setCorrelationId(AMQPMessageIdHelper.INSTANCE.toIdObject(correlationId)); } catch (AmqpProtocolException e) { properties.setCorrelationId(correlationId); } } long expiration = message.getExpiration(); if (expiration != 0) { long ttl = expiration - System.currentTimeMillis(); if (ttl < 0) { ttl = 1; } if (header == null) { header = new Header(); } header.setTtl(new UnsignedInteger((int) ttl)); if (properties == null) { properties = new Properties(); } properties.setAbsoluteExpiryTime(new Date(expiration)); } long timeStamp = message.getTimestamp(); if (timeStamp != 0) { if (properties == null) { properties = new Properties(); } properties.setCreationTime(new Date(timeStamp)); } // JMSX Message Properties int deliveryCount = message.getRedeliveryCounter(); if (deliveryCount > 0) { if (header == null) { header = new Header(); } header.setDeliveryCount(UnsignedInteger.valueOf(deliveryCount)); } String userId = message.getUserID(); if (userId != null) { if (properties == null) { properties = new Properties(); } properties.setUserId(new Binary(userId.getBytes(StandardCharsets.UTF_8))); } String groupId = message.getGroupID(); if (groupId != null) { if (properties == null) { properties = new Properties(); } properties.setGroupId(groupId); } int groupSequence = message.getGroupSequence(); if (groupSequence > 0) { if (properties == null) { properties = new Properties(); } properties.setGroupSequence(UnsignedInteger.valueOf(groupSequence)); } final Map<String, Object> entries; try { entries = message.getProperties(); } catch (IOException e) { throw JMSExceptionSupport.create(e); } for (Map.Entry<String, Object> entry : entries.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith(JMS_AMQP_PREFIX)) { if (key.startsWith(NATIVE, JMS_AMQP_PREFIX_LENGTH)) { // skip transformer appended properties continue; } else if (key.startsWith(ORIGINAL_ENCODING, JMS_AMQP_PREFIX_LENGTH)) { // skip transformer appended properties continue; } else if (key.startsWith(MESSAGE_FORMAT, JMS_AMQP_PREFIX_LENGTH)) { messageFormat = (long) TypeConversionSupport.convert(entry.getValue(), Long.class); continue; } else if (key.startsWith(HEADER, JMS_AMQP_PREFIX_LENGTH)) { if (header == null) { header = new Header(); } continue; } else if (key.startsWith(PROPERTIES, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } continue; } else if (key.startsWith(MESSAGE_ANNOTATION_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (maMap == null) { maMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_MESSAGE_ANNOTATION_PREFIX.length()); maMap.put(Symbol.valueOf(name), value); continue; } else if (key.startsWith(FIRST_ACQUIRER, JMS_AMQP_PREFIX_LENGTH)) { if (header == null) { header = new Header(); } header.setFirstAcquirer((boolean) TypeConversionSupport.convert(value, Boolean.class)); continue; } else if (key.startsWith(CONTENT_TYPE, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setContentType(Symbol.getSymbol((String) TypeConversionSupport.convert(value, String.class))); continue; } else if (key.startsWith(CONTENT_ENCODING, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setContentEncoding(Symbol.getSymbol((String) TypeConversionSupport.convert(value, String.class))); continue; } else if (key.startsWith(REPLYTO_GROUP_ID, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setReplyToGroupId((String) TypeConversionSupport.convert(value, String.class)); continue; } else if (key.startsWith(DELIVERY_ANNOTATION_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (daMap == null) { daMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_DELIVERY_ANNOTATION_PREFIX.length()); daMap.put(Symbol.valueOf(name), value); continue; } else if (key.startsWith(FOOTER_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (footerMap == null) { footerMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_FOOTER_PREFIX.length()); footerMap.put(Symbol.valueOf(name), value); continue; } } else if (key.startsWith(AMQ_SCHEDULED_MESSAGE_PREFIX )) { // strip off the scheduled message properties continue; } // The property didn't map into any other slot so we store it in the // Application Properties section of the message. if (apMap == null) { apMap = new HashMap<>(); } apMap.put(key, value); int messageType = message.getDataStructureType(); if (messageType == CommandTypes.ACTIVEMQ_MESSAGE) { // Type of command to recognize advisory message Object data = message.getDataStructure(); if(data != null) { apMap.put("ActiveMqDataStructureType", data.getClass().getSimpleName()); } } } final AmqpWritableBuffer buffer = new AmqpWritableBuffer(); encoder.setByteBuffer(buffer); if (header != null) { encoder.writeObject(header); } if (daMap != null) { encoder.writeObject(new DeliveryAnnotations(daMap)); } if (maMap != null) { encoder.writeObject(new MessageAnnotations(maMap)); } if (properties != null) { encoder.writeObject(properties); } if (apMap != null) { encoder.writeObject(new ApplicationProperties(apMap)); } if (body != null) { encoder.writeObject(body); } if (footerMap != null) { encoder.writeObject(new Footer(footerMap)); } return new EncodedMessage(messageFormat, buffer.getArray(), 0, buffer.getArrayLength()); }
@Test public void testConvertObjectMessageToAmqpMessageWithDataBody() throws Exception { ActiveMQObjectMessage outbound = createObjectMessage(TEST_OBJECT_VALUE); outbound.onSend(); outbound.storeContent(); JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer(); EncodedMessage encoded = transformer.transform(outbound); assertNotNull(encoded); Message amqp = encoded.decode(); assertNotNull(amqp.getBody()); assertTrue(amqp.getBody() instanceof Data); assertFalse(0 == ((Data) amqp.getBody()).getValue().getLength()); Object value = deserialize(((Data) amqp.getBody()).getValue().getArray()); assertNotNull(value); assertTrue(value instanceof UUID); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PCollectionsImmutableMap<?, ?> that = (PCollectionsImmutableMap<?, ?>) o; return underlying().equals(that.underlying()); }
@Test public void testEquals() { final HashPMap<Object, Object> mock = mock(HashPMap.class); assertEquals(new PCollectionsImmutableMap<>(mock), new PCollectionsImmutableMap<>(mock)); final HashPMap<Object, Object> someOtherMock = mock(HashPMap.class); assertNotEquals(new PCollectionsImmutableMap<>(mock), new PCollectionsImmutableMap<>(someOtherMock)); }
public Set<Flow> parseDataSet(ImmutableList<InformationElement> informationElements, Map<Integer, TemplateRecord> templateMap, ByteBuf setContent) { ImmutableSet.Builder<Flow> flowBuilder = ImmutableSet.builder(); // Padding: data records have no header and no fixed length, but the end of a data set (which are non-delimited series of data records), there _may_ be padding // (see https://datatracker.ietf.org/doc/html/rfc7011#section-3.3.1) // Furthermore it states: "The padding length MUST be shorter than any allowable record in this Set." // We could calculate the minimum record length from informationElements, but we would need to take into consideration that it might be made up of variable length elements. // Thus, it is much simpler to catch the exception and return the flows we have collected so far. int flowNum = 1; readFlows: while (setContent.isReadable()) { try { if (LOG.isTraceEnabled()) { LOG.trace("Parsing flow {}", flowNum); } flowNum++; final ImmutableMap.Builder<String, Object> fields = ImmutableMap.builder(); for (InformationElement informationElement : informationElements) { final int firstByte = setContent.readerIndex(); InformationElementDefinition desc = infoElemDefs.getDefinition(informationElement.id(), informationElement.enterpriseNumber()); switch (desc.dataType()) { // these are special because they can use reduced-size encoding (RFC 7011 Sec 6.2) case UNSIGNED8: case UNSIGNED16: case UNSIGNED32: case UNSIGNED64: long unsignedValue; switch (informationElement.length()) { case 1: unsignedValue = setContent.readUnsignedByte(); break; case 2: unsignedValue = setContent.readUnsignedShort(); break; case 3: unsignedValue = setContent.readUnsignedMedium(); break; case 4: unsignedValue = setContent.readUnsignedInt(); break; case 5: case 6: case 7: case 8: byte[] bytesBigEndian = {0, 0, 0, 0, 0, 0, 0, 0}; int firstIndex = 8 - informationElement.length(); setContent.readBytes(bytesBigEndian, firstIndex, informationElement.length()); unsignedValue = Longs.fromByteArray(bytesBigEndian); break; default: throw new IpfixException("Unexpected length for unsigned integer"); } fields.put(desc.fieldName(), unsignedValue); break; case SIGNED8: case SIGNED16: case SIGNED32: case SIGNED64: long signedValue; switch (informationElement.length()) { case 1: signedValue = setContent.readByte(); break; case 2: signedValue = setContent.readShort(); break; case 3: signedValue = setContent.readMedium(); break; case 4: signedValue = setContent.readUnsignedInt(); break; case 5: case 6: case 7: case 8: byte[] bytesBigEndian = {0, 0, 0, 0, 0, 0, 0, 0}; int firstIndex = 8 - informationElement.length() - 1; setContent.readBytes(bytesBigEndian, firstIndex, informationElement.length()); signedValue = Longs.fromByteArray(bytesBigEndian); break; default: throw new IpfixException("Unexpected length for unsigned integer"); } fields.put(desc.fieldName(), signedValue); break; case FLOAT32: case FLOAT64: double floatValue; switch (informationElement.length()) { case 4: floatValue = setContent.readFloat(); break; case 8: floatValue = setContent.readDouble(); break; default: throw new IpfixException("Unexpected length for float value: " + informationElement.length()); } fields.put(desc.fieldName(), floatValue); break; // the remaining types aren't subject to reduced-size encoding case MACADDRESS: byte[] macBytes = new byte[6]; setContent.readBytes(macBytes); fields.put(desc.fieldName(), String.format(Locale.ROOT, "%02x:%02x:%02x:%02x:%02x:%02x", macBytes[0], macBytes[1], macBytes[2], macBytes[3], macBytes[4], macBytes[5])); break; case IPV4ADDRESS: byte[] ipv4Bytes = new byte[4]; setContent.readBytes(ipv4Bytes); try { fields.put(desc.fieldName(), InetAddress.getByAddress(ipv4Bytes).getHostAddress()); } catch (UnknownHostException e) { throw new IpfixException("Unable to parse IPV4 address", e); } break; case IPV6ADDRESS: byte[] ipv6Bytes = new byte[16]; setContent.readBytes(ipv6Bytes); try { fields.put(desc.fieldName(), InetAddress.getByAddress(ipv6Bytes).getHostAddress()); } catch (UnknownHostException e) { throw new IpfixException("Unable to parse IPV6 address", e); } break; case BOOLEAN: final byte booleanByte = setContent.readByte(); switch (booleanByte) { case 1: fields.put(desc.fieldName(), true); break; case 2: fields.put(desc.fieldName(), false); break; default: throw new IpfixException("Invalid value for boolean: " + booleanByte); } break; case STRING: final CharSequence charSequence; if (informationElement.length() == 65535) { // variable length element, parse accordingly int length = getVarLength(setContent); charSequence = setContent.readCharSequence(length, StandardCharsets.UTF_8); } else { // fixed length element, just read the string from the buffer charSequence = setContent.readCharSequence(informationElement.length(), StandardCharsets.UTF_8); } fields.put(desc.fieldName(), String.valueOf(charSequence).replace("\0", "")); break; case OCTETARRAY: final byte[] octetArray; if (informationElement.length() == 65535) { int length = getVarLength(setContent); octetArray = new byte[length]; } else { octetArray = new byte[informationElement.length()]; } setContent.readBytes(octetArray); fields.put(desc.fieldName(), Hex.encodeHexString(octetArray)); break; case DATETIMESECONDS: final long dateTimeSeconds = setContent.readUnsignedInt(); fields.put(desc.fieldName(), ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateTimeSeconds), ZoneOffset.UTC)); break; case DATETIMEMILLISECONDS: final long dateTimeMills = setContent.readLong(); fields.put(desc.fieldName(), ZonedDateTime.ofInstant(Instant.ofEpochMilli(dateTimeMills), ZoneOffset.UTC)); break; case DATETIMEMICROSECONDS: case DATETIMENANOSECONDS: final long seconds = setContent.readUnsignedInt(); long fraction = setContent.readUnsignedInt(); if (desc.dataType() == InformationElementDefinition.DataType.DATETIMEMICROSECONDS) { // bottom 11 bits must be cleared for micros to ensure the precision is correct (RFC 7011 Sec 6.1.9) fraction = fraction & ~0x7FF; } fields.put(desc.fieldName(), ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds, fraction), ZoneOffset.UTC)); break; case BASICLIST: { // TODO add to field somehow int length = informationElement.length() == 65535 ? getVarLength(setContent) : setContent.readUnsignedByte(); ByteBuf listBuffer = setContent.readSlice(length); final short semantic = listBuffer.readUnsignedByte(); final InformationElement element = parseInformationElement(listBuffer); InformationElementDefinition def = infoElemDefs.getDefinition(element.id(), element.enterpriseNumber()); if (def == null) { LOG.error("Unable to find information element definition in basicList: id {} PEN {}, this is a bug, cannot parse packet.", element.id(), element.enterpriseNumber()); break; } else { LOG.warn("Skipping basicList data ({} bytes)", informationElement.length()); while (listBuffer.isReadable()) { // simply discard the bytes for now listBuffer.skipBytes(element.length()); } } break; } case SUBTEMPLATELIST: { // there are three possibilities here (compare https://tools.ietf.org/html/rfc6313#section-4.5.2): // 1. the data set's template has an explicit length // 2. the length is < 255 encoded as 1 byte, in variable length format (not recommended) // 3. the length is encoded as 3 bytes, in variable length format (recommended per RFC 6313) /* encoding format in this case is according to Figure 5: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Semantic | Template ID | ... | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | subTemplateList Content ... | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ... | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Semantic is one of: * 0xFF - undefined * 0x00 - noneOf * 0x01 - exactlyOneOf * 0x02 - oneOrMoreOf * 0x03 - allOf * 0x04 - ordered */ int length = informationElement.length() == 65535 ? getVarLength(setContent) : setContent.readUnsignedByte(); // adjust length for semantic + templateId length -= 3; LOG.debug("Remaining data buffer:\n{}", ByteBufUtil.prettyHexDump(setContent)); // TODO add to field somehow final short semantic = setContent.readUnsignedByte(); final int templateId = setContent.readUnsignedShort(); final TemplateRecord templateRecord = templateMap.get(templateId); if (templateRecord == null) { LOG.error("Unable to parse subtemplateList, because we don't have the template for it: {}, skipping data ({} bytes)", templateId, length); setContent.skipBytes(length); break; } final ByteBuf listContent = setContent.readSlice(length); // if this is not readable, it's an empty list final ImmutableList.Builder<Flow> flowsBuilder = ImmutableList.builder(); if (listContent.isReadable()) { flowsBuilder.addAll(parseDataSet(templateRecord.informationElements(), templateMap, listContent)); } final ImmutableList<Flow> flows = flowsBuilder.build(); // flatten arrays and fields into the field name until we have support for nested objects for (int i = 0; i < flows.size(); i++) { final String fieldPrefix = desc.fieldName() + "_" + i + "_"; flows.get(i).fields().forEach((field, value) -> { fields.put(fieldPrefix + field, value); }); } break; } case SUBTEMPLATEMULTILIST: { int length = informationElement.length() == 65535 ? getVarLength(setContent) : setContent.readUnsignedByte(); setContent.skipBytes(length); LOG.warn("subtemplateMultilist support is not implemented, skipping data ({} bytes)", length); break; } } if (LOG.isTraceEnabled()) { LOG.trace("Field {}:\n{}", informationElement.id(), ByteBufUtil.prettyHexDump(setContent, firstByte, setContent.readerIndex() - firstByte)); } } flowBuilder.add(Flow.create(fields.build())); } catch (IndexOutOfBoundsException ioobe) { // this can happen if we read past the valid flows into the optional padding following a record set. // to differentiate a bug and the legitimate trailing 0x00 bytes padding case, we actually consume the rest of the bytes and check that they are all 0. if (setContent.forEachByte(value -> value == 0x00) != -1) { // if we still have bytes left, it means we had non-zero bytes, thus not only padding. this is bad and probably a bug of some sort. LOG.error("Verify data record padding failed, trailing bytes were not all 0x00"); throw ioobe; } // label for clarity //noinspection UnnecessaryLabelOnBreakStatement break readFlows; } } return flowBuilder.build(); }
@Test public void parseDataSet() throws IOException { final ByteBuf packet = Utils.readPacket("templates-data.ipfix"); InformationElementDefinitions infoElementDefs = new InformationElementDefinitions(Resources.getResource("ipfix-iana-elements.json"), Resources.getResource("ixia-ied.json")); final IpfixMessage ipfixMessage = new IpfixParser(infoElementDefs).parseMessage(packet); assertThat(ipfixMessage).isNotNull(); final ImmutableList<TemplateRecord> templateRecords = ipfixMessage.templateRecords(); assertThat(templateRecords).hasSize(2); final TemplateRecord firstTemplate = templateRecords.get(0); assertThat(firstTemplate.templateId()).isEqualTo(256); assertThat(firstTemplate.informationElements()).hasSize(51) .containsExactly( InformationElement.create(1, 8, 0), InformationElement.create(2, 8, 0), InformationElement.create(4, 1, 0), InformationElement.create(6, 1, 0), InformationElement.create(7, 2, 0), InformationElement.create(8, 4, 0), InformationElement.create(10, 4, 0), InformationElement.create(11, 2, 0), InformationElement.create(12, 4, 0), InformationElement.create(14, 4, 0), InformationElement.create(16, 4, 0), InformationElement.create(17, 4, 0), InformationElement.create(32, 2, 0), InformationElement.create(136, 1, 0), InformationElement.create(152, 8, 0), InformationElement.create(153, 8, 0), InformationElement.create(110, 4, 3054), InformationElement.create(111, 65535, 3054), InformationElement.create(120, 4, 3054), InformationElement.create(121, 65535, 3054), InformationElement.create(122, 4, 3054), InformationElement.create(123, 65535, 3054), InformationElement.create(125, 65535, 3054), InformationElement.create(126, 4, 3054), InformationElement.create(127, 4, 3054), InformationElement.create(140, 4, 3054), InformationElement.create(141, 65535, 3054), InformationElement.create(142, 4, 3054), InformationElement.create(143, 65535, 3054), InformationElement.create(145, 65535, 3054), InformationElement.create(146, 4, 3054), InformationElement.create(147, 4, 3054), InformationElement.create(160, 1, 3054), InformationElement.create(161, 65535, 3054), InformationElement.create(162, 1, 3054), InformationElement.create(163, 65535, 3054), InformationElement.create(178, 65535, 3054), InformationElement.create(179, 65535, 3054), InformationElement.create(180, 2, 3054), InformationElement.create(182, 65535, 3054), InformationElement.create(183, 65535, 3054), InformationElement.create(184, 65535, 3054), InformationElement.create(185, 65535, 3054), InformationElement.create(186, 65535, 3054), InformationElement.create(187, 65535, 3054), InformationElement.create(188, 4, 3054), InformationElement.create(189, 65535, 3054), InformationElement.create(190, 65535, 3054), InformationElement.create(191, 65535, 3054), InformationElement.create(192, 65535, 3054), InformationElement.create(193, 4, 3054) ); final TemplateRecord secondTemplate = templateRecords.get(1); assertThat(secondTemplate.templateId()).isEqualTo(257); assertThat(secondTemplate.informationElements()) .hasSize(50) .containsOnly( InformationElement.create(1, 8, 0), InformationElement.create(2, 8, 0), InformationElement.create(4, 1, 0), InformationElement.create(6, 1, 0), InformationElement.create(7, 2, 0), InformationElement.create(10, 4, 0), InformationElement.create(11, 2, 0), InformationElement.create(14, 4, 0), InformationElement.create(16, 4, 0), InformationElement.create(17, 4, 0), InformationElement.create(27, 16, 0), InformationElement.create(28, 16, 0), InformationElement.create(136, 1, 0), InformationElement.create(139, 2, 0), InformationElement.create(152, 8, 0), InformationElement.create(153, 8, 0), InformationElement.create(110, 4, 3054), InformationElement.create(111, 65535, 3054), InformationElement.create(120, 4, 3054), InformationElement.create(121, 65535, 3054), InformationElement.create(122, 4, 3054), InformationElement.create(123, 65535, 3054), InformationElement.create(125, 65535, 3054), InformationElement.create(126, 4, 3054), InformationElement.create(127, 4, 3054), InformationElement.create(140, 4, 3054), InformationElement.create(141, 65535, 3054), InformationElement.create(142, 4, 3054), InformationElement.create(143, 65535, 3054), InformationElement.create(145, 65535, 3054), InformationElement.create(146, 4, 3054), InformationElement.create(147, 4, 3054), InformationElement.create(160, 1, 3054), InformationElement.create(161, 65535, 3054), InformationElement.create(162, 1, 3054), InformationElement.create(163, 65535, 3054), InformationElement.create(178, 65535, 3054), InformationElement.create(179, 65535, 3054), InformationElement.create(180, 2, 3054), InformationElement.create(182, 65535, 3054), InformationElement.create(183, 65535, 3054), InformationElement.create(184, 65535, 3054), InformationElement.create(185, 65535, 3054), InformationElement.create(186, 65535, 3054), InformationElement.create(187, 65535, 3054), InformationElement.create(188, 4, 3054), InformationElement.create(189, 65535, 3054), InformationElement.create(190, 65535, 3054), InformationElement.create(191, 65535, 3054), InformationElement.create(192, 65535, 3054) ); final ImmutableList<OptionsTemplateRecord> optionsTemplateRecords = ipfixMessage.optionsTemplateRecords(); assertThat(optionsTemplateRecords).describedAs("options template records").hasSize(1); assertThat(optionsTemplateRecords.get(0).scopeFields()) .describedAs("first record's scope fields") .hasSize(1); assertThat(ipfixMessage.flows()).describedAs("Flows") .hasSize(1); final Flow flow = ipfixMessage.flows().get(0); assertThat(flow.fields()).containsExactly( immutableEntry("octetDeltaCount", 103L), immutableEntry("packetDeltaCount", 1L), immutableEntry("protocolIdentifier", 17L), immutableEntry("tcpControlBits", 0L), immutableEntry("sourceTransportPort", 53L), immutableEntry("sourceIPv4Address", "36.83.97.149"), immutableEntry("ingressInterface", 1L), immutableEntry("destinationTransportPort", 30297L), immutableEntry("destinationIPv4Address", "36.83.97.7"), immutableEntry("egressInterface", 1L), immutableEntry("bgpSourceAsNumber", 17974L), immutableEntry("bgpDestinationAsNumber", 17974L), immutableEntry("icmpTypeCodeIPv4", 0L), immutableEntry("flowEndReason", 1L), immutableEntry("flowStartMilliseconds", ZonedDateTime.of(2018, 9, 13, 21, 39, 13, 249_000_000, ZoneOffset.UTC)), immutableEntry("flowEndMilliseconds", ZonedDateTime.of(2018, 9, 13, 21, 39, 13, 249_000_000, ZoneOffset.UTC)), immutableEntry("l7ApplicationId", 1L), immutableEntry("l7ApplicationName", "domain"), immutableEntry("sourceIpCountryCode", "ID"), immutableEntry("sourceIpCountryName", "Indonesia"), immutableEntry("sourceIpRegionCode", "SN"), immutableEntry("sourceIpRegionName", "South Sulawesi"), immutableEntry("sourceIpCityName", "Ballaparang"), immutableEntry("sourceIpLatitude", -5.146399974822998), immutableEntry("sourceIpLongitude", 119.44129943847656), immutableEntry("destinationIpCountryCode", "ID"), immutableEntry("destinationIpCountryName", "Indonesia"), immutableEntry("destinationIpRegionCode", "SN"), immutableEntry("destinationIpRegionName", "South Sulawesi"), immutableEntry("destinationIpCityName", "Ballaparang"), immutableEntry("destinationIpLatitude", -5.146399974822998), immutableEntry("destinationIpLongitude", 119.44129943847656), immutableEntry("osDeviceId", 0L), immutableEntry("osDeviceName", "unknown"), immutableEntry("browserId", 0L), immutableEntry("browserName", "-"), immutableEntry("sslConnectionEncryptionType", "Cleartext"), immutableEntry("sslEncryptionCipherName", "none"), immutableEntry("sslEncryptionKeyLength", 0L), immutableEntry("userAgent", ""), immutableEntry("hostName", ""), immutableEntry("uri", ""), immutableEntry("dnsText", ""), immutableEntry("sourceAsName", "TELKOMNET-AS2-AP PT Telekomunikasi Indonesia, ID"), immutableEntry("destinationAsName", "TELKOMNET-AS2-AP PT Telekomunikasi Indonesia, ID"), immutableEntry("transactionLatency", 53L), immutableEntry("dnsQueryHostName", "server-2453614b.example.int."), immutableEntry("dnsResponseHostName", "server-2453614b.example.int."), immutableEntry("dnsClasses", "IN"), immutableEntry("threatType", ""), immutableEntry("threatIpv4", "0.0.0.0") ); }
public static Credentials create(ECKeyPair ecKeyPair) { String address = Numeric.prependHexPrefix(Keys.getAddress(ecKeyPair)); return new Credentials(ecKeyPair, address); }
@Test public void testCredentialsFromECKeyPair() { Credentials credentials = Credentials.create(SampleKeys.PRIVATE_KEY_STRING, SampleKeys.PUBLIC_KEY_STRING); verify(credentials); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) { if ( n == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null")); } if ( scale == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "scale", "cannot be null")); } // Based on Table 76: Semantics of numeric functions, the scale is in range −6111 .. 6176 if (scale.compareTo(BigDecimal.valueOf(-6111)) < 0 || scale.compareTo(BigDecimal.valueOf(6176)) > 0) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "scale", "must be in range between -6111 to 6176.")); } return FEELFnResult.ofResult( n.setScale( scale.intValue(), RoundingMode.HALF_EVEN ) ); }
@Test void invokeRoundingOdd() { FunctionTestUtil.assertResult(decimalFunction.invoke(BigDecimal.valueOf(10.35), BigDecimal.ONE), BigDecimal.valueOf(10.4)); }
public static void free(final DirectBuffer buffer) { if (null != buffer) { free(buffer.byteBuffer()); } }
@Test @EnabledForJreRange(min = JAVA_9) void freeThrowsIllegalArgumentExceptionIfByteBufferIsASlice() { final ByteBuffer buffer = ByteBuffer.allocateDirect(4).slice(); assertThrows(IllegalArgumentException.class, () -> BufferUtil.free(buffer)); }
public ApplicationBuilder qosPort(Integer qosPort) { this.qosPort = qosPort; return getThis(); }
@Test void qosPort() { ApplicationBuilder builder = new ApplicationBuilder(); builder.qosPort(8080); Assertions.assertEquals(8080, builder.build().getQosPort()); }
public void setExtractor(ApacheHttpClientResourceExtractor extractor) { AssertUtil.notNull(extractor, "extractor cannot be null"); this.extractor = extractor; }
@Test(expected = IllegalArgumentException.class) public void testConfigSetCleaner() { SentinelApacheHttpClientConfig config = new SentinelApacheHttpClientConfig(); config.setExtractor(null); }
@Override public Dataset<PartitionStat> get() { StructType partitionSchema = spark.sql(String.format("SELECT * FROM %s.partitions", tableName)).schema(); try { partitionSchema.apply("partition"); return spark .sql(String.format("SELECT partition, file_count FROM %s.partitions", tableName)) .map(new TablePartitionStats.PartitionStatMapper(), Encoders.bean(PartitionStat.class)); } catch (IllegalArgumentException e) { return spark .sql(String.format("SELECT null, file_count FROM %s.partitions", tableName)) .map(new TablePartitionStats.PartitionStatMapper(), Encoders.bean(PartitionStat.class)); } }
@Test public void testNonPartitionedTablePartitionStats() throws Exception { final String testTable = "db.test_table_partition_stats_non_partitioned"; try (SparkSession spark = getSparkSession()) { spark.sql("USE openhouse"); spark.sql(String.format("CREATE TABLE %s (id INT, data STRING)", testTable)); spark.sql(String.format("INSERT INTO %s VALUES (0, '0')", testTable)); spark.sql(String.format("INSERT INTO %s VALUES (1, '1')", testTable)); TablePartitionStats tablePartitionStats = TablePartitionStats.builder().spark(spark).tableName(testTable).build(); List<PartitionStat> stats = tablePartitionStats.get().collectAsList(); Assertions.assertEquals(1, stats.size()); Assertions.assertTrue(stats.get(0).getValues().isEmpty()); Assertions.assertEquals(2, stats.get(0).getFileCount()); } }
public void commitBlock(final long workerId, final long usedBytesOnTier, final String tierAlias, final String mediumType, final long blockId, final long length) throws AlluxioStatusException { retryRPC(() -> { CommitBlockPRequest request = CommitBlockPRequest.newBuilder().setWorkerId(workerId).setUsedBytesOnTier(usedBytesOnTier) .setTierAlias(tierAlias).setMediumType(mediumType) .setBlockId(blockId).setLength(length).build(); mClient.commitBlock(request); return null; }, LOG, "CommitBlock", "workerId=%d,usedBytesOnTier=%d,tierAlias=%s,mediumType=%s,blockId=%d,length=%d", workerId, usedBytesOnTier, tierAlias, mediumType, blockId, length); }
@Test public void commitBlock() throws Exception { ConcurrentHashMap<Long, Long> committedBlocks = new ConcurrentHashMap<>(); final long workerId = 1L; final long blockId = 2L; final long usedBytesOnTier = 1024 * 1024L; final long length = 1024 * 1024L; final String tierAlias = "MEM"; final String mediumType = "MEM"; createMockService( new BlockMasterWorkerServiceGrpc.BlockMasterWorkerServiceImplBase() { @Override public void commitBlock(CommitBlockPRequest request, StreamObserver<CommitBlockPResponse> responseObserver) { long blockId = request.getBlockId(); long workerId = request.getWorkerId(); committedBlocks.put(blockId, workerId); responseObserver.onNext(CommitBlockPResponse.newBuilder().build()); responseObserver.onCompleted(); } }); BlockMasterClient client = new BlockMasterClient( MasterClientContext.newBuilder(ClientContext.create(mConf)).build() ); client.commitBlock(workerId, usedBytesOnTier, tierAlias, mediumType, blockId, length); assertEquals(1, committedBlocks.size()); assertEquals(workerId, (long) committedBlocks.get(blockId)); }
public TenantCapacity getTenantCapacity(String tenantId) { TenantCapacityMapper tenantCapacityMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.TENANT_CAPACITY); String sql = tenantCapacityMapper.select( Arrays.asList("id", "quota", "`usage`", "`max_size`", "max_aggr_count", "max_aggr_size", "tenant_id"), Collections.singletonList("tenant_id")); List<TenantCapacity> list = jdbcTemplate.query(sql, new Object[] {tenantId}, TENANT_CAPACITY_ROW_MAPPER); if (list.isEmpty()) { return null; } return list.get(0); }
@Test void testGetTenantCapacity() { List<TenantCapacity> list = new ArrayList<>(); TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant("test"); list.add(tenantCapacity); String tenantId = "testId"; when(jdbcTemplate.query(anyString(), eq(new Object[] {tenantId}), any(RowMapper.class))).thenReturn(list); TenantCapacity ret = service.getTenantCapacity(tenantId); assertEquals(tenantCapacity.getTenant(), ret.getTenant()); }
@Override public Optional<String> getScmRevision() { return scmRevision; }
@Test public void getScmRevision() { assertThat(new CiConfigurationImpl(null, "test").getScmRevision()).isEmpty(); assertThat(new CiConfigurationImpl("", "test").getScmRevision()).isEmpty(); assertThat(new CiConfigurationImpl(" ", "test").getScmRevision()).isEmpty(); assertThat(new CiConfigurationImpl("a7bdf2d", "test").getScmRevision()).hasValue("a7bdf2d"); }
@Override public void onWorkflowFinalized(Workflow workflow) { WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput()); WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow); String reason = workflow.getReasonForIncompletion(); LOG.info( "Workflow {} with execution_id [{}] is finalized with internal state [{}] and reason [{}]", summary.getIdentity(), workflow.getWorkflowId(), workflow.getStatus(), reason); metrics.counter( MetricConstants.WORKFLOW_STATUS_LISTENER_CALL_BACK_METRIC, getClass(), TYPE_TAG, "onWorkflowFinalized", MetricConstants.STATUS_TAG, workflow.getStatus().name()); if (reason != null && workflow.getStatus() == Workflow.WorkflowStatus.FAILED && reason.startsWith(MaestroStartTask.DEDUP_FAILURE_PREFIX)) { LOG.info( "Workflow {} with execution_id [{}] has not actually started, thus skip onWorkflowFinalized.", summary.getIdentity(), workflow.getWorkflowId()); return; // special case doing nothing } WorkflowInstance.Status instanceStatus = instanceDao.getWorkflowInstanceStatus( summary.getWorkflowId(), summary.getWorkflowInstanceId(), summary.getWorkflowRunId()); if (instanceStatus == null || (instanceStatus.isTerminal() && workflow.getStatus().isTerminal())) { LOG.info( "Workflow {} with execution_id [{}] does not exist or already " + "in a terminal state [{}] with internal state [{}], thus skip onWorkflowFinalized.", summary.getIdentity(), workflow.getWorkflowId(), instanceStatus, workflow.getStatus()); return; } Map<String, Task> realTaskMap = TaskHelper.getUserDefinedRealTaskMap(workflow); // cancel internally failed tasks realTaskMap.values().stream() .filter(task -> !StepHelper.retrieveStepStatus(task.getOutputData()).isTerminal()) .forEach(task -> maestroTask.cancel(workflow, task, null)); WorkflowRuntimeOverview overview = TaskHelper.computeOverview( objectMapper, summary, runtimeSummary.getRollupBase(), realTaskMap); try { validateAndUpdateOverview(overview, summary); switch (workflow.getStatus()) { case TERMINATED: // stopped due to stop request if (reason != null && reason.startsWith(FAILURE_REASON_PREFIX)) { update(workflow, WorkflowInstance.Status.FAILED, summary, overview); } else { update(workflow, WorkflowInstance.Status.STOPPED, summary, overview); } break; case TIMED_OUT: update(workflow, WorkflowInstance.Status.TIMED_OUT, summary, overview); break; default: // other status (FAILED, COMPLETED, PAUSED, RUNNING) to be handled here. Optional<Task.Status> done = TaskHelper.checkProgress(realTaskMap, summary, overview, true); switch (done.orElse(Task.Status.IN_PROGRESS)) { /** * This is a special status to indicate that the workflow has succeeded. Check {@link * TaskHelper#checkProgress} for more details. */ case FAILED_WITH_TERMINAL_ERROR: WorkflowInstance.Status nextStatus = AggregatedViewHelper.deriveAggregatedStatus( instanceDao, summary, WorkflowInstance.Status.SUCCEEDED, overview); if (!nextStatus.isTerminal()) { throw new MaestroInternalError( "Invalid status: [%s], expecting a terminal one", nextStatus); } update(workflow, nextStatus, summary, overview); break; case FAILED: case CANCELED: // due to step failure update(workflow, WorkflowInstance.Status.FAILED, summary, overview); break; case TIMED_OUT: update(workflow, WorkflowInstance.Status.TIMED_OUT, summary, overview); break; // all other status are invalid default: metrics.counter( MetricConstants.WORKFLOW_STATUS_LISTENER_CALL_BACK_METRIC, getClass(), TYPE_TAG, "invalidStatusOnWorkflowFinalized"); throw new MaestroInternalError( "Invalid status [%s] onWorkflowFinalized", workflow.getStatus()); } break; } } catch (MaestroInternalError | IllegalArgumentException e) { // non-retryable error and still fail the instance LOG.warn("onWorkflowFinalized is failed with a non-retryable error", e); metrics.counter( MetricConstants.WORKFLOW_STATUS_LISTENER_CALL_BACK_METRIC, getClass(), TYPE_TAG, "nonRetryableErrorOnWorkflowFinalized"); update( workflow, WorkflowInstance.Status.FAILED, summary, overview, Details.create( e.getMessage(), "onWorkflowFinalized is failed with non-retryable error.")); } }
@Test public void testWorkflowFinalizedComplete() { when(workflow.getStatus()).thenReturn(Workflow.WorkflowStatus.COMPLETED); statusListener.onWorkflowFinalized(workflow); Assert.assertEquals( 1L, metricRepo .getCounter( MetricConstants.WORKFLOW_STATUS_LISTENER_CALL_BACK_METRIC, MaestroWorkflowStatusListener.class, "type", "onWorkflowFinalized", "status", "COMPLETED") .count()); when(instanceDao.getWorkflowInstanceStatus(eq("test-workflow-id"), anyLong(), anyLong())) .thenReturn(WorkflowInstance.Status.SUCCEEDED); statusListener.onWorkflowFinalized(workflow); Assert.assertEquals( 2L, metricRepo .getCounter( MetricConstants.WORKFLOW_STATUS_LISTENER_CALL_BACK_METRIC, MaestroWorkflowStatusListener.class, "type", "onWorkflowFinalized", "status", "COMPLETED") .count()); }
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) { if (null == source) { return null; } T target = ReflectUtil.newInstanceIfPossible(tClass); copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); return target; }
@Test public void copyPropertiesMapToMapIgnoreNullTest() { // 测试MapToMap final Map<String, Object> p1 = new HashMap<>(); p1.put("isSlow", true); p1.put("name", "测试"); p1.put("subName", null); final Map<String, Object> map = MapUtil.newHashMap(); BeanUtil.copyProperties(p1, map, CopyOptions.create().setIgnoreNullValue(true)); assertTrue((Boolean) map.get("isSlow")); assertEquals("测试", map.get("name")); assertFalse(map.containsKey("subName")); }
public B accesslog(String accesslog) { this.accesslog = accesslog; return getThis(); }
@Test void accesslog() { ServiceBuilder builder = new ServiceBuilder(); builder.accesslog("accesslog"); Assertions.assertEquals("accesslog", builder.build().getAccesslog()); }
public static @NonNull String quoteArgument(@NonNull String argument) { if (!NEEDS_QUOTING.matcher(argument).find()) return argument; StringBuilder sb = new StringBuilder(); sb.append('"'); int end = argument.length(); for (int i = 0; i < end; i++) { int nrBackslashes = 0; while (i < end && argument.charAt(i) == '\\') { i++; nrBackslashes++; } if (i == end) { // backslashes at the end of the argument must be escaped so the terminate quote isn't nrBackslashes = nrBackslashes * 2; } else if (argument.charAt(i) == '"') { // backslashes preceding a quote all need to be escaped along with the quote nrBackslashes = nrBackslashes * 2 + 1; } // else backslashes have no special meaning and don't need to be escaped here sb.append("\\".repeat(Math.max(0, nrBackslashes))); if (i < end) { sb.append(argument.charAt(i)); } } return sb.append('"').toString(); }
@Test public void testQuoteArgument_OnlyQuotesWhenNecessary() { for (String arg : Arrays.asList("", "foo", "foo-bar", "C:\\test\\path", "http://www.example.com/")) { assertEquals(arg, WindowsUtil.quoteArgument(arg)); } }
public static long parseBytes(String text) throws IllegalArgumentException { Objects.requireNonNull(text, "text cannot be null"); final String trimmed = text.trim(); if (trimmed.isEmpty()) { throw new IllegalArgumentException("argument is an empty- or whitespace-only string"); } final int len = trimmed.length(); int pos = 0; char current; while (pos < len && (current = trimmed.charAt(pos)) >= '0' && current <= '9') { pos++; } final String number = trimmed.substring(0, pos); final String unit = trimmed.substring(pos).trim().toLowerCase(Locale.US); if (number.isEmpty()) { throw new NumberFormatException("text does not start with a number"); } final long value; try { value = Long.parseLong(number); // this throws a NumberFormatException on overflow } catch (NumberFormatException e) { throw new IllegalArgumentException( "The value '" + number + "' cannot be re represented as 64bit number (numeric overflow)."); } final long multiplier = parseUnit(unit).map(MemoryUnit::getMultiplier).orElse(1L); final long result = value * multiplier; // check for overflow if (result / multiplier != value) { throw new IllegalArgumentException( "The value '" + text + "' cannot be re represented as 64bit number of bytes (numeric overflow)."); } return result; }
@Test void testParseNumberOverflow() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> MemorySize.parseBytes("100000000000000000000000000000000 bytes")); }
public FederationPolicyManager getPolicyManager(String queueName) throws YarnException { FederationPolicyManager policyManager = policyManagerMap.get(queueName); // If we don't have the policy manager cached, pull configuration // from the FederationStateStore to create and cache it if (policyManager == null) { try { // If we don't have the configuration cached, pull it // from the stateStore SubClusterPolicyConfiguration conf = policyConfMap.get(queueName); if (conf == null) { conf = stateStore.getPolicyConfiguration(queueName); } // If configuration is still null, it does not exist in the // FederationStateStore if (conf == null) { LOG.info("Read null policy for queue {}.", queueName); return null; } // Generate PolicyManager based on PolicyManagerType. String policyManagerType = conf.getType(); policyManager = FederationPolicyUtils.instantiatePolicyManager(policyManagerType); policyManager.setQueue(queueName); // If PolicyManager supports Weighted PolicyInfo, it means that // we need to use this parameter to determine which sub-cluster the router goes to // or which sub-cluster the container goes to. if (policyManager.isSupportWeightedPolicyInfo()) { ByteBuffer weightedPolicyInfoParams = conf.getParams(); if (weightedPolicyInfoParams == null) { LOG.warn("Warning: Queue = {}, FederationPolicyManager {} WeightedPolicyInfo is empty.", queueName, policyManagerType); return null; } WeightedPolicyInfo weightedPolicyInfo = WeightedPolicyInfo.fromByteBuffer(conf.getParams()); policyManager.setWeightedPolicyInfo(weightedPolicyInfo); } else { LOG.warn("Warning: FederationPolicyManager of unsupported WeightedPolicyInfo type {}, " + "initialization may be incomplete.", policyManager.getClass()); } policyManagerMap.put(queueName, policyManager); policyConfMap.put(queueName, conf); } catch (YarnException e) { LOG.error("Error reading SubClusterPolicyConfiguration from state " + "store for queue: {}", queueName); throw e; } } return policyManager; }
@Test public void testGetPolicy() throws YarnException { WeightedLocalityPolicyManager manager = (WeightedLocalityPolicyManager) policyFacade .getPolicyManager(TEST_QUEUE); Assert.assertEquals(testConf, manager.serializeConf()); }