focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public static final StartTime absolute(Instant absoluteStart) {
return new StartTime(StartTimeOption.ABSOLUTE, null, absoluteStart);
}
|
@Test
public void testStopAbsolute() {
StopTime st = StopTime.absolute(OffsetDateTime
.of(2017, 3, 20, 11, 43, 11, 0, ZoneOffset.ofHours(-7))
.toInstant());
assertEquals(StopTimeOption.ABSOLUTE, st.option());
assertNull(st.relativeTime());
assertEquals("2017-03-20T11:43:11-07:00", st
.absoluteTime()
.atOffset(ZoneOffset.ofHours(-7))
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
|
public static List<KiePMMLFieldOperatorValue> getXORConstraintEntryFromSimplePredicates(final List<Predicate> predicates, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) {
return predicates.stream()
.filter(predicate -> predicate instanceof SimplePredicate)
.map(predicate -> {
SimplePredicate simplePredicate = (SimplePredicate) predicate;
String fieldName = fieldTypeMap.get(simplePredicate.getField()).getGeneratedType();
OPERATOR operator = OPERATOR.byName(simplePredicate.getOperator().value());
Object value = getCorrectlyFormattedObject(simplePredicate, fieldTypeMap);
return new KiePMMLFieldOperatorValue(fieldName, null, Collections.singletonList(new KiePMMLOperatorValue(operator, value)), null);
}).collect(Collectors.toList());
}
|
@Test
void getXORConstraintEntryFromSimplePredicates() {
List<Predicate> predicates = new ArrayList<>(simplePredicates);
List<KiePMMLFieldOperatorValue> retrieved = KiePMMLASTFactoryUtils
.getXORConstraintEntryFromSimplePredicates(predicates, fieldTypeMap);
assertThat(retrieved).isNotNull();
assertThat(retrieved).hasSameSizeAs(simplePredicates);
commonVerifyKiePMMLFieldOperatorValueList(retrieved, null);
}
|
public CompatibilityInfoMap checkRestSpecVsSnapshot(String prevRestSpecPath, String currSnapshotPath, CompatibilityLevel compatLevel)
{
return checkCompatibility(prevRestSpecPath, currSnapshotPath, compatLevel, true);
}
|
@Test
public void testCompatibleRestSpecVsSnapshot()
{
final RestLiSnapshotCompatibilityChecker checker = new RestLiSnapshotCompatibilityChecker();
final CompatibilityInfoMap infoMap = checker.checkRestSpecVsSnapshot(RESOURCES_DIR + FS + "idls" + FS + "twitter-statuses.restspec.json",
RESOURCES_DIR + FS + "snapshots" + FS + "twitter-statuses.snapshot.json",
CompatibilityLevel.EQUIVALENT);
Assert.assertTrue(infoMap.isEquivalent());
}
|
@Override
public final String toString() {
return ", " + columnName + " = " + getRightValue();
}
|
@Test
void assertParameterMarkerGeneratedKeyAssignmentTokenToString() {
generatedKeyAssignmentToken = new ParameterMarkerGeneratedKeyAssignmentToken(0, "id");
String resultParameterMarkerGeneratedKeyAssignmentTokenToString = generatedKeyAssignmentToken.toString();
assertThat(resultParameterMarkerGeneratedKeyAssignmentTokenToString, is(", id = ?"));
}
|
@Override
public boolean accept(Object object) {
return factToCheck.stream()
.allMatch(factCheckerHandle ->
factCheckerHandle.getClazz().isAssignableFrom(object.getClass()) &&
factCheckerHandle.getCheckFuction().apply(object).isValid());
}
|
@Test
public void acceptWithFailure() {
ConditionFilter conditionFilterFail = createConditionFilter(object -> ValueWrapper.errorWithValidValue(null, null));
assertThat(conditionFilterFail.accept("String")).isFalse();
}
|
public static boolean isMatch(String str, String exp) {
int strIndex = 0;
int expIndex = 0;
int starIndex = -1; //记录上一个 '*' 的位置
while (strIndex < str.length()) {
final char pkgChar = str.charAt(strIndex);
final char expChar = expIndex < exp.length() ? exp.charAt(expIndex) : '\0';
if (pkgChar == expChar) { //字符相等
strIndex++;
expIndex++;
} else if (expChar == '*') { //遇到'*', 记录'*'的位置,并记录 expIndex 和 match
starIndex = expIndex;
expIndex++;
} else if (starIndex != -1) { //不是上述两种情况,无法匹配,因此回溯
expIndex = starIndex + 1;
strIndex++;
} else { //其他情况, 直接返回false
return false;
}
}
//检测 exp 尾部是否全部都为 '*'
while (expIndex < exp.length() && exp.charAt(expIndex) == '*') {
expIndex++;
}
//若 exp 尾部全部为 '*',说明匹配
return expIndex == exp.length();
}
|
@Test
public void testIsMatch() {
Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "cn.myperf4j*abc"));
Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "*.myperf4j*abc"));
Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "*.myperf4j*a*c"));
Assert.assertFalse(isMatch("cn.myperf4j.config.abc", "*.myperf4j*ac"));
Assert.assertFalse(isMatch("cn.myperf4j.config.abc", "a*.myperf4j*ac"));
Assert.assertFalse(isMatch("cn.myperf4j.config.abc", "a*.myperf4j.a*"));
}
|
@VisibleForTesting
static List<Tuple2<ConfigGroup, String>> generateTablesForClass(
Class<?> optionsClass, Collection<OptionWithMetaInfo> optionWithMetaInfos) {
ConfigGroups configGroups = optionsClass.getAnnotation(ConfigGroups.class);
List<OptionWithMetaInfo> allOptions = selectOptionsToDocument(optionWithMetaInfos);
if (allOptions.isEmpty()) {
return Collections.emptyList();
}
List<Tuple2<ConfigGroup, String>> tables;
if (configGroups != null) {
tables = new ArrayList<>(configGroups.groups().length + 1);
Tree tree = new Tree(configGroups.groups(), allOptions);
for (ConfigGroup group : configGroups.groups()) {
List<OptionWithMetaInfo> configOptions = tree.findConfigOptions(group);
if (!configOptions.isEmpty()) {
sortOptions(configOptions);
tables.add(Tuple2.of(group, toHtmlTable(configOptions)));
}
}
List<OptionWithMetaInfo> configOptions = tree.getDefaultOptions();
if (!configOptions.isEmpty()) {
sortOptions(configOptions);
tables.add(Tuple2.of(null, toHtmlTable(configOptions)));
}
} else {
sortOptions(allOptions);
tables = Collections.singletonList(Tuple2.of(null, toHtmlTable(allOptions)));
}
return tables;
}
|
@Test
void testOverrideDefault() {
final String expectedTable =
"<table class=\"configuration table table-bordered\">\n"
+ " <thead>\n"
+ " <tr>\n"
+ " <th class=\"text-left\" style=\"width: 20%\">Key</th>\n"
+ " <th class=\"text-left\" style=\"width: 15%\">Default</th>\n"
+ " <th class=\"text-left\" style=\"width: 10%\">Type</th>\n"
+ " <th class=\"text-left\" style=\"width: 55%\">Description</th>\n"
+ " </tr>\n"
+ " </thead>\n"
+ " <tbody>\n"
+ " <tr>\n"
+ " <td><h5>first.option.a</h5></td>\n"
+ " <td style=\"word-wrap: break-word;\">default_1</td>\n"
+ " <td>Integer</td>\n"
+ " <td>This is example description for the first option.</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td><h5>second.option.a</h5></td>\n"
+ " <td style=\"word-wrap: break-word;\">default_2</td>\n"
+ " <td>String</td>\n"
+ " <td>This is long example description for the second option.</td>\n"
+ " </tr>\n"
+ " </tbody>\n"
+ "</table>\n";
final String htmlTable =
ConfigOptionsDocGenerator.generateTablesForClass(
TestConfigGroupWithOverriddenDefault.class,
ConfigurationOptionLocator.extractConfigOptions(
TestConfigGroupWithOverriddenDefault.class))
.get(0)
.f1;
assertThat(htmlTable).isEqualTo(expectedTable);
}
|
protected void checkRunningTxnExceedLimit(TransactionState.LoadJobSourceType sourceType) throws RunningTxnExceedException {
switch (sourceType) {
case ROUTINE_LOAD_TASK:
// no need to check limit for routine load task:
// 1. the number of running routine load tasks is limited by Config.max_routine_load_task_num_per_be
// 2. if we add routine load txn to runningTxnNums, runningTxnNums will always be occupied by routine load,
// and other txn may not be able to submitted.
break;
case LAKE_COMPACTION:
// no need to check limit for cloud native table compaction.
// high frequency and small batch loads may cause compaction execute rarely.
break;
default:
if (runningTxnNums >= Config.max_running_txn_num_per_db) {
throw new RunningTxnExceedException("current running txns on db " + dbId + " is "
+ runningTxnNums + ", larger than limit " + Config.max_running_txn_num_per_db);
}
break;
}
}
|
@Test
public void testCheckRunningTxnExceedLimit() {
int maxRunningTxnNumPerDb = Config.max_running_txn_num_per_db;
DatabaseTransactionMgr mgr = new DatabaseTransactionMgr(0, masterGlobalStateMgr);
Deencapsulation.setField(mgr, "runningTxnNums", maxRunningTxnNumPerDb);
ExceptionChecker.expectThrowsNoException(
() -> mgr.checkRunningTxnExceedLimit(TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK));
ExceptionChecker.expectThrowsNoException(
() -> mgr.checkRunningTxnExceedLimit(TransactionState.LoadJobSourceType.LAKE_COMPACTION));
ExceptionChecker.expectThrows(RunningTxnExceedException.class,
() -> mgr.checkRunningTxnExceedLimit(TransactionState.LoadJobSourceType.BACKEND_STREAMING));
}
|
public int validate(
final ServiceContext serviceContext,
final List<ParsedStatement> statements,
final SessionProperties sessionProperties,
final String sql
) {
requireSandbox(serviceContext);
final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext));
final Injector injector = injectorFactory.apply(ctx, serviceContext);
final KsqlConfig ksqlConfig = ctx.getKsqlConfig();
int numPersistentQueries = 0;
for (final ParsedStatement parsed : statements) {
final PreparedStatement<?> prepared = ctx.prepare(
parsed,
(isVariableSubstitutionEnabled(sessionProperties, ksqlConfig)
? sessionProperties.getSessionVariables()
: Collections.emptyMap())
);
final ConfiguredStatement<?> configured = ConfiguredStatement.of(prepared,
SessionConfig.of(ksqlConfig, sessionProperties.getMutableScopedProperties())
);
final int currNumPersistentQueries = validate(
serviceContext,
configured,
sessionProperties,
ctx,
injector
);
numPersistentQueries += currNumPersistentQueries;
if (currNumPersistentQueries > 0
&& QueryCapacityUtil.exceedsPersistentQueryCapacity(ctx, ksqlConfig)) {
QueryCapacityUtil.throwTooManyActivePersistentQueriesException(ctx, ksqlConfig, sql);
}
}
return numPersistentQueries;
}
|
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT")
@Test
public void shouldCallPrepareStatementWithEmptySessionVariablesIfSubstitutionDisabled() {
// Given
givenRequestValidator(ImmutableMap.of(CreateStream.class, statementValidator));
when(ksqlConfig.getBoolean(KsqlConfig.KSQL_VARIABLE_SUBSTITUTION_ENABLE)).thenReturn(false);
// When
final List<ParsedStatement> statements = givenParsed(SOME_STREAM_SQL);
validator.validate(serviceContext, statements, sessionProperties, "sql");
// Then
verify(sandboxEngine).prepare(statements.get(0), Collections.emptyMap());
verify(sessionProperties, never()).getSessionVariables();
}
|
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
}
|
@Test
public void parse_density_ldpi() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("ldpi", config);
assertThat(config.density).isEqualTo(DENSITY_LOW);
}
|
@Override
public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) {
return getDescriptionInHtml(rule)
.map(this::generateSections)
.orElse(emptySet());
}
|
@Test
public void parse_to_risk_description_fields_when_desc_contains_no_section() {
String descriptionWithoutTitles = "description without titles";
when(rule.htmlDescription()).thenReturn(descriptionWithoutTitles);
Set<RuleDescriptionSectionDto> results = generator.generateSections(rule);
Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent));
assertThat(sectionKeyToContent).hasSize(2)
.containsEntry(ROOT_CAUSE_SECTION_KEY, descriptionWithoutTitles)
.containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription());
}
|
@Override public SlotAssignmentResult ensure(long key1, long key2) {
assert key1 != unassignedSentinel : "ensure() called with key1 == nullKey1 (" + unassignedSentinel + ')';
return super.ensure0(key1, key2);
}
|
@Test
public void testPut() {
final long key1 = randomKey();
final long key2 = randomKey();
SlotAssignmentResult slot = hsa.ensure(key1, key2);
assertTrue(slot.isNew());
final long valueAddress = slot.address();
assertNotEquals(NULL_ADDRESS, valueAddress);
slot = hsa.ensure(key1, key2);
assertFalse(slot.isNew());
assertEquals(valueAddress, slot.address());
}
|
@Override
public NacosUser authenticate(String username, String rawPassword) throws AccessException {
if (StringUtils.isBlank(username) || StringUtils.isBlank(rawPassword)) {
throw new AccessException("user not found!");
}
NacosUserDetails nacosUserDetails = (NacosUserDetails) userDetailsService.loadUserByUsername(username);
if (nacosUserDetails == null || !PasswordEncoderUtil.matches(rawPassword, nacosUserDetails.getPassword())) {
throw new AccessException("user not found!");
}
return new NacosUser(nacosUserDetails.getUsername(), jwtTokenManager.createToken(username));
}
|
@Test
void testAuthenticate6() throws AccessException {
NacosUser nacosUser = new NacosUser();
when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser);
NacosUser authenticate = abstractAuthenticationManager.authenticate("token");
assertEquals(nacosUser, authenticate);
}
|
public static void copyStream(InputStream input, Writer output) throws IOException {
try (InputStreamReader inputStreamReader = new InputStreamReader(input)) {
char[] buffer = new char[1024]; // Adjust if you want
int bytesRead;
while ((bytesRead = inputStreamReader.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
}
|
@Test
void testCopyStreamOutputStream() throws IOException {
InputStream inputStream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copyStream(inputStream, outputStream);
assertThat(outputStream.toString()).contains("test");
}
|
@Override
public void exists(final String path, final boolean watch, final AsyncCallback.StatCallback cb, final Object ctx)
{
if (!SymlinkUtil.containsSymlink(path))
{
_zk.exists(path, watch, cb, ctx);
}
else
{
SymlinkStatCallback compositeCallback = new SymlinkStatCallback(path, _defaultWatcher, cb);
exists0(path, watch ? compositeCallback : null, compositeCallback, ctx);
}
}
|
@Test
public void testSymlinkWithExistWatch3() throws InterruptedException, ExecutionException
{
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AsyncCallback.StatCallback existCallback = new AsyncCallback.StatCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, Stat stat)
{
KeeperException.Code result = KeeperException.Code.get(rc);
Assert.assertEquals(result, KeeperException.Code.OK);
latch.countDown();
}
};
Watcher existWatch = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
Assert.assertEquals(event.getType(), Event.EventType.NodeCreated);
_zkClient.getZooKeeper().exists(event.getPath(), null, existCallback, null);
}
};
AsyncCallback.StatCallback existCallback2 = new AsyncCallback.StatCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, Stat stat)
{
KeeperException.Code result = KeeperException.Code.get(rc);
Assert.assertEquals(result, KeeperException.Code.NONODE);
latch2.countDown();
}
};
// symlink /$link doesn't exist.
_zkClient.getZooKeeper().exists("/$link", existWatch, existCallback2, null);
latch2.await(30, TimeUnit.SECONDS);
// create symlink /$link -> /foo/bar. existWatch should be notified.
_zkClient.createSymlink("/$link", "/foo/bar", new FutureCallback<>());
latch.await(30, TimeUnit.SECONDS);
// delete symlink /$link
_zkClient.removeNodeUnsafe("/$link", new FutureCallback<>());
}
|
public PutMessageResult putMessageReturnResult(MessageExtBrokerInner messageInner) {
LOGGER.debug("[BUG-TO-FIX] Thread:{} msgID:{}", Thread.currentThread().getName(), messageInner.getMsgId());
PutMessageResult result = store.putMessage(messageInner);
if (result != null && result.getPutMessageStatus() == PutMessageStatus.PUT_OK) {
this.brokerController.getBrokerStatsManager().incTopicPutNums(messageInner.getTopic());
this.brokerController.getBrokerStatsManager().incTopicPutSize(messageInner.getTopic(),
result.getAppendMessageResult().getWroteBytes());
this.brokerController.getBrokerStatsManager().incBrokerPutNums();
}
return result;
}
|
@Test
public void testPutMessageReturnResult() {
when(messageStore.putMessage(any(MessageExtBrokerInner.class)))
.thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
PutMessageResult result = transactionBridge.putMessageReturnResult(createMessageBrokerInner());
assertThat(result.getPutMessageStatus()).isEqualTo(PutMessageStatus.PUT_OK);
}
|
public void push(int id, float value) {
checkIdInRange(id);
if (size == max)
throw new IllegalStateException("Cannot push anymore, the heap is already full. size: " + size);
if (contains(id))
throw new IllegalStateException("Element with id: " + id + " was pushed already, you need to use the update method if you want to change its value");
size++;
tree[size] = id;
positions[id] = size;
vals[size] = value;
percolateUp(size);
}
|
@Test
public void outOfRange() {
assertThrows(IllegalArgumentException.class, () -> new MinHeapWithUpdate(4).push(4, 1.2f));
assertThrows(IllegalArgumentException.class, () -> new MinHeapWithUpdate(4).push(-1, 1.2f));
}
|
@Override
public Thread newThread(Runnable target) {
return delegate.newThread(target);
}
|
@Test
void requireThatThreadsCreatedAreJDiscContainerThreads() {
assertEquals(ContainerThread.class,
new ContainerThreadFactory(Mockito.mock(MetricConsumerProvider.class))
.newThread(Mockito.mock(Runnable.class))
.getClass());
}
|
public T send() throws IOException {
return web3jService.send(this, responseType);
}
|
@Test
public void testEthSendRawTransaction() throws Exception {
web3j.ethSendRawTransaction(
"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f"
+ "072445675058bb8eb970870f072445675")
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendRawTransaction\",\"params\":[\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\"],\"id\":1}");
}
|
@Override
public Optional<IndexSetConfig> get(String id) {
return get(new ObjectId(id));
}
|
@Test
@MongoDBFixtures("MongoIndexSetServiceTest.json")
public void getWithStringId() throws Exception {
final Optional<IndexSetConfig> indexSetConfig = indexSetService.get("57f3d721a43c2d59cb750001");
assertThat(indexSetConfig)
.isPresent()
.contains(
IndexSetConfig.create(
"57f3d721a43c2d59cb750001",
"Test 1",
"This is the index set configuration for Test 1",
true, true,
"test_1",
4,
1,
MessageCountRotationStrategy.class.getCanonicalName(),
MessageCountRotationStrategyConfig.create(1000),
NoopRetentionStrategy.class.getCanonicalName(),
NoopRetentionStrategyConfig.create(10),
ZonedDateTime.of(2016, 10, 4, 17, 0, 0, 0, ZoneOffset.UTC),
"standard",
"test_1",
null,
1,
false
)
);
}
|
@Override
public String getCommandWithArguments() {
List<String> argList = new ArrayList<>();
argList.add(super.getCommandWithArguments());
argList.add(containerName);
return StringUtils.join(argList, " ");
}
|
@Test
public void getCommandWithArguments() {
dockerInspectCommand.withGettingContainerStatus();
assertEquals("inspect --format='{{.State.Status}}' container_name",
dockerInspectCommand.getCommandWithArguments());
}
|
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filteredOpenAPI;
}
OpenAPI clone = new OpenAPI();
clone.info(filteredOpenAPI.getInfo());
clone.openapi(filteredOpenAPI.getOpenapi());
clone.jsonSchemaDialect(filteredOpenAPI.getJsonSchemaDialect());
clone.setSpecVersion(filteredOpenAPI.getSpecVersion());
clone.setExtensions(filteredOpenAPI.getExtensions());
clone.setExternalDocs(filteredOpenAPI.getExternalDocs());
clone.setSecurity(filteredOpenAPI.getSecurity());
clone.setServers(filteredOpenAPI.getServers());
clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags()));
final Set<String> allowedTags = new HashSet<>();
final Set<String> filteredTags = new HashSet<>();
Paths clonedPaths = new Paths();
if (filteredOpenAPI.getPaths() != null) {
for (String resourcePath : filteredOpenAPI.getPaths().keySet()) {
PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath);
PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers);
PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags);
if (clonedPathItem != null) {
if (!clonedPathItem.readOperations().isEmpty()) {
clonedPaths.addPathItem(resourcePath, clonedPathItem);
}
}
}
clone.paths(clonedPaths);
}
filteredTags.removeAll(allowedTags);
final List<Tag> tags = clone.getTags();
if (tags != null && !filteredTags.isEmpty()) {
tags.removeIf(tag -> filteredTags.contains(tag.getName()));
if (clone.getTags().isEmpty()) {
clone.setTags(null);
}
}
if (filteredOpenAPI.getWebhooks() != null) {
for (String resourcePath : filteredOpenAPI.getWebhooks().keySet()) {
PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath);
PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers);
PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags);
if (clonedPathItem != null) {
if (!clonedPathItem.readOperations().isEmpty()) {
clone.addWebhooks(resourcePath, clonedPathItem);
}
}
}
}
if (filteredOpenAPI.getComponents() != null) {
clone.components(new Components());
clone.getComponents().setSchemas(filterComponentsSchema(filter, filteredOpenAPI.getComponents().getSchemas(), params, cookies, headers));
clone.getComponents().setSecuritySchemes(filteredOpenAPI.getComponents().getSecuritySchemes());
clone.getComponents().setCallbacks(filteredOpenAPI.getComponents().getCallbacks());
clone.getComponents().setExamples(filteredOpenAPI.getComponents().getExamples());
clone.getComponents().setExtensions(filteredOpenAPI.getComponents().getExtensions());
clone.getComponents().setHeaders(filteredOpenAPI.getComponents().getHeaders());
clone.getComponents().setLinks(filteredOpenAPI.getComponents().getLinks());
clone.getComponents().setParameters(filteredOpenAPI.getComponents().getParameters());
clone.getComponents().setRequestBodies(filteredOpenAPI.getComponents().getRequestBodies());
clone.getComponents().setResponses(filteredOpenAPI.getComponents().getResponses());
clone.getComponents().setPathItems(filteredOpenAPI.getComponents().getPathItems());
}
if (filter.isRemovingUnreferencedDefinitions()) {
clone = removeBrokenReferenceDefinitions(clone);
}
return clone;
}
|
@Test(description = "it should clone everything from JSON without models")
public void cloneWithoutModels() throws IOException {
final String json = ResourceUtils.loadClassResource(getClass(), RESOURCE_PATH_WITHOUT_MODELS);
final OpenAPI openAPI = Json.mapper().readValue(json, OpenAPI.class);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoOpOperationsFilter(), null, null, null);
SerializationMatchers.assertEqualsToJson(filtered, json);
}
|
public static Sensor enforcedProcessingSensor(final String threadId,
final String taskId,
final StreamsMetricsImpl streamsMetrics,
final Sensor... parentSensors) {
return invocationRateAndCountSensor(
threadId,
taskId,
ENFORCED_PROCESSING,
ENFORCED_PROCESSING_RATE_DESCRIPTION,
ENFORCED_PROCESSING_TOTAL_DESCRIPTION,
RecordingLevel.DEBUG,
streamsMetrics,
parentSensors
);
}
|
@Test
public void shouldGetEnforcedProcessingSensor() {
final String operation = "enforced-processing";
final String totalDescription = "The total number of occurrences of enforced-processing operations";
final String rateDescription = "The average number of occurrences of enforced-processing operations per second";
when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)).thenReturn(expectedSensor);
when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap);
try (final MockedStatic<StreamsMetricsImpl> streamsMetricsStaticMock = mockStatic(StreamsMetricsImpl.class)) {
final Sensor sensor = TaskMetrics.enforcedProcessingSensor(THREAD_ID, TASK_ID, streamsMetrics);
streamsMetricsStaticMock.verify(
() -> StreamsMetricsImpl.addInvocationRateAndCountToSensor(
expectedSensor,
TASK_LEVEL_GROUP,
tagMap,
operation,
rateDescription,
totalDescription
)
);
assertThat(sensor, is(expectedSensor));
}
}
|
public static ModelType of(String name, String version) {
validate(name, version);
return Builder.create().name(name).version(version).build();
}
|
@Test
public void deserialize() {
final ModelType modelType = ModelType.of("foobar", "1");
final JsonNode jsonNode = objectMapper.convertValue(modelType, JsonNode.class);
assertThat(jsonNode.isObject()).isTrue();
assertThat(jsonNode.path("name").asText()).isEqualTo("foobar");
assertThat(jsonNode.path("version").asText()).isEqualTo("1");
}
|
public void close() {
synchronized (LOCK) {
for (KafkaMbean mbean : this.mbeans.values())
unregister(mbean);
}
}
|
@Test
public void testDeprecatedJmxPrefixWithDefaultMetrics() throws Exception {
@SuppressWarnings("deprecation")
JmxReporter reporter = new JmxReporter("my-prefix");
// for backwards compatibility, ensure prefix does not get overridden by the default empty namespace in metricscontext
MetricConfig metricConfig = new MetricConfig();
Metrics metrics = new Metrics(metricConfig, new ArrayList<>(Collections.singletonList(reporter)), Time.SYSTEM);
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
Sensor sensor = metrics.sensor("my-sensor");
sensor.add(metrics.metricName("pack.bean1.avg", "grp1"), new Avg());
assertEquals("my-prefix", server.getObjectInstance(new ObjectName("my-prefix:type=grp1")).getObjectName().getDomain());
} finally {
metrics.close();
}
}
|
public abstract int getLocalPort();
|
@Test
public void test_getLocalPort_whenNotYetBound() {
Reactor reactor = newReactor();
try (AsyncServerSocket socket = newAsyncServerSocket(reactor)) {
int localPort = socket.getLocalPort();
assertEquals(-1, localPort);
}
}
|
@Override
public boolean containsInt(K name, int value) {
return false;
}
|
@Test
public void testContainsInt() {
assertFalse(HEADERS.containsInt("name1", 1));
}
|
public static String toStepName(ExecutableStage executableStage) {
/*
* Look for the first/input ParDo/DoFn in this executable stage by
* matching ParDo/DoFn's input PCollection with executable stage's
* input PCollection
*/
Set<PipelineNode.PTransformNode> inputs =
executableStage.getTransforms().stream()
.filter(
transform ->
transform
.getTransform()
.getInputsMap()
.containsValue(executableStage.getInputPCollection().getId()))
.collect(Collectors.toSet());
Set<String> outputIds =
executableStage.getOutputPCollections().stream()
.map(PipelineNode.PCollectionNode::getId)
.collect(Collectors.toSet());
/*
* Look for the last/output ParDo/DoFn in this executable stage by
* matching ParDo/DoFn's output PCollection(s) with executable stage's
* out PCollection(s)
*/
Set<PipelineNode.PTransformNode> outputs =
executableStage.getTransforms().stream()
.filter(
transform ->
CollectionUtils.containsAny(
transform.getTransform().getOutputsMap().values(), outputIds))
.collect(Collectors.toSet());
return String.format("[%s-%s]", toStepName(inputs), toStepName(outputs));
}
|
@Test
public void testExecutableStageWithPDone() {
pipeline
.apply("MyCreateOf", Create.of("1"))
.apply(
"PDoneTransform",
new PTransform<PCollection<String>, PDone>() {
@Override
public PDone expand(PCollection<String> input) {
return PDone.in(pipeline);
}
});
assertEquals("[MyCreateOf-]", DoFnUtils.toStepName(getOnlyExecutableStage(pipeline)));
}
|
public boolean isIncompatibleWith(short version) {
return min() > version || max() < version;
}
|
@Test
public void testIsIncompatibleWith() {
assertFalse(new SupportedVersionRange((short) 1, (short) 1).isIncompatibleWith((short) 1));
assertFalse(new SupportedVersionRange((short) 1, (short) 4).isIncompatibleWith((short) 2));
assertFalse(new SupportedVersionRange((short) 1, (short) 4).isIncompatibleWith((short) 1));
assertFalse(new SupportedVersionRange((short) 1, (short) 4).isIncompatibleWith((short) 4));
assertTrue(new SupportedVersionRange((short) 2, (short) 3).isIncompatibleWith((short) 1));
assertTrue(new SupportedVersionRange((short) 2, (short) 3).isIncompatibleWith((short) 4));
}
|
public static <T> T populate(final Properties properties, final Class<T> clazz) {
T obj = null;
try {
obj = clazz.getDeclaredConstructor().newInstance();
return populate(properties, obj);
} catch (Throwable e) {
log.warn("Error occurs !", e);
}
return obj;
}
|
@Test
public void testPopulate_ExistObj() {
CustomizedConfig config = new CustomizedConfig();
config.setConsumerId("NewConsumerId");
Assert.assertEquals(config.getConsumerId(), "NewConsumerId");
config = BeanUtils.populate(properties, config);
//RemotingConfig config = BeanUtils.populate(properties, RemotingConfig.class);
Assert.assertEquals(config.getRmqMaxRedeliveryTimes(), 120);
Assert.assertEquals(config.getStringTest(), "kaka");
Assert.assertEquals(config.getRmqConsumerGroup(), "Default_Consumer_Group");
Assert.assertEquals(config.getRmqMessageConsumeTimeout(), 101);
Assert.assertEquals(config.getLongTest(), 1234567890L);
Assert.assertEquals(config.getDoubleTest(), 10.234, 0.000001);
}
|
public static Predicate<TopicMessageDTO> celScriptFilter(String script) {
CelValidationResult celValidationResult = CEL_COMPILER.compile(script);
if (celValidationResult.hasError()) {
throw new CelException(script, celValidationResult.getErrorString());
}
try {
CelAbstractSyntaxTree ast = celValidationResult.getAst();
CelRuntime.Program program = CEL_RUNTIME.createProgram(ast);
return createPredicate(script, program);
} catch (CelValidationException | CelEvaluationException e) {
throw new CelException(script, e);
}
}
|
@Test
void testBase64DecodingWorks() {
var uuid = UUID.randomUUID().toString();
var msg = "test." + Base64.getEncoder().encodeToString(uuid.getBytes());
var f = celScriptFilter("string(base64.decode(record.value.split('.')[1])).contains('" + uuid + "')");
assertTrue(f.test(msg().content(msg)));
}
|
public JobMetaDataParameterObject processJobMultipart(JobMultiPartParameterObject parameterObject)
throws IOException, NoSuchAlgorithmException {
// Change the timestamp in the beginning to avoid expiration
changeLastUpdatedTime();
validateReceivedParameters(parameterObject);
validateReceivedPartNumbersAreExpected(parameterObject);
validatePartChecksum(parameterObject);
// Parts numbers are good. Save them
currentPart = parameterObject.getCurrentPartNumber();
totalPart = parameterObject.getTotalPartNumber();
Path jarPath = jobMetaDataParameterObject.getJarPath();
// Append data to file
try (OutputStream outputStream = Files.newOutputStream(jarPath, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
outputStream.write(parameterObject.getPartData(), 0, parameterObject.getPartSize());
}
if (LOGGER.isInfoEnabled()) {
String message = String.format("Session : %s jarPath: %s PartNumber: %d/%d Total file size : %d bytes",
parameterObject.getSessionId(), jarPath, currentPart, totalPart, Files.size(jarPath));
LOGGER.info(message);
}
JobMetaDataParameterObject result = null;
// If parts are complete
if (currentPart == totalPart) {
validateJarChecksum();
result = jobMetaDataParameterObject;
}
return result;
}
|
@Test
public void testInvalidOrder() {
JobMultiPartParameterObject jobMultiPartParameterObject = new JobMultiPartParameterObject();
jobMultiPartParameterObject.setSessionId(null);
jobMultiPartParameterObject.setCurrentPartNumber(2);
jobMultiPartParameterObject.setTotalPartNumber(1);
jobMultiPartParameterObject.setPartData(null);
jobMultiPartParameterObject.setPartSize(0);
Assert.assertThrows(JetException.class, () -> jobUploadStatus.processJobMultipart(jobMultiPartParameterObject));
}
|
private void validateContentLength(final int contentLength, final boolean multiRecipientMessage, final String userAgent) {
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("oversize", String.valueOf(oversize)),
Tag.of("multiRecipientMessage", String.valueOf(multiRecipientMessage))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
}
|
@Test
void testValidateContentLength() throws Exception {
final int contentLength = Math.toIntExact(MessageController.MAX_MESSAGE_SIZE + 1);
final byte[] contentBytes = new byte[contentLength];
Arrays.fill(contentBytes, (byte) 1);
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
.put(Entity.entity(new IncomingMessageList(
List.of(new IncomingMessage(1, (byte) 1, 1, new String(contentBytes))), false, true,
System.currentTimeMillis()),
MediaType.APPLICATION_JSON_TYPE))) {
assertThat("Bad response", response.getStatus(), is(equalTo(413)));
verify(messageSender, never()).sendMessage(any(Account.class), any(Device.class), any(Envelope.class),
anyBoolean());
}
}
|
@Override
@Deprecated
public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransformerSupplier, "valueTransformerSupplier can't be null");
return doFlatTransformValues(
toValueTransformerWithKeySupplier(valueTransformerSupplier),
NamedInternal.empty(),
stateStoreNames);
}
|
@Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullValueTransformerWithKeySupplierOnFlatTransformValuesWithNamedAndStores() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues(
(ValueTransformerWithKeySupplier<Object, Object, Iterable<Object>>) null,
Named.as("flatValueWitKeyTransformer"),
"stateStore"));
assertThat(exception.getMessage(), equalTo("valueTransformerSupplier can't be null"));
}
|
public static NodeBadge number(int n) {
// TODO: consider constraints, e.g. 1 <= n <= 999
return new NodeBadge(Status.INFO, false, Integer.toString(n), null);
}
|
@Test
public void numberOnly() {
badge = NodeBadge.number(NUM);
checkFields(badge, Status.INFO, false, NUM_STR, null);
}
|
@Override
public TopicAssignment place(
PlacementSpec placement,
ClusterDescriber cluster
) throws InvalidReplicationFactorException {
RackList rackList = new RackList(random, cluster.usableBrokers());
throwInvalidReplicationFactorIfNonPositive(placement.numReplicas());
throwInvalidReplicationFactorIfZero(rackList.numUnfencedBrokers());
throwInvalidReplicationFactorIfTooFewBrokers(placement.numReplicas(),
rackList.numTotalBrokers());
List<List<Integer>> placements = new ArrayList<>(placement.numPartitions());
for (int partition = 0; partition < placement.numPartitions(); partition++) {
placements.add(rackList.place(placement.numReplicas()));
}
return new TopicAssignment(
placements.stream().map(replicas -> new PartitionAssignment(replicas, cluster)).collect(Collectors.toList())
);
}
|
@Test
public void testPlacementOnFencedReplicaOnSingleRack() {
MockRandom random = new MockRandom();
RackList rackList = new RackList(random, Arrays.asList(
new UsableBroker(3, Optional.empty(), false),
new UsableBroker(1, Optional.empty(), true),
new UsableBroker(2, Optional.empty(), false)).iterator());
assertEquals(3, rackList.numTotalBrokers());
assertEquals(2, rackList.numUnfencedBrokers());
assertEquals(Collections.singletonList(Optional.empty()), rackList.rackNames());
assertEquals(Arrays.asList(3, 2, 1), rackList.place(3));
assertEquals(Arrays.asList(2, 3, 1), rackList.place(3));
assertEquals(Arrays.asList(3, 2, 1), rackList.place(3));
assertEquals(Arrays.asList(2, 3, 1), rackList.place(3));
}
|
public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException {
if (pattern == null || host == null) {
throw new IllegalArgumentException(
"Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host);
}
pattern = pattern.trim();
if ("*.*.*.*".equals(pattern) || "*".equals(pattern)) {
return true;
}
InetAddress inetAddress = InetAddress.getByName(host);
boolean isIpv4 = isValidV4Address(inetAddress);
String[] hostAndPort = getPatternHostAndPort(pattern, isIpv4);
if (hostAndPort[1] != null && !hostAndPort[1].equals(String.valueOf(port))) {
return false;
}
pattern = hostAndPort[0];
String splitCharacter = SPLIT_IPV4_CHARACTER;
if (!isIpv4) {
splitCharacter = SPLIT_IPV6_CHARACTER;
}
String[] mask = pattern.split(splitCharacter);
// check format of pattern
checkHostPattern(pattern, mask, isIpv4);
host = inetAddress.getHostAddress();
if (pattern.equals(host)) {
return true;
}
// short name condition
if (!ipPatternContainExpression(pattern)) {
InetAddress patternAddress = InetAddress.getByName(pattern);
return patternAddress.getHostAddress().equals(host);
}
String[] ipAddress = host.split(splitCharacter);
for (int i = 0; i < mask.length; i++) {
if ("*".equals(mask[i]) || mask[i].equals(ipAddress[i])) {
continue;
} else if (mask[i].contains("-")) {
String[] rangeNumStrs = StringUtils.split(mask[i], '-');
if (rangeNumStrs.length != 2) {
throw new IllegalArgumentException("There is wrong format of ip Address: " + mask[i]);
}
Integer min = getNumOfIpSegment(rangeNumStrs[0], isIpv4);
Integer max = getNumOfIpSegment(rangeNumStrs[1], isIpv4);
Integer ip = getNumOfIpSegment(ipAddress[i], isIpv4);
if (ip < min || ip > max) {
return false;
}
} else if ("0".equals(ipAddress[i])
&& ("0".equals(mask[i])
|| "00".equals(mask[i])
|| "000".equals(mask[i])
|| "0000".equals(mask[i]))) {
continue;
} else if (!mask[i].equals(ipAddress[i])) {
return false;
}
}
return true;
}
|
@Test
void testMatchIpRangeMatchWhenIpv6Exception() {
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> NetUtils.matchIpRange("234e:0:4567::3d:*", "234e:0:4567::3d:ff", 90));
assertTrue(thrown.getMessage().contains("If you config ip expression that contains '*'"));
thrown = assertThrows(
IllegalArgumentException.class,
() -> NetUtils.matchIpRange("234e:0:4567:3d", "234e:0:4567::3d:ff", 90));
assertTrue(thrown.getMessage().contains("The host is ipv6, but the pattern is not ipv6 pattern"));
thrown = assertThrows(
IllegalArgumentException.class, () -> NetUtils.matchIpRange("192.168.1.1-65-3", "192.168.1.63", 90));
assertTrue(thrown.getMessage().contains("There is wrong format of ip Address"));
}
|
@Override
public Connection createConnection(String host, int port) throws IOException {
try {
Socket socket;
SocketFactory socketFactory;
socketFactory = config.isUsingSSL() && config.getHttpProxyHost() == null
? SSLSocketFactory
.getDefault()
: SocketFactory.getDefault();
if (config.getHttpProxyHost() != null) {
// setup the proxy tunnel
socket = socketFactory.createSocket();
// jsmpp uses enquire link timer as socket read timeout, so also use it to establish the initial connection
socket.connect(new InetSocketAddress(config.getHttpProxyHost(), config.getHttpProxyPort()),
config.getEnquireLinkTimer());
connectProxy(host, port, socket);
} else {
socket = socketFactory.createSocket();
// jsmpp uses enquire link timer as socket read timeout, so also use it to establish the initial connection
socket.connect(new InetSocketAddress(host, port), config.getEnquireLinkTimer());
}
if (config.isUsingSSL() && config.getHttpProxyHost() != null) {
// Init the SSL socket which is based on the proxy socket
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, host, port, true);
sslSocket.startHandshake();
socket = sslSocket;
}
return new SocketConnection(socket);
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
|
@Test
@Disabled("Must be manually tested")
public void createConnection() throws IOException {
SmppConfiguration configuration = new SmppConfiguration();
SmppConnectionFactory factory = SmppConnectionFactory.getInstance(configuration);
Connection connection = factory.createConnection("localhost", 2775);
try {
assertNotNull(connection);
assertTrue(connection.isOpen());
} finally {
if (connection != null) {
connection.close();
}
}
}
|
@Override
public Map<K, V> getCachedMap() {
return localCacheView.getCachedMap();
}
|
@Test
public void testPutGetCache() {
RLocalCachedMap<String, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test"));
Map<String, Integer> cache = map.getCachedMap();
map.put("12", 1);
map.put("14", 2);
map.put("15", 3);
assertThat(cache).containsValues(1, 2, 3);
assertThat(map.get("12")).isEqualTo(1);
assertThat(map.get("14")).isEqualTo(2);
assertThat(map.get("15")).isEqualTo(3);
RLocalCachedMap<String, Integer> map1 = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test"));
assertThat(map1.get("12")).isEqualTo(1);
assertThat(map1.get("14")).isEqualTo(2);
assertThat(map1.get("15")).isEqualTo(3);
}
|
@Override
public Path path() {
return path(true);
}
|
@Test
void shouldReturnTheSameWorkingDirPath() {
LocalWorkingDir workingDirectory = new LocalWorkingDir(Path.of("/tmp"), IdUtils.create());
assertThat(workingDirectory.path(), is(workingDirectory.path()));
}
|
public Optional<String> getNameByActiveVersion(final String path) {
Matcher matcher = activeVersionPathPattern.matcher(path);
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty();
}
|
@Test
void assertGetNameByActiveVersionWhenNotFound() {
Optional<String> actual = converter.getNameByActiveVersion("/invalid");
assertFalse(actual.isPresent());
}
|
public static CreateSourceAsProperties from(final Map<String, Literal> literals) {
try {
return new CreateSourceAsProperties(literals, false);
} catch (final ConfigException e) {
final String message = e.getMessage().replace(
"configuration",
"property"
);
throw new KsqlException(message, e);
}
}
|
@Test
public void shouldFailIfInvalidConfig() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> from(
of("foo", new StringLiteral("bar"))
)
);
// Then:
assertThat(e.getMessage(), containsString("Invalid config variable(s) in the WITH clause: FOO"));
}
|
@Override
public boolean isCloseOnCircuitBreakerEnabled() {
return clientConfig.getPropertyAsBoolean(CLOSE_ON_CIRCUIT_BREAKER, true);
}
|
@Test
void testIsCloseOnCircuitBreakerEnabled() {
assertTrue(connectionPoolConfig.isCloseOnCircuitBreakerEnabled());
}
|
@Override
public long usedHeapMemory() {
return heap.usedMemory();
}
|
@Test
void chunkMustDeallocateOrReuseWthBufferRelease() throws Exception {
AdaptiveByteBufAllocator allocator = newAllocator(false);
ByteBuf a = allocator.heapBuffer(8192);
assertEquals(128 * 1024, allocator.usedHeapMemory());
ByteBuf b = allocator.heapBuffer(120 * 1024);
assertEquals(128 * 1024, allocator.usedHeapMemory());
b.release();
a.release();
assertEquals(128 * 1024, allocator.usedHeapMemory());
a = allocator.heapBuffer(8192);
assertEquals(128 * 1024, allocator.usedHeapMemory());
b = allocator.heapBuffer(120 * 1024);
assertEquals(128 * 1024, allocator.usedHeapMemory());
a.release();
ByteBuf c = allocator.heapBuffer(8192);
assertEquals(2 * 128 * 1024, allocator.usedHeapMemory());
c.release();
assertEquals(2 * 128 * 1024, allocator.usedHeapMemory());
b.release();
assertEquals(2 * 128 * 1024, allocator.usedHeapMemory());
}
|
public SnapshotDto setBuildString(@Nullable String buildString) {
checkLength(MAX_BUILD_STRING_LENGTH, buildString, "buildString");
this.buildString = buildString;
return this;
}
|
@Test
void hashcode_whenDifferentInstanceWithDifferentValues_shouldNotBeEqual() {
SnapshotDto snapshotDto1 = create();
SnapshotDto snapshotDto2 = create().setBuildString("some-other-string");
assertThat(snapshotDto1).doesNotHaveSameHashCodeAs(snapshotDto2);
}
|
@Override
public FSINFO3Response fsinfo(XDR xdr, RpcInfo info) {
return fsinfo(xdr, getSecurityHandler(info), info.remoteAddress());
}
|
@Test(timeout = 60000)
public void testFsinfo() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
FSINFO3Request req = new FSINFO3Request(handle);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
FSINFO3Response response1 = nfsd.fsinfo(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals("Incorrect return code:", Nfs3Status.NFS3ERR_ACCES,
response1.getStatus());
// Attempt by a priviledged user should pass.
FSINFO3Response response2 = nfsd.fsinfo(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals("Incorrect return code:", Nfs3Status.NFS3_OK,
response2.getStatus());
}
|
@Deprecated
public BigtableConfig withBigtableOptionsConfigurator(
SerializableFunction<BigtableOptions.Builder, BigtableOptions.Builder> configurator) {
checkArgument(configurator != null, "configurator can not be null");
return toBuilder().setBigtableOptionsConfigurator(configurator).build();
}
|
@Test
public void testWithBigtableOptionsConfigurator() {
assertEquals(
CONFIGURATOR,
config.withBigtableOptionsConfigurator(CONFIGURATOR).getBigtableOptionsConfigurator());
thrown.expect(IllegalArgumentException.class);
config.withBigtableOptionsConfigurator(null);
}
|
public static void stepExecuted(final Supplier<PMMLStep> stepSupplier, final PMMLRuntimeContext context) {
if (!context.getEfestoListeners().isEmpty()) {
final PMMLStep step = stepSupplier.get();
context.getEfestoListeners().forEach(listener -> listener.stepExecuted(step));
}
}
|
@Test
void stepExecuted() {
final Map<Integer, PMMLStep> listenerFeedback = new HashMap<>();
int size = 3;
PMMLRuntimeContext pmmlContext = getPMMLContext(size, listenerFeedback);
AtomicBoolean invoked = new AtomicBoolean(false);
PMMLListenerUtils.stepExecuted(() -> new PMMLStepTest(invoked), pmmlContext);
assertThat(invoked).isTrue();
assertThat(listenerFeedback).hasSize(size);
final PMMLStep retrieved = listenerFeedback.get(0);
IntStream.range(1, size).forEach(i -> assertThat(listenerFeedback.get(i)).isEqualTo(retrieved));
}
|
@Override
public void onEvent(Event event) {
if (EnvUtil.getStandaloneMode()) {
return;
}
if (event instanceof ClientEvent.ClientVerifyFailedEvent) {
syncToVerifyFailedServer((ClientEvent.ClientVerifyFailedEvent) event);
} else {
syncToAllServer((ClientEvent) event);
}
}
|
@Test
void testOnClientChangedEventWithoutResponsible() {
when(clientManager.isResponsibleClient(client)).thenReturn(false);
distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(client));
verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong());
verify(distroProtocol, never()).sync(any(), any());
}
|
public static Permission getPermission(String name, String serviceName, String... actions) {
PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName);
if (permissionFactory == null) {
throw new IllegalArgumentException("No permissions found for service: " + serviceName);
}
return permissionFactory.create(name, actions);
}
|
@Test
public void getPermission_DistributedExecutor() {
Permission permission = ActionConstants.getPermission("foo", DistributedExecutorService.SERVICE_NAME);
assertNotNull(permission);
assertTrue(permission instanceof ExecutorServicePermission);
}
|
public Collection<RepositoryTuple> swapToRepositoryTuples(final YamlRuleConfiguration yamlRuleConfig) {
RepositoryTupleEntity tupleEntity = yamlRuleConfig.getClass().getAnnotation(RepositoryTupleEntity.class);
if (null == tupleEntity) {
return Collections.emptyList();
}
if (tupleEntity.leaf()) {
return Collections.singleton(new RepositoryTuple(tupleEntity.value(), YamlEngine.marshal(yamlRuleConfig)));
}
Collection<RepositoryTuple> result = new LinkedList<>();
RuleNodePath ruleNodePath = TypedSPILoader.getService(RuleNodePathProvider.class, yamlRuleConfig.getRuleConfigurationType()).getRuleNodePath();
for (Field each : getFields(yamlRuleConfig.getClass())) {
boolean isAccessible = each.isAccessible();
each.setAccessible(true);
result.addAll(swapToRepositoryTuples(yamlRuleConfig, ruleNodePath, each));
each.setAccessible(isAccessible);
}
return result;
}
|
@Test
void assertSwapToRepositoryTuplesWithNodeYamlRuleConfiguration() {
NodeYamlRuleConfiguration yamlRuleConfig = new NodeYamlRuleConfiguration();
yamlRuleConfig.setMapValue(Collections.singletonMap("k", new LeafYamlRuleConfiguration("v")));
yamlRuleConfig.setCollectionValue(Collections.singletonList(new LeafYamlRuleConfiguration("foo")));
yamlRuleConfig.setStringValue("str");
yamlRuleConfig.setBooleanValue(true);
yamlRuleConfig.setIntegerValue(1);
yamlRuleConfig.setLongValue(10L);
yamlRuleConfig.setEnumValue(NodeYamlRuleConfigurationEnum.FOO);
LeafYamlRuleConfiguration leaf = new LeafYamlRuleConfiguration();
leaf.setValue("leaf");
yamlRuleConfig.setLeaf(leaf);
yamlRuleConfig.setGens(Collections.singleton("value"));
yamlRuleConfig.setGen("single_gen");
List<RepositoryTuple> actual = new ArrayList<>(new RepositoryTupleSwapperEngine().swapToRepositoryTuples(yamlRuleConfig));
assertThat(actual.size(), is(10));
assertThat(actual.get(0).getKey(), is("map_value/k"));
assertThat(actual.get(0).getValue(), is("value: v" + System.lineSeparator()));
assertThat(actual.get(1).getKey(), is("collection_value"));
assertThat(actual.get(1).getValue(), is("- !LEAF" + System.lineSeparator() + " value: foo" + System.lineSeparator()));
assertThat(actual.get(2).getKey(), is("string_value"));
assertThat(actual.get(2).getValue(), is("str"));
assertThat(actual.get(3).getKey(), is("boolean_value"));
assertThat(actual.get(3).getValue(), is("true"));
assertThat(actual.get(4).getKey(), is("integer_value"));
assertThat(actual.get(4).getValue(), is("1"));
assertThat(actual.get(5).getKey(), is("long_value"));
assertThat(actual.get(5).getValue(), is("10"));
assertThat(actual.get(6).getKey(), is("enum_value"));
assertThat(actual.get(6).getValue(), is("FOO"));
assertThat(actual.get(7).getKey(), is("leaf"));
assertThat(actual.get(7).getValue(), is("value: leaf" + System.lineSeparator()));
assertThat(actual.get(8).getKey(), is("gens/gen: value"));
assertThat(actual.get(8).getValue(), is("value"));
assertThat(actual.get(9).getKey(), is("gen"));
assertThat(actual.get(9).getValue(), is("single_gen"));
}
|
@Override
public String getMetadata() {
if (getEntityDescriptorElement() != null) {
return Configuration.serializeSamlObject(getEntityDescriptorElement()).toString();
}
throw new TechnicalException("Metadata cannot be retrieved because entity descriptor is null");
}
|
@Test
public void resolveMetadataDocumentAsString() {
metadataResolver.init();
var metadata = metadataResolver.getMetadata();
assertNotNull(metadata);
}
|
@Override
public void collectionItemAdded(final Host bookmark) {
try {
if(this.isLocked()) {
log.debug("Skip indexing collection while loading");
}
else {
this.index();
}
}
finally {
super.collectionItemAdded(bookmark);
}
}
|
@Test
public void testLoadAwaitFilesystemChange() throws Exception {
final Local source = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
final CountDownLatch wait = new CountDownLatch(1);
final BookmarkCollection collection = new BookmarkCollection(source) {
@Override
public void collectionItemAdded(final Host bookmark) {
super.collectionItemAdded(bookmark);
wait.countDown();
}
};
collection.load();
final String uid = "4d6b034c-8635-4e2f-93b1-7306ba22da22";
final Local b = new Local(source, String.format("%s.duck", uid));
final String bookmark = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
"<plist version=\"1.0\">\n" +
"<dict>\n" +
"\t<key>Access Timestamp</key>\n" +
"\t<string>1296634123295</string>\n" +
"\t<key>Hostname</key>\n" +
"\t<string>mirror.switch.ch</string>\n" +
"\t<key>Nickname</key>\n" +
"\t<string>mirror.switch.ch – FTP</string>\n" +
"\t<key>Port</key>\n" +
"\t<string>21</string>\n" +
"\t<key>Protocol</key>\n" +
"\t<string>test</string>\n" +
"\t<key>UUID</key>\n" +
"\t<string>" + uid + "</string>\n" +
"\t<key>Username</key>\n" +
"\t<string>anonymous</string>\n" +
"</dict>\n" +
"</plist>\n";
final OutputStream os = b.getOutputStream(false);
os.write(bookmark.getBytes(StandardCharsets.UTF_8));
os.close();
assertTrue(source.exists());
wait.await();
assertFalse(collection.isEmpty());
assertEquals(1, collection.size());
assertEquals(uid, collection.get(0).getUuid());
assertEquals(uid + ".duck", collection.getFile(collection.get(0)).getName());
collection.getFile(collection.get(0)).delete();
}
|
@Override
public Collection<String> getDistributedTableNames() {
return Collections.emptySet();
}
|
@Test
void assertGetDistributedTableMapper() {
assertThat(new LinkedList<>(ruleAttribute.getDistributedTableNames()), is(Collections.emptyList()));
}
|
@Override
public void updateRouter(Router osRouter) {
checkNotNull(osRouter, ERR_NULL_ROUTER);
checkArgument(!Strings.isNullOrEmpty(osRouter.getId()), ERR_NULL_ROUTER_ID);
osRouterStore.updateRouter(osRouter);
log.info(String.format(MSG_ROUTER, osRouter.getId(), MSG_UPDATED));
}
|
@Test(expected = NullPointerException.class)
public void testUpdateRouterWithNull() {
target.updateRouter(null);
}
|
public static String getRelativeLinkTo(Item p) {
Map<Object, String> ancestors = new HashMap<>();
View view = null;
StaplerRequest request = Stapler.getCurrentRequest();
for (Ancestor a : request.getAncestors()) {
ancestors.put(a.getObject(), a.getRelativePath());
if (a.getObject() instanceof View)
view = (View) a.getObject();
}
String path = ancestors.get(p);
if (path != null) {
return normalizeURI(path + '/');
}
Item i = p;
String url = "";
while (true) {
ItemGroup ig = i.getParent();
url = i.getShortUrl() + url;
if (ig == Jenkins.get() || (view != null && ig == view.getOwner().getItemGroup())) {
assert i instanceof TopLevelItem;
if (view != null) {
// assume p and the current page belong to the same view, so return a relative path
// (even if they did not, View.getItem does not by default verify ownership)
return normalizeURI(ancestors.get(view) + '/' + url);
} else {
// otherwise return a path from the root Hudson
return normalizeURI(request.getContextPath() + '/' + p.getUrl());
}
}
path = ancestors.get(ig);
if (path != null) {
return normalizeURI(path + '/' + url);
}
assert ig instanceof Item; // if not, ig must have been the Hudson instance
i = (Item) ig;
}
}
|
@Issue("JENKINS-17713")
@Test public void getRelativeLinkTo_MavenModules() {
StaplerRequest req = createMockRequest("/jenkins");
try (
MockedStatic<Stapler> mocked = mockStatic(Stapler.class);
MockedStatic<Jenkins> mockedJenkins = mockStatic(Jenkins.class)
) {
Jenkins j = createMockJenkins(mockedJenkins);
mocked.when(Stapler::getCurrentRequest).thenReturn(req);
TopLevelItemAndItemGroup ms = mock(TopLevelItemAndItemGroup.class);
when(ms.getShortUrl()).thenReturn("job/ms/");
// TODO "." (in second ancestor) is what Stapler currently fails to do. Could edit test to use ".." but set a different request path?
createMockAncestors(req, createAncestor(j, "../.."), createAncestor(ms, "."));
Item m = mock(Item.class);
when(m.getParent()).thenReturn(ms);
when(m.getShortUrl()).thenReturn("grp$art/");
assertEquals("grp$art/", Functions.getRelativeLinkTo(m));
}
}
|
@VisibleForTesting
static Path resolveEntropy(Path path, EntropyInjectingFileSystem efs, boolean injectEntropy)
throws IOException {
final String entropyInjectionKey = efs.getEntropyInjectionKey();
if (entropyInjectionKey == null) {
return path;
} else {
final URI originalUri = path.toUri();
final String checkpointPath = originalUri.getPath();
final int indexOfKey = checkpointPath.indexOf(entropyInjectionKey);
if (indexOfKey == -1) {
return path;
} else {
final StringBuilder buffer = new StringBuilder(checkpointPath.length());
buffer.append(checkpointPath, 0, indexOfKey);
if (injectEntropy) {
buffer.append(efs.generateEntropy());
}
buffer.append(
checkpointPath,
indexOfKey + entropyInjectionKey.length(),
checkpointPath.length());
final String rewrittenPath = buffer.toString();
try {
return new Path(
new URI(
originalUri.getScheme(),
originalUri.getAuthority(),
rewrittenPath,
originalUri.getQuery(),
originalUri.getFragment())
.normalize());
} catch (URISyntaxException e) {
// this could only happen if the injected entropy string contains invalid
// characters
throw new IOException(
"URI format error while processing path for entropy injection", e);
}
}
}
}
|
@Test
void testFullUriNonMatching() throws Exception {
EntropyInjectingFileSystem efs = new TestEntropyInjectingFs("_entropy_key_", "ignored");
Path path = new Path("s3://hugo@myawesomehost:55522/path/to/the/file");
assertThat(EntropyInjector.resolveEntropy(path, efs, true)).isEqualTo(path);
assertThat(EntropyInjector.resolveEntropy(path, efs, false)).isEqualTo(path);
}
|
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/or a JWE with JSON claims as the payload.
// In this example it is a JWS nested inside a JWE
// So we first create a JsonWebSignature object.
JsonWebSignature jws = new JsonWebSignature();
// The payload of the JWS is JSON content of the JWT Claims
jws.setPayload(claims.toJson());
// The JWT is signed using the sender's private key
jws.setKey(privateKey);
// Get provider from security config file, it should be two digit
// And the provider id will set as prefix for keyid in the token header, for example: 05100
// if there is no provider id, we use "00" for the default value
String provider_id = "";
if (jwtConfig.getProviderId() != null) {
provider_id = jwtConfig.getProviderId();
if (provider_id.length() == 1) {
provider_id = "0" + provider_id;
} else if (provider_id.length() > 2) {
logger.error("provider_id defined in the security.yml file is invalid; the length should be 2");
provider_id = provider_id.substring(0, 2);
}
}
jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid());
// Set the signature algorithm on the JWT/JWS that will integrity protect the claims
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
// Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
// representation, which is a string consisting of three dot ('.') separated
// base64url-encoded parts in the form Header.Payload.Signature
jwt = jws.getCompactSerialization();
return jwt;
}
|
@Test
public void longLivedTrainingJwt() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("training.accounts.read", "training.customers.read", "training.myaccounts.read", "training.transacts.read"), "user");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.deserializePrivateKey(long_key, KeyUtil.RSA));
System.out.println("***LongLived Training JWT***: " + jwt);
}
|
@Override
public final int readInt() throws EOFException {
final int i = readInt(pos);
pos += INT_SIZE_IN_BYTES;
return i;
}
|
@Test
public void testReadIntByteOrder() throws Exception {
int readInt = in.readInt(LITTLE_ENDIAN);
int theInt = Bits.readIntL(INIT_DATA, 0);
assertEquals(theInt, readInt);
}
|
public boolean isDryrun() {
return dryrun;
}
|
@Test
public void testDryRunParamInRobotFrameworkCamelConfigurations() throws Exception {
RobotFrameworkEndpoint robotFrameworkEndpoint = createEndpointWithOption("");
assertEquals(false, robotFrameworkEndpoint.getConfiguration().isDryrun());
robotFrameworkEndpoint = createEndpointWithOption("dryrun=true");
assertEquals(true, robotFrameworkEndpoint.getConfiguration().isDryrun());
}
|
public static URI parse(String featureIdentifier) {
return parse(FeaturePath.parse(featureIdentifier));
}
|
@Test
void reject_feature_with_lines() {
Executable testMethod = () -> FeatureIdentifier.parse(URI.create("classpath:/path/to/file.feature:10:40"));
IllegalArgumentException actualThrown = assertThrows(IllegalArgumentException.class, testMethod);
assertThat("Unexpected exception message", actualThrown.getMessage(), is(equalTo(
"featureIdentifier does not reference a single feature file: classpath:/path/to/file.feature:10:40")));
}
|
public void eval(Object... args) throws HiveException {
// When the parameter is (Integer, Array[Double]), Flink calls udf.eval(Integer,
// Array[Double]), which is not a problem.
// But when the parameter is a single array, Flink calls udf.eval(Array[Double]),
// at this point java's var-args will cast Array[Double] to Array[Object] and let it be
// Object... args, So we need wrap it.
if (isArgsSingleArray) {
args = new Object[] {args};
}
checkArgument(args.length == conversions.length);
if (!allIdentityConverter) {
for (int i = 0; i < args.length; i++) {
args[i] = conversions[i].toHiveObject(args[i]);
}
}
function.process(args);
}
|
@Test
public void testOverSumInt() throws Exception {
Object[] constantArgs = new Object[] {null, 4};
DataType[] dataTypes = new DataType[] {DataTypes.INT(), DataTypes.INT()};
HiveGenericUDTF udf = init(TestOverSumIntUDTF.class, constantArgs, dataTypes);
udf.eval(5, 4);
assertThat(collector.result).isEqualTo(Arrays.asList(Row.of(9), Row.of(9)));
// Test empty input and empty output
constantArgs = new Object[] {};
dataTypes = new DataType[] {};
udf = init(TestOverSumIntUDTF.class, constantArgs, dataTypes);
udf.eval();
assertThat(collector.result).isEqualTo(Arrays.asList());
}
|
@Override
public OpensearchDistribution get() {
return distribution.get();
}
|
@Test
void testDetection() {
final OpensearchDistribution x64 = provider(tempDir, OpensearchArchitecture.x64).get();
Assertions.assertThat(x64.version()).isEqualTo("2.5.0");
Assertions.assertThat(x64.platform()).isEqualTo("linux");
Assertions.assertThat(x64.architecture()).isEqualTo(OpensearchArchitecture.x64);
final OpensearchDistribution mac = provider(tempDir, OpensearchArchitecture.x64).get();
Assertions.assertThat(mac.version()).isEqualTo("2.5.0");
Assertions.assertThat(mac.platform()).isEqualTo("linux");
Assertions.assertThat(mac.architecture()).isEqualTo(OpensearchArchitecture.x64);
final OpensearchDistribution aarch64 = provider(tempDir, OpensearchArchitecture.aarch64).get();
Assertions.assertThat(aarch64.version()).isEqualTo("2.5.0");
Assertions.assertThat(aarch64.platform()).isEqualTo("linux");
Assertions.assertThat(aarch64.architecture()).isEqualTo(OpensearchArchitecture.aarch64);
}
|
public MethodConfig setParameter(String key, String value) {
if (parameters == null) {
parameters = new ConcurrentHashMap<String, String>();
}
parameters.put(key, value);
return this;
}
|
@Test
public void setParameter() throws Exception {
MethodConfig methodConfig = new MethodConfig();
Assert.assertNull(methodConfig.parameters);
Assert.assertNull(methodConfig.getParameter("aa"));
methodConfig.setName("echo");
methodConfig.setParameter("aa", "11");
Assert.assertNotNull(methodConfig.parameters);
Assert.assertEquals(methodConfig.getParameter("aa"), "11");
}
|
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
}
|
@Test
public void testUpdateFetchPositionResetToEarliestOffset() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.EARLIEST);
client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.EARLIEST_TIMESTAMP,
validLeaderEpoch), listOffsetResponse(Errors.NONE, 1L, 5L));
offsetFetcher.resetPositionsIfNeeded();
consumerClient.pollNoWakeup();
assertFalse(subscriptions.isOffsetResetNeeded(tp0));
assertTrue(subscriptions.isFetchable(tp0));
assertEquals(5, subscriptions.position(tp0).offset);
}
|
@SafeVarargs
public static <S extends Comparable<S>> QueryLimit<S> getMinimum(QueryLimit<S> limit, QueryLimit<S>... limits)
{
Optional<QueryLimit<S>> queryLimit = Stream.concat(
limits != null ? Arrays.stream(limits) : Stream.empty(),
limit != null ? Stream.of(limit) : Stream.empty())
.filter(Objects::nonNull)
.min(Comparator.comparing(QueryLimit::getLimit));
return queryLimit.orElseThrow(() -> new IllegalArgumentException("At least one nonnull argument is required."));
}
|
@Test
public void testGetMinimum()
{
QueryLimit<Duration> longLimit = createDurationLimit(new Duration(2, HOURS), SYSTEM);
QueryLimit<Duration> shortLimit = createDurationLimit(new Duration(1, MINUTES), RESOURCE_GROUP);
assertEquals(getMinimum(QUERY_LIMIT_DURATION, longLimit, shortLimit), shortLimit);
QueryLimit<DataSize> largeLimit = createDataSizeLimit(new DataSize(2, MEGABYTE), QUERY);
QueryLimit<DataSize> smallLimit = createDataSizeLimit(new DataSize(1, BYTE), RESOURCE_GROUP);
assertEquals(getMinimum(smallLimit, QUERY_LIMIT_DATA_SIZE, largeLimit), smallLimit);
assertEquals(getMinimum(null, QUERY_LIMIT_DATA_SIZE, largeLimit), QUERY_LIMIT_DATA_SIZE);
assertEquals(getMinimum(null, largeLimit, null, null, QUERY_LIMIT_DATA_SIZE), QUERY_LIMIT_DATA_SIZE);
assertEquals(getMinimum(smallLimit, null, null, null), smallLimit);
assertThrows(IllegalArgumentException.class, () -> getMinimum(null));
assertThrows(IllegalArgumentException.class, () -> getMinimum(null, null, null));
}
|
@Override
public RateLimiter rateLimiter(final String name) {
return rateLimiter(name, getDefaultConfig());
}
|
@Test
public void rateLimiterNewWithNullConfigSupplier() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage("Supplier must not be null");
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
Supplier<RateLimiterConfig> rateLimiterConfigSupplier = null;
registry.rateLimiter("name", rateLimiterConfigSupplier);
}
|
public static String getMimeType(String filePath) {
if (StrUtil.isBlank(filePath)) {
return null;
}
// 补充一些常用的mimeType
if (StrUtil.endWithIgnoreCase(filePath, ".css")) {
return "text/css";
} else if (StrUtil.endWithIgnoreCase(filePath, ".js")) {
return "application/x-javascript";
} else if (StrUtil.endWithIgnoreCase(filePath, ".rar")) {
return "application/x-rar-compressed";
} else if (StrUtil.endWithIgnoreCase(filePath, ".7z")) {
return "application/x-7z-compressed";
} else if (StrUtil.endWithIgnoreCase(filePath, ".wgt")) {
return "application/widget";
} else if (StrUtil.endWithIgnoreCase(filePath, ".webp")) {
// JDK8不支持
return "image/webp";
}
String contentType = URLConnection.getFileNameMap().getContentTypeFor(filePath);
if (null == contentType) {
contentType = getMimeType(Paths.get(filePath));
}
return contentType;
}
|
@Test
public void getMimeTypeTest() {
String mimeType = FileUtil.getMimeType("test2Write.jpg");
assertEquals("image/jpeg", mimeType);
mimeType = FileUtil.getMimeType("test2Write.html");
assertEquals("text/html", mimeType);
mimeType = FileUtil.getMimeType("main.css");
assertEquals("text/css", mimeType);
mimeType = FileUtil.getMimeType("test.js");
// 在 jdk 11+ 会获取到 text/javascript,而非 自定义的 application/x-javascript
final List<String> list = ListUtil.of("text/javascript", "application/x-javascript");
assertTrue(list.contains(mimeType));
// office03
mimeType = FileUtil.getMimeType("test.doc");
assertEquals("application/msword", mimeType);
mimeType = FileUtil.getMimeType("test.xls");
assertEquals("application/vnd.ms-excel", mimeType);
mimeType = FileUtil.getMimeType("test.ppt");
assertEquals("application/vnd.ms-powerpoint", mimeType);
// office07+
mimeType = FileUtil.getMimeType("test.docx");
assertEquals("application/vnd.openxmlformats-officedocument.wordprocessingml.document", mimeType);
mimeType = FileUtil.getMimeType("test.xlsx");
assertEquals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", mimeType);
mimeType = FileUtil.getMimeType("test.pptx");
assertEquals("application/vnd.openxmlformats-officedocument.presentationml.presentation", mimeType);
// pr#2617@Github
mimeType = FileUtil.getMimeType("test.wgt");
assertEquals("application/widget", mimeType);
// issue#3092
mimeType = FileUtil.getMimeType("https://xxx.oss-cn-hangzhou.aliyuncs.com/xxx.webp");
assertEquals("image/webp", mimeType);
}
|
public Optional<Result> execute( List<RowMetaAndData> rows ) throws KettleException {
if ( rows.isEmpty() || stopped ) {
return Optional.empty();
}
Trans subtrans = this.createSubtrans();
running.add( subtrans );
parentTrans.addActiveSubTransformation( subTransName, subtrans );
// Pass parameter values
passParametersToTrans( subtrans, rows.get( 0 ) );
Result result = new Result();
result.setRows( rows );
subtrans.setPreviousResult( result );
subtrans.prepareExecution( this.parentTrans.getArguments() );
List<RowMetaAndData> rowMetaAndData = new ArrayList<>();
subtrans.getSteps().stream()
.filter( c -> c.step.getStepname().equalsIgnoreCase( subStep ) )
.findFirst()
.ifPresent( c -> c.step.addRowListener( new RowAdapter() {
@Override public void rowWrittenEvent( RowMetaInterface rowMeta, Object[] row ) {
rowMetaAndData.add( new RowMetaAndData( rowMeta, row ) );
}
} ) );
subtrans.startThreads();
subtrans.waitUntilFinished();
updateStatuses( subtrans );
running.remove( subtrans );
Result subtransResult = subtrans.getResult();
subtransResult.setRows( rowMetaAndData );
releaseBufferPermits( rows.size() );
return Optional.of( subtransResult );
}
|
@Test
public void blockAndUnblockTwice() throws KettleException, InterruptedException, ExecutionException,
TimeoutException {
final ExecutorService executorService = Executors.newFixedThreadPool( 1 );
TransMeta parentMeta =
new TransMeta( this.getClass().getResource( "subtrans-executor-parent.ktr" ).getPath(), new Variables() );
TransMeta subMeta =
new TransMeta( this.getClass().getResource( "subtrans-executor-sub.ktr" ).getPath(), new Variables() );
LoggingObjectInterface loggingObject = new LoggingObject( "anything" );
Trans parentTrans = new Trans( parentMeta, loggingObject );
SubtransExecutor subtransExecutor =
new SubtransExecutor( "subtransname", parentTrans, subMeta, true, new TransExecutorParameters(), "", 1 );
RowMetaInterface rowMeta = parentMeta.getStepFields( "Data Grid" );
List<RowMetaAndData> rows = Arrays.asList(
new RowMetaAndData( rowMeta, "Pentaho", 1L ),
new RowMetaAndData( rowMeta, "Pentaho", 2L ),
new RowMetaAndData( rowMeta, "Pentaho", 3L ),
new RowMetaAndData( rowMeta, "Pentaho", 4L ) );
CompletableFuture<Boolean> acquireThreadRunning = new CompletableFuture();
Future future = executorService.submit( () -> safeAcquirePermits( subtransExecutor, 8, acquireThreadRunning ) );
//Acquire the permits before releasing them by waiting for the acquire thread to spin up.
assertTrue( acquireThreadRunning.get( 5, TimeUnit.SECONDS ) );
//Release 2*4=8 permits by calling execute twice with 4 rows
subtransExecutor.execute( rows );
subtransExecutor.execute( rows );
final boolean timedOut = !safeWaitForCompletion( future, 5 );
assertFalse( timedOut );
}
|
@Override
public boolean recycle() {
if (this.buffer != null) {
if (this.buffer.capacity() > MAX_CAPACITY_TO_RECYCLE) {
// If the size is too large, we should release it to avoid memory overhead
this.buffer = null;
} else {
BufferUtils.clear(this.buffer);
}
}
return recyclers.recycle(this, handle);
}
|
@Test
public void testRecycle() {
final ByteBufferCollector object = ByteBufferCollector.allocateByRecyclers();
object.recycle();
final ByteBufferCollector object2 = ByteBufferCollector.allocateByRecyclers();
Assert.assertSame(object, object2);
object2.recycle();
}
|
protected abstract MemberData memberData(Subscription subscription);
|
@Test
public void testMemberData() {
List<String> topics = topics(topic);
List<TopicPartition> ownedPartitions = partitions(tp(topic1, 0), tp(topic2, 1));
List<Subscription> subscriptions = new ArrayList<>();
// add subscription in all ConsumerProtocolSubscription versions
subscriptions.add(buildSubscriptionV0(topics, ownedPartitions, generationId, 0));
subscriptions.add(buildSubscriptionV1(topics, ownedPartitions, generationId, 1));
subscriptions.add(buildSubscriptionV2Above(topics, ownedPartitions, generationId, 2));
for (Subscription subscription : subscriptions) {
if (subscription != null) {
AbstractStickyAssignor.MemberData memberData = assignor.memberData(subscription);
assertEquals(ownedPartitions, memberData.partitions, "subscription: " + subscription + " doesn't have expected owned partition");
assertEquals(generationId, memberData.generation.orElse(-1), "subscription: " + subscription + " doesn't have expected generation id");
}
}
}
|
@Override
public CustomResponse<Void> logout(TokenInvalidateRequest tokenInvalidateRequest) {
return userServiceClient.logout(tokenInvalidateRequest);
}
|
@Test
void logout_ValidTokenInvalidateRequest_ReturnsCustomResponse() {
// Given
TokenInvalidateRequest tokenInvalidateRequest = TokenInvalidateRequest.builder()
.accessToken("validAccessToken")
.refreshToken("validRefreshToken")
.build();
CustomResponse<Void> expectedResponse = CustomResponse.<Void>builder()
.httpStatus(HttpStatus.OK)
.isSuccess(true)
.build();
// When
when(userServiceClient.logout(any(TokenInvalidateRequest.class)))
.thenReturn(expectedResponse);
CustomResponse<Void> result = logoutService.logout(tokenInvalidateRequest);
// Then
assertNotNull(result);
assertTrue(result.getIsSuccess());
assertEquals(HttpStatus.OK, result.getHttpStatus());
// Verify
verify(userServiceClient, times(1)).logout(any(TokenInvalidateRequest.class));
}
|
@Override
protected final CompletableFuture<MetricCollectionResponseBody> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway)
throws RestHandlerException {
metricFetcher.update();
final MetricStore.ComponentMetricStore componentMetricStore =
getComponentMetricStore(request, metricFetcher.getMetricStore());
if (componentMetricStore == null || componentMetricStore.metrics == null) {
return CompletableFuture.completedFuture(
new MetricCollectionResponseBody(Collections.emptyList()));
}
final Set<String> requestedMetrics =
new HashSet<>(request.getQueryParameter(MetricsFilterParameter.class));
if (requestedMetrics.isEmpty()) {
return CompletableFuture.completedFuture(
new MetricCollectionResponseBody(getAvailableMetrics(componentMetricStore)));
} else {
final List<Metric> metrics =
getRequestedMetrics(componentMetricStore, requestedMetrics);
return CompletableFuture.completedFuture(new MetricCollectionResponseBody(metrics));
}
}
|
@Test
void testListMetrics() throws Exception {
final CompletableFuture<MetricCollectionResponseBody> completableFuture =
testMetricsHandler.handleRequest(
HandlerRequest.create(
EmptyRequestBody.getInstance(),
new TestMessageParameters(),
Collections.emptyList()),
mockDispatcherGateway);
assertThat(completableFuture).isDone();
final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get();
assertThat(metricCollectionResponseBody.getMetrics()).hasSize(1);
final Metric metric = metricCollectionResponseBody.getMetrics().iterator().next();
assertThat(metric.getId()).isEqualTo(TEST_METRIC_NAME);
assertThat(metric.getValue()).isNull();
}
|
@Override
public ByteBuf getBytes(int index, byte[] dst) {
getBytes(index, dst, 0, dst.length);
return this;
}
|
@Test
public void getDirectByteBufferBoundaryCheck() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.getBytes(-1, ByteBuffer.allocateDirect(0));
}
});
}
|
@VisibleForTesting
static Optional<String> checkSchemas(
final LogicalSchema schema,
final LogicalSchema other
) {
final Optional<String> keyError = checkSchemas(schema.key(), other.key(), "key ")
.map(msg -> "Key columns must be identical. " + msg);
if (keyError.isPresent()) {
return keyError;
}
return checkSchemas(schema.columns(), other.columns(), "");
}
|
@Test
public void shouldEnforceNoReordering() {
// Given:
final LogicalSchema someSchema = LogicalSchema.builder()
.keyColumn(ColumnName.of("k0"), SqlTypes.INTEGER)
.valueColumn(ColumnName.of("f0"), SqlTypes.BIGINT)
.valueColumn(ColumnName.of("f1"), SqlTypes.STRING)
.build();
final LogicalSchema otherSchema = LogicalSchema.builder()
.keyColumn(ColumnName.of("k0"), SqlTypes.INTEGER)
.valueColumn(ColumnName.of("f1"), SqlTypes.STRING)
.valueColumn(ColumnName.of("f0"), SqlTypes.BIGINT)
.build();
// When:
final Optional<String> s = StructuredDataSource.checkSchemas(someSchema, otherSchema);
// Then:
assertThat(s.isPresent(), is(true));
assertThat(s.get(), containsString("The following columns are changed, missing or reordered: [`f0` BIGINT, `f1` STRING]"));
}
|
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by(
PredicateT predicate) {
return new Filter<>(predicate);
}
|
@Test
@Category(NeedsRunner.class)
public void testFilterByMethodReferenceWithLambda() {
PCollection<Integer> output =
p.apply(Create.of(1, 2, 3, 4, 5, 6, 7)).apply(Filter.by(new EvenFilter()::isEven));
PAssert.that(output).containsInAnyOrder(2, 4, 6);
p.run();
}
|
public static ExecutionArrayList<Byte> hexToBytes(ExecutionContext ctx, String value) {
String hex = prepareNumberString(value, true);
if (hex == null) {
throw new IllegalArgumentException("Hex string must be not empty!");
}
int len = hex.length();
if (len % 2 > 0) {
throw new IllegalArgumentException("Hex string must be even-length.");
}
int radix = isHexadecimal(value);
if (radix != HEX_RADIX) {
throw new NumberFormatException("Value: \"" + value + "\" is not numeric or hexDecimal format!");
}
byte [] data = hexToBytes(hex);
return bytesToExecutionArrayList(ctx, data);
}
|
@Test
public void hexToBytes_Test() {
String input = "0x01752B0367FA000500010488FFFFFFFFFFFFFFFF33";
byte[] expected = {1, 117, 43, 3, 103, -6, 0, 5, 0, 1, 4, -120, -1, -1, -1, -1, -1, -1, -1, -1, 51};
List<Byte> actual = TbUtils.hexToBytes(ctx, input);
Assertions.assertEquals(toList(expected), actual);
try {
input = "0x01752B0367FA000500010488FFFFFFFFFFFFFFFF3";
TbUtils.hexToBytes(ctx, input);
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("Hex string must be even-length."));
}
try {
input = "0x01752B0367KA000500010488FFFFFFFFFFFFFFFF33";
TbUtils.hexToBytes(ctx, input);
} catch (NumberFormatException e) {
Assertions.assertTrue(e.getMessage().contains("Value: \"" + input + "\" is not numeric or hexDecimal format!"));
}
try {
input = "";
TbUtils.hexToBytes(ctx, input);
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("Hex string must be not empty"));
}
}
|
@Override
public boolean tryAcquireJobLock(Configuration conf) {
Path path = new Path(locksDir, String.format(LOCKS_DIR_JOB_FILENAME, getJobJtIdentifier(conf)));
return tryCreateFile(conf, path);
}
|
@Test(expected = NullPointerException.class)
public void testMissingJobId() {
Configuration conf = new Configuration();
tested.tryAcquireJobLock(conf);
}
|
public synchronized Topology addSource(final String name,
final String... topics) {
internalTopologyBuilder.addSource(null, name, null, null, null, topics);
return this;
}
|
@Test
public void shouldNotAllowNullTopicsWhenAddingSourceWithPattern() {
assertThrows(NullPointerException.class, () -> topology.addSource("source", (Pattern) null));
}
|
public static String findDatumOverlijden(List<Container> categorieList){
return findValue(categorieList, CATEGORIE_OVERLIJDEN, ELEMENT_DATUM_OVERLIJDEN);
}
|
@Test
public void testFindDatumOverlijden() {
assertThat(CategorieUtil.findDatumOverlijden(createFullCategories()), is("datumoverlijden"));
}
|
private StorageVolume getStorageVolumeOfDb(String svName) throws DdlException {
StorageVolume sv = null;
if (svName.equals(StorageVolumeMgr.DEFAULT)) {
sv = getDefaultStorageVolume();
if (sv == null) {
throw ErrorReportException.report(ErrorCode.ERR_NO_DEFAULT_STORAGE_VOLUME);
}
} else {
sv = getStorageVolumeByName(svName);
if (sv == null) {
throw new DdlException("Unknown storage volume \"" + svName + "\"");
}
}
return sv;
}
|
@Test
public void testGetStorageVolumeOfDb() throws DdlException, AlreadyExistsException {
new Expectations() {
{
editLog.logSetDefaultStorageVolume((SetDefaultStorageVolumeLog) any);
}
};
SharedDataStorageVolumeMgr sdsvm = new SharedDataStorageVolumeMgr();
ErrorReportException ex = Assert.assertThrows(ErrorReportException.class, () -> Deencapsulation.invoke(sdsvm,
"getStorageVolumeOfDb", StorageVolumeMgr.DEFAULT));
Assert.assertEquals(ErrorCode.ERR_NO_DEFAULT_STORAGE_VOLUME, ex.getErrorCode());
sdsvm.createBuiltinStorageVolume();
String defaultSVId = sdsvm.getStorageVolumeByName(SharedDataStorageVolumeMgr.BUILTIN_STORAGE_VOLUME).getId();
String svName = "test";
List<String> locations = Arrays.asList("s3://abc");
Map<String, String> storageParams = new HashMap<>();
storageParams.put(AWS_S3_REGION, "region");
storageParams.put(AWS_S3_ENDPOINT, "endpoint");
storageParams.put(AWS_S3_USE_AWS_SDK_DEFAULT_BEHAVIOR, "true");
String testSVId = sdsvm.createStorageVolume(svName, "S3", locations, storageParams, Optional.empty(), "");
StorageVolume sv = Deencapsulation.invoke(sdsvm, "getStorageVolumeOfDb", StorageVolumeMgr.DEFAULT);
Assert.assertEquals(defaultSVId, sv.getId());
sv = Deencapsulation.invoke(sdsvm, "getStorageVolumeOfDb", svName);
Assert.assertEquals(testSVId, sv.getId());
}
|
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently available in the standard converters
final JsonNode value = isJsonSchema
? JsonSerdeUtils.readJsonSR(bytes, MAPPER, JsonNode.class)
: MAPPER.readTree(bytes);
final Object coerced = enforceFieldType(
"$",
new JsonValueContext(value, schema)
);
if (LOG.isTraceEnabled()) {
LOG.trace("Deserialized {}. topic:{}, row:{}", target, topic, coerced);
}
return SerdeUtils.castToTargetType(coerced, targetType);
} catch (final Exception e) {
// Clear location in order to avoid logging data, for security reasons
if (e instanceof JsonParseException) {
((JsonParseException) e).clearLocation();
}
throw new SerializationException(
"Failed to deserialize " + target + " from topic: " + topic + ". " + e.getMessage(), e);
}
}
|
@Test
public void shouldDeserializeJsonObjectWithMissingFields() {
// Given:
final Map<String, Object> orderRow = new HashMap<>(AN_ORDER);
orderRow.remove("ordertime");
final byte[] bytes = serializeJson(orderRow);
// When:
final Struct result = deserializer.deserialize(SOME_TOPIC, bytes);
// Then:
assertThat(result, is(expectedOrder
.put(ORDERTIME, null)
));
}
|
public static DatabaseBackendHandler newInstance(final QueryContext queryContext, final ConnectionSession connectionSession, final boolean preferPreparedStatement) {
SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext();
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof DoStatement) {
return new UnicastDatabaseBackendHandler(queryContext, connectionSession);
}
if (sqlStatement instanceof SetStatement && null == connectionSession.getUsedDatabaseName()) {
return () -> new UpdateResponseHeader(sqlStatement);
}
if (sqlStatement instanceof DALStatement && !isDatabaseRequiredDALStatement(sqlStatement)
|| sqlStatement instanceof SelectStatement && !((SelectStatement) sqlStatement).getFrom().isPresent()) {
return new UnicastDatabaseBackendHandler(queryContext, connectionSession);
}
return DatabaseConnectorFactory.getInstance().newInstance(queryContext, connectionSession.getDatabaseConnectionManager(), preferPreparedStatement);
}
|
@Test
void assertNewInstanceReturnedUnicastDatabaseBackendHandlerWithDAL() {
String sql = "DESC tbl";
SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DALStatement.class));
DatabaseBackendHandler actual =
DatabaseBackendHandlerFactory.newInstance(
new QueryContext(sqlStatementContext, sql, Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class)),
mock(ConnectionSession.class), false);
assertThat(actual, instanceOf(UnicastDatabaseBackendHandler.class));
}
|
@Override
public AccessKeyPair getAccessKey(URL url, Invocation invocation) {
AccessKeyPair accessKeyPair = new AccessKeyPair();
String accessKeyId = url.getParameter(Constants.ACCESS_KEY_ID_KEY);
String secretAccessKey = url.getParameter(Constants.SECRET_ACCESS_KEY_KEY);
accessKeyPair.setAccessKey(accessKeyId);
accessKeyPair.setSecretKey(secretAccessKey);
return accessKeyPair;
}
|
@Test
void testGetAccessKey() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk");
DefaultAccessKeyStorage defaultAccessKeyStorage = new DefaultAccessKeyStorage();
AccessKeyPair accessKey = defaultAccessKeyStorage.getAccessKey(url, mock(Invocation.class));
assertNotNull(accessKey);
assertEquals(accessKey.getAccessKey(), "ak");
assertEquals(accessKey.getSecretKey(), "sk");
}
|
@Override
public boolean checkAndSetSupportPartitionInformation(Connection connection) {
String catalogSchema = "information_schema";
String partitionInfoTable = "partitions";
// Different types of MySQL protocol databases have different case names for schema and table names,
// which need to be converted to lowercase for comparison
try (ResultSet catalogSet = connection.getMetaData().getCatalogs()) {
while (catalogSet.next()) {
String schemaName = catalogSet.getString("TABLE_CAT");
if (schemaName.equalsIgnoreCase(catalogSchema)) {
try (ResultSet tableSet = connection.getMetaData().getTables(catalogSchema, null, null, null)) {
while (tableSet.next()) {
String tableName = tableSet.getString("TABLE_NAME");
if (tableName.equalsIgnoreCase(partitionInfoTable)) {
return this.supportPartitionInformation = true;
}
}
}
}
}
} catch (SQLException e) {
throw new StarRocksConnectorException(e.getMessage());
}
return this.supportPartitionInformation = false;
}
|
@Test
public void testCheckPartitionWithoutPartitionsTable() {
try {
JDBCSchemaResolver schemaResolver = new MysqlSchemaResolver();
Assert.assertFalse(schemaResolver.checkAndSetSupportPartitionInformation(connection));
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
}
}
|
public static PipelineJob get(final String jobId) {
return JOBS.get(jobId);
}
|
@Test
void assertGet() {
assertThat(PipelineJobRegistry.get("foo_job"), is(job));
}
|
public byte[] toByteArray() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
write(stream);
} catch (IOException e) {
// Should not happen as ByteArrayOutputStream does not throw IOException on write
throw new RuntimeException(e);
}
return stream.toByteArray();
}
|
@Test
public void testToByteArray_lt_OP_PUSHDATA1() {
// < OP_PUSHDATA1
for (byte len = 1; len < OP_PUSHDATA1; len++) {
byte[] bytes = new byte[len];
RANDOM.nextBytes(bytes);
byte[] expected = ByteUtils.concat(new byte[] { len }, bytes);
byte[] actual = new ScriptChunk(len, bytes).toByteArray();
assertArrayEquals(expected, actual);
}
}
|
@Override
public void start(EdgeExplorer explorer, int startNode) {
SimpleIntDeque fifo = new SimpleIntDeque();
GHBitSet visited = createBitSet();
visited.add(startNode);
fifo.push(startNode);
int current;
while (!fifo.isEmpty()) {
current = fifo.pop();
if (!goFurther(current))
continue;
EdgeIterator iter = explorer.setBaseNode(current);
while (iter.next()) {
int connectedId = iter.getAdjNode();
if (checkAdjacent(iter) && !visited.contains(connectedId)) {
visited.add(connectedId);
fifo.push(connectedId);
}
}
}
}
|
@Test
public void testBFS2() {
BreadthFirstSearch bfs = new BreadthFirstSearch() {
@Override
protected GHBitSet createBitSet() {
return new GHTBitSet();
}
@Override
public boolean goFurther(int v) {
counter++;
assertFalse(set.contains(v), "v " + v + " is already contained in set. iteration:" + counter);
set.add(v);
list.add(v);
return super.goFurther(v);
}
};
BaseGraph g = new BaseGraph.Builder(1).create();
g.edge(1, 2);
g.edge(2, 3);
g.edge(3, 4);
g.edge(1, 5);
g.edge(5, 6);
g.edge(6, 4);
bfs.start(g.createEdgeExplorer(), 1);
assertTrue(counter > 0);
assertEquals("[1, 5, 2, 6, 3, 4]", list.toString());
}
|
boolean hasCapacity() {
if (aggBuilder.getRecordsCount() == 0) {
return true;
}
int avgSize = (sizeBytes - BASE_OVERHEAD) / aggBuilder.getRecordsCount();
return sizeBytes + avgSize <= maxAggregatedBytes;
}
|
@Test
public void testHasCapacity() {
aggregator = new RecordsAggregator(BASE_OVERHEAD + PARTITION_KEY_OVERHEAD + 100, new Instant());
assertThat(aggregator.addRecord(PARTITION_KEY, null, new byte[30])).isTrue();
assertThat(aggregator.hasCapacity()).isTrue(); // can fit next record of avg size
assertThat(aggregator.addRecord(PARTITION_KEY, null, new byte[30])).isTrue();
assertThat(aggregator.hasCapacity()).isFalse(); // can't fit next record of avg size (overhead)
assertThat(aggregator.addRecord(PARTITION_KEY, null, new byte[30])).isFalse();
}
|
@Override
public synchronized boolean registerAETitle(String aet) throws ConfigurationException {
ensureConfigurationExists();
try {
registerAET(aet);
return true;
} catch (AETitleAlreadyExistsException e) {
return false;
}
}
|
@Test
public void testRegisterAETitle() throws Exception {
config.unregisterAETitle("TEST-AET1");
assertTrue(config.registerAETitle("TEST-AET1"));
assertFalse(config.registerAETitle("TEST-AET1"));
assertTrue(
Arrays.asList(config.listRegisteredAETitles())
.contains("TEST-AET1"));
config.unregisterAETitle("TEST-AET1");
assertFalse(
Arrays.asList(config.listRegisteredAETitles())
.contains("TEST-AET1"));
}
|
public boolean denied(String name, MediaType mediaType) {
String suffix = (name.contains(".") ? name.substring(name.lastIndexOf(".") + 1) : "").toLowerCase(Locale.ROOT);
boolean defaultDeny = false;
if (CollectionUtils.isNotEmpty(denyFiles)) {
if (denyFiles.contains(suffix)) {
return true;
}
defaultDeny = false;
}
if (CollectionUtils.isNotEmpty(allowFiles)) {
if (allowFiles.contains(suffix)) {
return false;
}
defaultDeny = true;
}
if (CollectionUtils.isNotEmpty(denyMediaType)) {
if (denyMediaType.contains(mediaType.toString())) {
return true;
}
defaultDeny = false;
}
if (CollectionUtils.isNotEmpty(allowMediaType)) {
if (allowMediaType.contains(mediaType.toString())) {
return false;
}
defaultDeny = true;
}
return defaultDeny;
}
|
@Test
public void testDenyWithAllow(){
FileUploadProperties uploadProperties=new FileUploadProperties();
uploadProperties.setAllowFiles(new HashSet<>(Arrays.asList("xls","json")));
assertFalse(uploadProperties.denied("test.xls", MediaType.ALL));
assertFalse(uploadProperties.denied("test.XLS", MediaType.ALL));
assertTrue(uploadProperties.denied("test.exe", MediaType.ALL));
}
|
protected static String normalizePath( String path, String scheme ) {
String normalizedPath = path;
if ( path.startsWith( "\\\\" ) ) {
File file = new File( path );
normalizedPath = file.toURI().toString();
} else if ( scheme == null ) {
File file = new File( path );
normalizedPath = file.getAbsolutePath();
}
return normalizedPath;
}
|
@Test
public void testNormalizePathWithFile() {
String vfsFilename = "\\\\tmp/acltest.txt";
String testNormalizePath = KettleVFS.normalizePath( vfsFilename, "someScheme" );
assertTrue( testNormalizePath.startsWith( "file:/" ) );
}
|
public static int fromLogical(Schema schema, java.util.Date value) {
if (!(LOGICAL_NAME.equals(schema.name())))
throw new DataException("Requested conversion of Time object but the schema does not match.");
Calendar calendar = Calendar.getInstance(UTC);
calendar.setTime(value);
long unixMillis = calendar.getTimeInMillis();
if (unixMillis < 0 || unixMillis > MILLIS_PER_DAY) {
throw new DataException("Kafka Connect Time type should not have any date fields set to non-zero values.");
}
return (int) unixMillis;
}
|
@Test
public void testFromLogical() {
assertEquals(0, Time.fromLogical(Time.SCHEMA, EPOCH.getTime()));
assertEquals(10000, Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime()));
}
|
@Override
public Iterator<E> iterator() {
return new ElementIterator();
}
|
@Test
public void testIteratorHasNextReturnsFalseIfIteratedOverAll() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
populateSet(set, 1);
final Iterator<Integer> iterator = set.iterator();
iterator.next();
assertFalse(iterator.hasNext());
}
|
@Override
public Object toKsqlRow(final Schema connectSchema, final Object connectData) {
if (connectData == null) {
return null;
}
return toKsqlValue(schema, connectSchema, connectData, "");
}
|
@Test
public void shouldTranslateStructFieldWithDifferentCase() {
// Given:
final Schema structSchema = SchemaBuilder
.struct()
.field("INT", SchemaBuilder.OPTIONAL_INT32_SCHEMA)
.optional()
.build();
final Schema rowSchema = SchemaBuilder
.struct()
.field("STRUCT", structSchema)
.build();
final Schema dataStructSchema = SchemaBuilder
.struct()
.field("iNt", SchemaBuilder.OPTIONAL_INT32_SCHEMA)
.optional()
.build();
final Schema dataRowSchema = SchemaBuilder
.struct()
.field("STRUCT", dataStructSchema)
.optional()
.build();
final Struct connectStruct = new Struct(dataRowSchema);
final Struct structColumn = new Struct(dataStructSchema);
structColumn.put("iNt", 123);
connectStruct.put("STRUCT", structColumn);
final ConnectDataTranslator connectToKsqlTranslator = new ConnectDataTranslator(rowSchema);
// When:
final Struct row = (Struct) connectToKsqlTranslator.toKsqlRow(dataRowSchema, connectStruct);
// Then:
assertThat(row.get("STRUCT"), instanceOf(Struct.class));
final Struct connectStructColumn = (Struct)row.get("STRUCT");
assertThat(connectStructColumn.schema(), equalTo(structSchema));
assertThat(connectStructColumn.get("INT"), equalTo(123));
}
|
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
attributes.find(file, listener);
return true;
}
catch(NotfoundException e) {
return false;
}
catch(AccessDeniedException e) {
// Object is inaccessible to current user, but does exist.
return true;
}
}
|
@Test
public void testFindFile() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new GoogleStorageTouchFeature(session).touch(file, new TransferStatus());
assertTrue(new GoogleStorageFindFeature(session).find(file));
assertFalse(new GoogleStorageFindFeature(session).find(new Path(file.getAbsolute(), EnumSet.of(Path.Type.directory))));
new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
|
@Override
public void close() throws IOException {
if (null != closeableGroup) {
closeableGroup.close();
}
}
|
@Test
public void testCloseBeforeInitializeDoesntThrow() throws IOException {
catalog = new SnowflakeCatalog();
// Make sure no exception is thrown if we call close() before initialize(), in case callers
// add a catalog to auto-close() helpers but end up never using/initializing a catalog.
catalog.close();
assertThat(fakeClient.isClosed())
.overridingErrorMessage("expected not to have called close() on snowflakeClient")
.isFalse();
}
|
@Override
public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity)
throws Exception {
HttpRequestBase request = build(uri, httpMethod, requestHttpEntity, defaultConfig);
CloseableHttpResponse response = client.execute(request);
return new DefaultClientHttpResponse(response);
}
|
@Test
void testExecuteForFormWithoutConfig() throws Exception {
isForm = true;
Header header = Header.newInstance().addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
Map<String, String> body = new HashMap<>();
body.put("test", "test");
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity);
assertEquals(response, getActualResponse(actual));
}
|
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
long datetime = payload.readInt8();
return 0L == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDateTime(datetime);
}
|
@Test
void assertRead() {
when(payload.readInt8()).thenReturn(99991231235959L);
LocalDateTime expected = LocalDateTime.of(9999, 12, 31, 23, 59, 59);
assertThat(new MySQLDatetimeBinlogProtocolValue().read(columnDef, payload), is(Timestamp.valueOf(expected)));
}
|
@SuppressWarnings("unchecked")
public static <S extends Stanza> S parseStanza(String stanza) throws XmlPullParserException, SmackParsingException, IOException {
return (S) parseStanza(getParserFor(stanza), XmlEnvironment.EMPTY);
}
|
@Test
public void multipleMessageBodiesParsingTest() throws Exception {
String control = XMLBuilder.create("message")
.namespace(StreamOpen.CLIENT_NAMESPACE)
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", "en")
.e("body")
.t("This is a test of the emergency broadcast system, 1.")
.up()
.e("body")
.a("xml:lang", "ru")
.t("This is a test of the emergency broadcast system, 2.")
.up()
.e("body")
.a("xml:lang", "sp")
.t("This is a test of the emergency broadcast system, 3.")
.asString(outputProperties);
Stanza message = PacketParserUtils.parseStanza(control);
assertXmlSimilar(control, message.toXML());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.