focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public NearCachePreloaderConfig setStoreInitialDelaySeconds(int storeInitialDelaySeconds) {
this.storeInitialDelaySeconds = checkPositive("storeInitialDelaySeconds",
storeInitialDelaySeconds);
return this;
}
|
@Test(expected = IllegalArgumentException.class)
public void setStoreInitialDelaySeconds_withZero() {
config.setStoreInitialDelaySeconds(0);
}
|
public static OutputStream string2OutputStream(final String string, final String charsetName) {
if (string == null || isSpace(charsetName)) return null;
try {
return bytes2OutputStream(string.getBytes(charsetName));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
|
@Test
public void string2OutputStreamInputQuestionsReturnNull() {
Assert.assertNull(
ConvertKit.string2OutputStream("\u0000\u0000\u0000???????????????????", "")
);
}
|
@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
return unmarshal(exchange, (Object) stream);
}
|
@Test
public void testJsonApiUnmarshall() throws Exception {
Class<?>[] formats = { MyBook.class, MyAuthor.class };
JsonApiDataFormat jsonApiDataFormat = new JsonApiDataFormat(MyBook.class, formats);
String jsonApiInput = this.generateTestDataAsString();
Exchange exchange = new DefaultExchange(context);
Object outputObj = jsonApiDataFormat.unmarshal(exchange, new ByteArrayInputStream(jsonApiInput.getBytes()));
assertNotNull(outputObj);
MyBook book = (MyBook) outputObj;
assertEquals("Camel in Action", book.getTitle());
assertEquals("1", book.getAuthor().getAuthorId());
}
|
@Override
public Optional<String> getLocalHadoopConfigurationDirectory() {
final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR);
if (StringUtils.isNotBlank(hadoopConfDirEnv)) {
return Optional.of(hadoopConfDirEnv);
}
final String hadoopHomeEnv = System.getenv(Constants.ENV_HADOOP_HOME);
if (StringUtils.isNotBlank(hadoopHomeEnv)) {
// Hadoop 2.2+
final File hadoop2ConfDir = new File(hadoopHomeEnv, "/etc/hadoop");
if (hadoop2ConfDir.exists()) {
return Optional.of(hadoop2ConfDir.getAbsolutePath());
}
// Hadoop 1.x
final File hadoop1ConfDir = new File(hadoopHomeEnv, "/conf");
if (hadoop1ConfDir.exists()) {
return Optional.of(hadoop1ConfDir.getAbsolutePath());
}
}
return Optional.empty();
}
|
@Test
void testGetLocalHadoopConfigurationDirectoryReturnEmptyWhenHadoopEnvIsNotSet()
throws Exception {
runTestWithEmptyEnv(
() -> {
final Optional<String> optional =
testingKubernetesParameters.getLocalHadoopConfigurationDirectory();
assertThat(optional).isNotPresent();
});
}
|
@Override
public void configure(Map<String, ?> configs) {
super.configure(configs);
configureSamplingInterval(configs);
configurePrometheusAdapter(configs);
configureQueryMap(configs);
}
|
@Test
public void testGetSamplesSuccess() throws Exception {
Map<String, Object> config = new HashMap<>();
config.put(PROMETHEUS_SERVER_ENDPOINT_CONFIG, "http://kafka-cluster-1.org:9090");
addCapacityConfig(config);
Set<String> topics = new HashSet<>(Arrays.asList(TEST_TOPIC, TEST_TOPIC_WITH_DOT));
for (String topic: topics) {
setUp();
_prometheusMetricSampler.configure(config);
MetricSamplerOptions metricSamplerOptions = buildMetricSamplerOptions(topic);
_prometheusMetricSampler._prometheusAdapter = _prometheusAdapter;
for (RawMetricType rawMetricType : _prometheusQueryMap.keySet()) {
setupPrometheusAdapterMock(rawMetricType, buildBrokerResults(),
buildTopicResults(topic), buildPartitionResults(topic));
}
replay(_prometheusAdapter);
MetricSampler.Samples samples = _prometheusMetricSampler.getSamples(metricSamplerOptions);
assertSamplesValid(samples, topic);
verify(_prometheusAdapter);
}
}
|
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
}
|
@Test
public void testCheckTypes() {
assertThat(rxJava2BulkheadAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava2BulkheadAspectExt.canHandleReturnType(Single.class)).isTrue();
}
|
@Override
public ImportResult importItem(
UUID id,
IdempotentImportExecutor idempotentExecutor,
TokensAndUrlAuthData authData,
MailContainerResource data) throws Exception {
// Lazy init the request for all labels in the destination account, since it may not be needed
// Mapping of labelName -> destination label id
Supplier<Map<String, String>> allDestinationLabels = allDestinationLabelsSupplier(authData);
// Import folders/labels
importLabels(authData, idempotentExecutor, allDestinationLabels, data.getFolders());
// Import the special DTP label
importDTPLabel(authData, idempotentExecutor, allDestinationLabels);
// Import labels from the given set of messages
importLabelsForMessages(
authData, idempotentExecutor, allDestinationLabels, data.getMessages());
importMessages(authData, idempotentExecutor, data.getMessages());
return ImportResult.OK;
}
|
@Test
public void importMessage() throws Exception {
MailContainerResource resource =
new MailContainerResource(null, Collections.singletonList(MESSAGE_MODEL));
ImportResult result = googleMailImporter.importItem(JOB_ID, executor, null, resource);
// Getting list of labels from Google
verify(labelsList, atLeastOnce()).execute();
// Importing message
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
verify(messages).insert(eq(GoogleMailImporter.USER), messageArgumentCaptor.capture());
assertThat(messageArgumentCaptor.getValue().getRaw()).isEqualTo(MESSAGE_RAW);
// TODO(olsona): test labels
}
|
@Override
public void clear() {
cache.clear();
}
|
@Test
public void testClear() throws Exception {
EventLoopGroup group = new DefaultEventLoopGroup(1);
try {
EventLoop loop = group.next();
final DefaultDnsCnameCache cache = new DefaultDnsCnameCache();
cache.cache("x.netty.io", "mapping.netty.io", 100000, loop);
cache.cache("y.netty.io", "mapping.netty.io", 100000, loop);
assertEquals("mapping.netty.io", cache.get("x.netty.io"));
assertEquals("mapping.netty.io", cache.get("y.netty.io"));
assertTrue(cache.clear("x.netty.io"));
assertNull(cache.get("x.netty.io"));
assertEquals("mapping.netty.io", cache.get("y.netty.io"));
cache.clear();
assertNull(cache.get("y.netty.io"));
} finally {
group.shutdownGracefully();
}
}
|
@Override
public SyntheticSourceReader createReader(PipelineOptions pipelineOptions) {
return new SyntheticSourceReader(this);
}
|
@Test
public void testIncreasingProgress() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
testSourceOptions.progressShape = ProgressShape.LINEAR;
SyntheticBoundedSource source = new SyntheticBoundedSource(testSourceOptions);
BoundedSource.BoundedReader<KV<byte[], byte[]>> reader = source.createReader(options);
// Reader starts at 0.0 progress.
assertEquals(0, reader.getFractionConsumed(), 1e-5);
// Set the lastFractionConsumed < 0.0 so that we can use strict inequality in the below loop.
double lastFractionConsumed = -1.0;
for (boolean more = reader.start(); more; more = reader.advance()) {
assertTrue(reader.getFractionConsumed() > lastFractionConsumed);
lastFractionConsumed = reader.getFractionConsumed();
}
assertEquals(1, reader.getFractionConsumed(), 1e-5);
}
|
public static String getDatabaseName(final SQLStatement sqlStatement, final String currentDatabaseName) {
Optional<DatabaseSegment> databaseSegment = sqlStatement instanceof FromDatabaseAvailable ? ((FromDatabaseAvailable) sqlStatement).getDatabase() : Optional.empty();
return databaseSegment.map(optional -> optional.getIdentifier().getValue()).orElse(currentDatabaseName);
}
|
@Test
void assertDatabaseNameWhenAvailableInSQLStatement() {
FromDatabaseAvailable sqlStatement = mock(FromDatabaseAvailable.class, withSettings().extraInterfaces(SQLStatement.class));
DatabaseSegment databaseSegment = mock(DatabaseSegment.class, RETURNS_DEEP_STUBS);
when(databaseSegment.getIdentifier().getValue()).thenReturn("bar_db");
when(sqlStatement.getDatabase()).thenReturn(Optional.of(databaseSegment));
assertThat(DatabaseNameUtils.getDatabaseName((SQLStatement) sqlStatement, "foo_db"), is("bar_db"));
}
|
@Override
public V putIfAbsent(K k, V v) {
return mInternalMap.putIfAbsent(new IdentityObject<>(k), v);
}
|
@Test
public void putIfAbsent() {
String t = new String("test");
assertNull(mMap.putIfAbsent(t, "v1"));
assertEquals(1, mMap.size());
assertEquals("v1", mMap.get(t));
assertFalse(mMap.containsKey("test"));
assertEquals("v1", mMap.putIfAbsent(t, "v2"));
assertEquals("v1", mMap.get(t));
}
|
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
}
|
@Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfByteArrayTooLongPrefixLengthIPv4() {
Ip4Prefix ipPrefix;
byte[] value;
value = new byte[] {1, 2, 3, 4};
ipPrefix = Ip4Prefix.valueOf(value, 33);
}
|
@SuppressWarnings("MethodLength")
static void dissectCommand(
final DriverEventCode code, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
final int encodedLength = dissectLogHeader(CONTEXT, code, buffer, offset, builder);
builder.append(": ");
switch (code)
{
case CMD_IN_ADD_PUBLICATION:
case CMD_IN_ADD_EXCLUSIVE_PUBLICATION:
PUB_MSG.wrap(buffer, offset + encodedLength);
dissectPublication(builder);
break;
case CMD_IN_ADD_SUBSCRIPTION:
SUB_MSG.wrap(buffer, offset + encodedLength);
dissectSubscription(builder);
break;
case CMD_IN_REMOVE_PUBLICATION:
case CMD_IN_REMOVE_SUBSCRIPTION:
case CMD_IN_REMOVE_COUNTER:
REMOVE_MSG.wrap(buffer, offset + encodedLength);
dissectRemoveEvent(builder);
break;
case CMD_OUT_PUBLICATION_READY:
case CMD_OUT_EXCLUSIVE_PUBLICATION_READY:
PUB_READY.wrap(buffer, offset + encodedLength);
dissectPublicationReady(builder);
break;
case CMD_OUT_AVAILABLE_IMAGE:
IMAGE_READY.wrap(buffer, offset + encodedLength);
dissectImageReady(builder);
break;
case CMD_OUT_ON_OPERATION_SUCCESS:
OPERATION_SUCCEEDED.wrap(buffer, offset + encodedLength);
dissectOperationSuccess(builder);
break;
case CMD_IN_KEEPALIVE_CLIENT:
case CMD_IN_CLIENT_CLOSE:
CORRELATED_MSG.wrap(buffer, offset + encodedLength);
dissectCorrelationEvent(builder);
break;
case CMD_OUT_ON_UNAVAILABLE_IMAGE:
IMAGE_MSG.wrap(buffer, offset + encodedLength);
dissectImage(builder);
break;
case CMD_IN_ADD_DESTINATION:
case CMD_IN_REMOVE_DESTINATION:
case CMD_IN_ADD_RCV_DESTINATION:
case CMD_IN_REMOVE_RCV_DESTINATION:
DESTINATION_MSG.wrap(buffer, offset + encodedLength);
dissectDestination(builder);
break;
case CMD_OUT_ERROR:
ERROR_MSG.wrap(buffer, offset + encodedLength);
dissectError(builder);
break;
case CMD_IN_ADD_COUNTER:
COUNTER_MSG.wrap(buffer, offset + encodedLength);
dissectCounter(builder);
break;
case CMD_OUT_SUBSCRIPTION_READY:
SUBSCRIPTION_READY.wrap(buffer, offset + encodedLength);
dissectSubscriptionReady(builder);
break;
case CMD_OUT_COUNTER_READY:
case CMD_OUT_ON_UNAVAILABLE_COUNTER:
COUNTER_UPDATE.wrap(buffer, offset + encodedLength);
dissectCounterUpdate(builder);
break;
case CMD_OUT_ON_CLIENT_TIMEOUT:
CLIENT_TIMEOUT.wrap(buffer, offset + encodedLength);
dissectClientTimeout(builder);
break;
case CMD_IN_TERMINATE_DRIVER:
TERMINATE_DRIVER.wrap(buffer, offset + encodedLength);
dissectTerminateDriver(builder);
break;
default:
builder.append("COMMAND_UNKNOWN: ").append(code);
break;
}
}
|
@Test
void dissectCommandUnknown()
{
final DriverEventCode eventCode = SEND_CHANNEL_CREATION;
internalEncodeLogHeader(buffer, 0, 5, 5, () -> 1_000_000_000L);
dissectCommand(eventCode, buffer, 0, builder);
assertEquals("[1.000000000] " + CONTEXT + ": " + eventCode.name() + " [5/5]: COMMAND_UNKNOWN: " + eventCode,
builder.toString());
}
|
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) {
NewExternalIssue newExternalIssue = sensorContext.newExternalIssue();
newExternalIssue.type(DEFAULT_TYPE);
newExternalIssue.engineId(driverName);
newExternalIssue.severity(toSonarQubeSeverity(ruleSeverity));
newExternalIssue.ruleId(requireNonNull(result.getRuleId(), "No ruleId found for issue thrown by driver " + driverName));
newExternalIssue.cleanCodeAttribute(DEFAULT_CLEAN_CODE_ATTRIBUTE);
newExternalIssue.addImpact(DEFAULT_SOFTWARE_QUALITY, toSonarQubeImpactSeverity(ruleSeverityForNewTaxonomy));
mapLocations(result, newExternalIssue);
return newExternalIssue;
}
|
@Test
public void mapResult_concatResultMessageAndLocationMessageForIssue() {
Location location = new Location().withMessage(new Message().withText("Location message"));
result.withLocations(List.of(location));
resultMapper.mapResult(DRIVER_NAME, WARNING, WARNING, result);
verify(newExternalIssueLocation).message("Result message - Location message");
}
|
public static LabelSelectorBuilder<?> builder() {
return new LabelSelectorBuilder<>();
}
|
@Test
void builderTest() {
var labelSelector = LabelSelector.builder()
.eq("a", "v1")
.in("b", "v2", "v3")
.build();
assertThat(labelSelector.toString())
.isEqualTo("a equal v1, b IN (v2, v3)");
}
|
public static Builder builder() {
return new Builder();
}
|
@Test
public void embeddedUdp() {
final ByteBuf pcapBuffer = Unpooled.buffer();
final ByteBuf payload = Unpooled.wrappedBuffer("Meow".getBytes());
InetSocketAddress serverAddr = new InetSocketAddress("1.1.1.1", 1234);
InetSocketAddress clientAddr = new InetSocketAddress("2.2.2.2", 3456);
// We fake a client
EmbeddedChannel embeddedChannel = new EmbeddedChannel(
PcapWriteHandler.builder()
.forceUdpChannel(clientAddr, serverAddr)
.build(new ByteBufOutputStream(pcapBuffer))
);
assertTrue(embeddedChannel.writeOutbound(payload));
assertEquals(payload, embeddedChannel.readOutbound());
// Verify the capture data
verifyUdpCapture(true, pcapBuffer, serverAddr, clientAddr);
assertFalse(embeddedChannel.finishAndReleaseAll());
}
|
public static Validator validRegex() {
return (name, val) -> {
if (!(val instanceof List)) {
throw new IllegalArgumentException("validator should only be used with "
+ "LIST of STRING defs");
}
final StringBuilder regexBuilder = new StringBuilder();
for (Object item : (List)val) {
if (!(item instanceof String)) {
throw new IllegalArgumentException("validator should only be used with "
+ "LIST of STRING defs");
}
if (regexBuilder.length() > 0) {
regexBuilder.append("|");
}
regexBuilder.append((String)item);
}
try {
Pattern.compile(regexBuilder.toString());
} catch (final Exception e) {
throw new ConfigException(name, val, "Not valid regular expression: " + e.getMessage());
}
};
}
|
@Test
public void shouldThrowOnNoRegexList() {
// Given:
final Validator validator = ConfigValidators.validRegex();
// When:
final Exception e = assertThrows(
IllegalArgumentException.class,
() -> validator.ensureValid("propName", "*.*")
);
// Then:
assertThat(e.getMessage(), containsString("validator should only be used with LIST of STRING defs"));
}
|
@Override
public String getName() {
return FUNCTION_NAME;
}
|
@Test
public void testCastNullColumn() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("cast(%s AS INT)", INT_SV_NULL_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(transformFunction instanceof CastTransformFunction);
Assert.assertEquals(transformFunction.getName(), CastTransformFunction.FUNCTION_NAME);
int[] expectedValues = new int[NUM_ROWS];
RoaringBitmap roaringBitmap = new RoaringBitmap();
for (int i = 0; i < NUM_ROWS; i++) {
if (isNullRow(i)) {
roaringBitmap.add(i);
} else {
expectedValues[i] = _intSVValues[i];
}
}
testTransformFunctionWithNull(transformFunction, expectedValues, roaringBitmap);
}
|
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/{executionId}")
@Operation(tags = {"Executions"}, summary = "Get an execution")
public Execution get(
@Parameter(description = "The execution id") @PathVariable String executionId
) {
return executionRepository
.findById(tenantService.resolveTenant(), executionId)
.orElse(null);
}
|
@Test
void restartFromTaskId() throws Exception {
final String flowId = "restart_with_inputs";
final String referenceTaskId = "instant";
// Run execution until it ends
Execution parentExecution = runnerUtils.runOne(null, TESTS_FLOW_NS, flowId, null, (flow, execution1) -> flowIO.typedInputs(flow, execution1, inputs));
Optional<Flow> flow = flowRepositoryInterface.findById(null, TESTS_FLOW_NS, flowId);
assertThat(flow.isPresent(), is(true));
// Run child execution starting from a specific task and wait until it finishes
Execution finishedChildExecution = runnerUtils.awaitChildExecution(
flow.get(),
parentExecution, throwRunnable(() -> {
Thread.sleep(100);
Execution createdChidExec = client.toBlocking().retrieve(
HttpRequest
.POST("/api/v1/executions/" + parentExecution.getId() + "/replay?taskRunId=" + parentExecution.findTaskRunByTaskIdAndValue(referenceTaskId, List.of()).getId(), ImmutableMap.of()),
Execution.class
);
assertThat(createdChidExec, notNullValue());
assertThat(createdChidExec.getParentId(), is(parentExecution.getId()));
assertThat(createdChidExec.getTaskRunList().size(), is(4));
assertThat(createdChidExec.getState().getCurrent(), is(State.Type.RESTARTED));
IntStream
.range(0, 3)
.mapToObj(value -> createdChidExec.getTaskRunList().get(value))
.forEach(taskRun -> assertThat(taskRun.getState().getCurrent(), is(State.Type.SUCCESS)));
assertThat(createdChidExec.getTaskRunList().get(3).getState().getCurrent(), is(State.Type.RESTARTED));
assertThat(createdChidExec.getTaskRunList().get(3).getAttempts().size(), is(1));
}),
Duration.ofSeconds(15));
assertThat(finishedChildExecution, notNullValue());
assertThat(finishedChildExecution.getParentId(), is(parentExecution.getId()));
assertThat(finishedChildExecution.getTaskRunList().size(), is(5));
finishedChildExecution
.getTaskRunList()
.stream()
.map(TaskRun::getState)
.forEach(state -> assertThat(state.getCurrent(), is(State.Type.SUCCESS)));
}
|
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not found.", groupId));
}
if (group == null) {
ClassicGroup classicGroup = new ClassicGroup(logContext, groupId, ClassicGroupState.EMPTY, time, metrics);
groups.put(groupId, classicGroup);
metrics.onClassicGroupStateTransition(null, classicGroup.currentState());
return classicGroup;
} else {
if (group.type() == CLASSIC) {
return (ClassicGroup) group;
} else {
// We don't support upgrading/downgrading between protocols at the moment so
// we throw an exception if a group exists with the wrong type.
throw new GroupIdNotFoundException(String.format("Group %s is not a classic group.",
groupId));
}
}
}
|
@Test
public void testStaticMemberRejoinWithUnknownMemberIdAndChangeOfProtocolWhileSelectProtocolUnchangedPersistenceFailure() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMembersJoinAndRebalance(
"group-id",
"leader-instance-id",
"follower-instance-id"
);
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup("group-id", false);
JoinGroupRequestProtocolCollection protocols = GroupMetadataManagerTestContext.toProtocols(group.selectProtocol());
JoinGroupRequestData request = new GroupMetadataManagerTestContext.JoinGroupRequestBuilder()
.withGroupId("group-id")
.withGroupInstanceId("follower-instance-id")
.withMemberId(UNKNOWN_MEMBER_ID)
.withProtocols(protocols)
.build();
GroupMetadataManagerTestContext.JoinResult followerJoinResult = context.sendClassicGroupJoin(
request,
true,
true
);
assertEquals(
Collections.singletonList(GroupCoordinatorRecordHelpers.newGroupMetadataRecord(group, group.groupAssignment(), MetadataVersion.latestTesting())),
followerJoinResult.records
);
// Simulate a failed write to the log.
followerJoinResult.appendFuture.completeExceptionally(Errors.MESSAGE_TOO_LARGE.exception());
assertTrue(followerJoinResult.joinFuture.isDone());
JoinGroupResponseData expectedResponse = new JoinGroupResponseData()
.setErrorCode(Errors.UNKNOWN_SERVER_ERROR.code())
.setGenerationId(rebalanceResult.generationId)
.setMemberId(followerJoinResult.joinFuture.get().memberId())
.setLeader(rebalanceResult.leaderId)
.setProtocolName("range")
.setProtocolType("consumer")
.setSkipAssignment(false)
.setMembers(Collections.emptyList());
checkJoinGroupResponse(
expectedResponse,
followerJoinResult.joinFuture.get(),
group,
STABLE,
Collections.emptySet()
);
// Join with old member id will not fail because the member id is not updated because of persistence failure
assertNotEquals(rebalanceResult.followerId, followerJoinResult.joinFuture.get().memberId());
followerJoinResult = context.sendClassicGroupJoin(request.setMemberId(rebalanceResult.followerId));
assertTrue(followerJoinResult.records.isEmpty());
// Join with leader and complete join phase.
GroupMetadataManagerTestContext.JoinResult leaderJoinResult = context.sendClassicGroupJoin(
request.setGroupInstanceId("leader-instance-id")
.setMemberId(rebalanceResult.leaderId)
);
assertTrue(leaderJoinResult.records.isEmpty());
assertTrue(leaderJoinResult.joinFuture.isDone());
assertTrue(followerJoinResult.joinFuture.isDone());
assertEquals(Errors.NONE.code(), leaderJoinResult.joinFuture.get().errorCode());
assertEquals(Errors.NONE.code(), followerJoinResult.joinFuture.get().errorCode());
// Sync with leader and receive assignment.
SyncGroupRequestData syncRequest = new GroupMetadataManagerTestContext.SyncGroupRequestBuilder()
.withGroupId("group-id")
.withGroupInstanceId("leader-instance-id")
.withMemberId(rebalanceResult.leaderId)
.withGenerationId(rebalanceResult.generationId + 1)
.build();
GroupMetadataManagerTestContext.SyncResult leaderSyncResult = context.sendClassicGroupSync(syncRequest);
// Simulate a successful write to the log. This will update the group with the new (empty) assignment.
leaderSyncResult.appendFuture.complete(null);
assertEquals(
Collections.singletonList(GroupCoordinatorRecordHelpers.newGroupMetadataRecord(group, group.groupAssignment(), MetadataVersion.latestTesting())),
leaderSyncResult.records
);
assertTrue(leaderSyncResult.syncFuture.isDone());
assertTrue(group.isInState(STABLE));
assertEquals(Errors.NONE.code(), leaderSyncResult.syncFuture.get().errorCode());
// Sync with old member id will also not fail as the member id is not updated due to persistence failure
GroupMetadataManagerTestContext.SyncResult oldMemberSyncResult = context.sendClassicGroupSync(
syncRequest
.setGroupInstanceId("follower-instance-id")
.setMemberId(rebalanceResult.followerId)
);
assertTrue(oldMemberSyncResult.records.isEmpty());
assertTrue(oldMemberSyncResult.syncFuture.isDone());
assertTrue(group.isInState(STABLE));
assertEquals(Errors.NONE.code(), oldMemberSyncResult.syncFuture.get().errorCode());
}
|
@VisibleForTesting
void validateRoleDuplicate(String name, String code, Long id) {
// 0. 超级管理员,不允许创建
if (RoleCodeEnum.isSuperAdmin(code)) {
throw exception(ROLE_ADMIN_CODE_ERROR, code);
}
// 1. 该 name 名字被其它角色所使用
RoleDO role = roleMapper.selectByName(name);
if (role != null && !role.getId().equals(id)) {
throw exception(ROLE_NAME_DUPLICATE, name);
}
// 2. 是否存在相同编码的角色
if (!StringUtils.hasText(code)) {
return;
}
// 该 code 编码被其它角色所使用
role = roleMapper.selectByCode(code);
if (role != null && !role.getId().equals(id)) {
throw exception(ROLE_CODE_DUPLICATE, code);
}
}
|
@Test
public void testValidateRoleDuplicate_codeDuplicate() {
// mock 数据
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setCode("code"));
roleMapper.insert(roleDO);
// 准备参数
String code = "code";
// 调用,并断言异常
assertServiceException(() -> roleService.validateRoleDuplicate(randomString(), code, null),
ROLE_CODE_DUPLICATE, code);
}
|
public Plan validateReservationSubmissionRequest(
ReservationSystem reservationSystem, ReservationSubmissionRequest request,
ReservationId reservationId) throws YarnException {
String message;
if (reservationId == null) {
message = "Reservation id cannot be null. Please try again specifying "
+ " a valid reservation id by creating a new reservation id.";
throw RPCUtil.getRemoteException(message);
}
// Check if it is a managed queue
String queue = request.getQueue();
Plan plan = getPlanFromQueue(reservationSystem, queue,
AuditConstants.SUBMIT_RESERVATION_REQUEST);
validateReservationDefinition(reservationId,
request.getReservationDefinition(), plan,
AuditConstants.SUBMIT_RESERVATION_REQUEST);
return plan;
}
|
@Test
public void testSubmitReservationInvalidPlan() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3);
when(rSystem.getPlan(PLAN_NAME)).thenReturn(null);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.endsWith(" is not managed by reservation system. Please try again with a valid reservable queue."));
LOG.info(message);
}
}
|
public Optional<ContentPackInstallation> findById(ObjectId id) {
final ContentPackInstallation installation = dbCollection.findOneById(id);
return Optional.ofNullable(installation);
}
|
@Test
@MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json")
public void findById() {
final ObjectId objectId = new ObjectId("5b4c935b4b900a0000000001");
final Optional<ContentPackInstallation> contentPacks = persistenceService.findById(objectId);
assertThat(contentPacks)
.isPresent()
.get()
.satisfies(contentPackInstallation -> assertThat(contentPackInstallation.id()).isEqualTo(objectId));
}
|
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> left,
final KTableHolder<K> right,
final StreamTableJoin<K> join,
final RuntimeBuildContext buildContext,
final JoinedFactory joinedFactory
) {
final Formats leftFormats = join.getInternalFormats();
final QueryContext queryContext = join.getProperties().getQueryContext();
final QueryContext.Stacker stacker = QueryContext.Stacker.of(queryContext);
final LogicalSchema leftSchema = left.getSchema();
final PhysicalSchema leftPhysicalSchema = PhysicalSchema.from(
leftSchema,
leftFormats.getKeyFeatures(),
leftFormats.getValueFeatures()
);
final Serde<GenericRow> leftSerde = buildContext.buildValueSerde(
leftFormats.getValueFormat(),
leftPhysicalSchema,
stacker.push(SERDE_CTX).getQueryContext()
);
final Serde<K> keySerde = left.getExecutionKeyFactory().buildKeySerde(
leftFormats.getKeyFormat(),
leftPhysicalSchema,
queryContext
);
final Joined<K, GenericRow, GenericRow> joined = joinedFactory.create(
keySerde,
leftSerde,
null,
StreamsUtil.buildOpName(queryContext)
);
final LogicalSchema rightSchema = right.getSchema();
final JoinParams joinParams = JoinParamsFactory
.create(join.getKeyColName(), leftSchema, rightSchema);
final KStream<K, GenericRow> result;
switch (join.getJoinType()) {
case LEFT:
result = left.getStream().leftJoin(right.getTable(), joinParams.getJoiner(), joined);
break;
case INNER:
result = left.getStream().join(right.getTable(), joinParams.getJoiner(), joined);
break;
default:
throw new IllegalStateException("invalid join type");
}
return left.withStream(result, joinParams.getSchema());
}
|
@Test
public void shouldBuildLeftSerdeCorrectly() {
// Given:
givenInnerJoin(SYNTH_KEY);
// When:
join.build(planBuilder, planInfo);
// Then:
final QueryContext leftCtx = QueryContext.Stacker.of(CTX).push("Left").getQueryContext();
verify(buildContext).buildValueSerde(FormatInfo.of(FormatFactory.JSON.name()), LEFT_PHYSICAL, leftCtx);
}
|
public void importCounters(String[] counterNames, String[] counterKinds, long[] counterDeltas) {
final int length = counterNames.length;
if (counterKinds.length != length || counterDeltas.length != length) {
throw new AssertionError("array lengths do not match");
}
for (int i = 0; i < length; ++i) {
final CounterName name = CounterName.named(counterPrefix + counterNames[i]);
final String kind = counterKinds[i];
final long delta = counterDeltas[i];
switch (kind) {
case "sum":
counterFactory.longSum(name).addValue(delta);
break;
case "max":
counterFactory.longMax(name).addValue(delta);
break;
case "min":
counterFactory.longMin(name).addValue(delta);
break;
default:
throw new IllegalArgumentException("unsupported counter kind: " + kind);
}
}
}
|
@Test
public void testSingleCounterMultipleDeltas() throws Exception {
String[] names = {"sum_counter", "sum_counter"};
String[] kinds = {"sum", "sum"};
long[] deltas = {122, 78};
counters.importCounters(names, kinds, deltas);
counterSet.extractUpdates(false, mockUpdateExtractor);
verify(mockUpdateExtractor)
.longSum(named("stageName-systemName-dataset-sum_counter"), false, 200L);
verifyNoMoreInteractions(mockUpdateExtractor);
}
|
@Override
public boolean test(Pickle pickle) {
if (expressions.isEmpty()) {
return true;
}
List<String> tags = pickle.getTags();
return expressions.stream()
.allMatch(expression -> expression.evaluate(tags));
}
|
@Test
void list_of_empty_tag_predicates_matches_pickle_with_any_tags() {
Pickle pickle = createPickleWithTags("@FOO");
TagPredicate predicate = createPredicate("", "");
assertTrue(predicate.test(pickle));
}
|
@Override
public void onMessage(Message<E> message) {
messageListener.onMessage(message);
}
|
@Test
public void onMessage() {
MessageListener<String> listener = createMessageListenerMock();
ReliableMessageListenerAdapter<String> adapter = new ReliableMessageListenerAdapter<>(listener);
Message<String> message = new Message<>("foo", "foo", System.currentTimeMillis(), null);
adapter.onMessage(message);
verify(listener).onMessage(message);
}
|
@Override
public Optional<String> resolveQueryFailure(QueryStats controlQueryStats, QueryException queryException, Optional<QueryObjectBundle> test)
{
if (!test.isPresent()) {
return Optional.empty();
}
// Decouple from com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OPEN_PARTITIONS
ErrorCodeSupplier errorCodeSupplier = new ErrorCodeSupplier() {
@Override
public ErrorCode toErrorCode()
{
int errorCodeMask = 0x0100_0000;
return new ErrorCode(21 + errorCodeMask, "HIVE_TOO_MANY_OPEN_PARTITIONS", ErrorType.USER_ERROR);
}
};
return mapMatchingPrestoException(queryException, TEST_MAIN, ImmutableSet.of(errorCodeSupplier),
e -> {
try {
ShowCreate showCreate = new ShowCreate(TABLE, test.get().getObjectName());
String showCreateResult = getOnlyElement(prestoAction.execute(showCreate, DESCRIBE, resultSet -> Optional.of(resultSet.getString(1))).getResults());
CreateTable createTable = (CreateTable) sqlParser.createStatement(showCreateResult, ParsingOptions.builder().setDecimalLiteralTreatment(AS_DOUBLE).build());
List<Property> bucketCountProperty = createTable.getProperties().stream()
.filter(property -> property.getName().getValue().equals("bucket_count"))
.collect(toImmutableList());
if (bucketCountProperty.size() != 1) {
return Optional.empty();
}
long bucketCount = ((LongLiteral) getOnlyElement(bucketCountProperty).getValue()).getValue();
int testClusterSize = this.testClusterSizeSupplier.get();
if (testClusterSize * maxBucketPerWriter < bucketCount) {
return Optional.of("Not enough workers on test cluster");
}
return Optional.empty();
}
catch (Throwable t) {
log.warn(t, "Exception when resolving HIVE_TOO_MANY_OPEN_PARTITIONS");
return Optional.empty();
}
});
}
|
@Test
public void testUnresolvedNonBucketed()
{
createTable.set(format("CREATE TABLE %s (x varchar, ds varchar) WITH (partitioned_by = ARRAY[\"ds\"])", TABLE_NAME));
getFailureResolver().resolveQueryFailure(CONTROL_QUERY_STATS, HIVE_TOO_MANY_OPEN_PARTITIONS_EXCEPTION, Optional.of(TEST_BUNDLE));
assertFalse(getFailureResolver().resolveQueryFailure(CONTROL_QUERY_STATS, HIVE_TOO_MANY_OPEN_PARTITIONS_EXCEPTION, Optional.of(TEST_BUNDLE)).isPresent());
}
|
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitMulti[] submitMulties = createSubmitMulti(exchange);
List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length);
for (SubmitMulti submitMulti : submitMulties) {
SubmitMultiResult result;
if (log.isDebugEnabled()) {
log.debug("Sending multiple short messages for exchange id '{}'...", exchange.getExchangeId());
}
try {
result = session.submitMultiple(
submitMulti.getServiceType(),
TypeOfNumber.valueOf(submitMulti.getSourceAddrTon()),
NumberingPlanIndicator.valueOf(submitMulti.getSourceAddrNpi()),
submitMulti.getSourceAddr(),
(Address[]) submitMulti.getDestAddresses(),
new ESMClass(submitMulti.getEsmClass()),
submitMulti.getProtocolId(),
submitMulti.getPriorityFlag(),
submitMulti.getScheduleDeliveryTime(),
submitMulti.getValidityPeriod(),
new RegisteredDelivery(submitMulti.getRegisteredDelivery()),
new ReplaceIfPresentFlag(submitMulti.getReplaceIfPresentFlag()),
DataCodings.newInstance(submitMulti.getDataCoding()),
submitMulti.getSmDefaultMsgId(),
submitMulti.getShortMessage(),
submitMulti.getOptionalParameters());
results.add(result);
} catch (Exception e) {
throw new SmppException(e);
}
}
if (log.isDebugEnabled()) {
log.debug("Sent multiple short messages for exchange id '{}' and received results '{}'", exchange.getExchangeId(),
results);
}
List<String> messageIDs = new ArrayList<>(results.size());
// {messageID : [{destAddr : address, error : errorCode}]}
Map<String, List<Map<String, Object>>> errors = new HashMap<>();
for (SubmitMultiResult result : results) {
UnsuccessDelivery[] deliveries = result.getUnsuccessDeliveries();
if (deliveries != null) {
List<Map<String, Object>> undelivered = new ArrayList<>();
for (UnsuccessDelivery delivery : deliveries) {
Map<String, Object> error = new HashMap<>();
error.put(SmppConstants.DEST_ADDR, delivery.getDestinationAddress().getAddress());
error.put(SmppConstants.ERROR, delivery.getErrorStatusCode());
undelivered.add(error);
}
if (!undelivered.isEmpty()) {
errors.put(result.getMessageId(), undelivered);
}
}
messageIDs.add(result.getMessageId());
}
Message message = ExchangeHelper.getResultMessage(exchange);
message.setHeader(SmppConstants.ID, messageIDs);
message.setHeader(SmppConstants.SENT_MESSAGE_COUNT, messageIDs.size());
if (!errors.isEmpty()) {
message.setHeader(SmppConstants.ERROR, errors);
}
}
|
@Test
public void executeWithOptionalParameter() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitMulti");
exchange.getIn().setHeader(SmppConstants.ID, "1");
exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_TON, TypeOfNumber.NATIONAL.value());
exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_NPI, NumberingPlanIndicator.NATIONAL.value());
exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR, "1818");
exchange.getIn().setHeader(SmppConstants.DEST_ADDR_TON, TypeOfNumber.INTERNATIONAL.value());
exchange.getIn().setHeader(SmppConstants.DEST_ADDR_NPI, NumberingPlanIndicator.INTERNET.value());
exchange.getIn().setHeader(SmppConstants.DEST_ADDR, Arrays.asList("1919"));
exchange.getIn().setHeader(SmppConstants.SCHEDULE_DELIVERY_TIME, new Date(1111111));
exchange.getIn().setHeader(SmppConstants.VALIDITY_PERIOD, new Date(2222222));
exchange.getIn().setHeader(SmppConstants.PROTOCOL_ID, (byte) 1);
exchange.getIn().setHeader(SmppConstants.PRIORITY_FLAG, (byte) 2);
exchange.getIn().setHeader(SmppConstants.REGISTERED_DELIVERY,
new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE).value());
exchange.getIn().setHeader(SmppConstants.REPLACE_IF_PRESENT_FLAG, ReplaceIfPresentFlag.REPLACE.value());
Map<String, String> optionalParameters = new LinkedHashMap<>();
optionalParameters.put("SOURCE_SUBADDRESS", "1292");
optionalParameters.put("ADDITIONAL_STATUS_INFO_TEXT", "urgent");
optionalParameters.put("DEST_ADDR_SUBUNIT", "4");
optionalParameters.put("DEST_TELEMATICS_ID", "2");
optionalParameters.put("QOS_TIME_TO_LIVE", "3600000");
optionalParameters.put("ALERT_ON_MESSAGE_DELIVERY", null);
exchange.getIn().setHeader(SmppConstants.OPTIONAL_PARAMETERS, optionalParameters);
exchange.getIn().setBody("short message body");
when(session.submitMultiple(eq("CMT"), eq(TypeOfNumber.NATIONAL), eq(NumberingPlanIndicator.NATIONAL), eq("1818"),
eq(new Address[] { new Address(TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.INTERNET, "1919") }),
eq(new ESMClass()), eq((byte) 1), eq((byte) 2), eq("-300101001831100+"), eq("-300101003702200+"),
eq(new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE)),
eq(ReplaceIfPresentFlag.REPLACE), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0),
eq("short message body".getBytes()),
eq(new OptionalParameter.Source_subaddress("1292".getBytes())),
eq(new OptionalParameter.Additional_status_info_text("urgent".getBytes())),
eq(new OptionalParameter.Dest_addr_subunit((byte) 4)),
eq(new OptionalParameter.Dest_telematics_id((short) 2)),
eq(new OptionalParameter.Qos_time_to_live(3600000)),
eq(new OptionalParameter.Alert_on_message_delivery("O".getBytes()))))
.thenReturn(new SubmitMultiResult("1", null, null));
command.execute(exchange);
assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID));
assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT));
assertNull(exchange.getMessage().getHeader(SmppConstants.ERROR));
}
|
@Override
String getMethodName(Invoker invoker, Invocation invocation, String prefix) {
return DubboUtils.getMethodResourceName(invoker, invocation, prefix);
}
|
@Test
public void testMethodFlowControlAsync() {
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
initFlowRule(consumerFilter.getMethodName(invoker, invocation, null));
invokeDubboRpc(false, invoker, invocation);
invokeDubboRpc(false, invoker, invocation);
Invocation invocation2 = DubboTestUtil.getDefaultMockInvocationTwo();
Result result2 = invokeDubboRpc(false, invoker, invocation2);
verifyInvocationStructureForCallFinish(invoker, invocation2);
assertEquals("normal", result2.getValue());
// the method of invocation should be blocked
Result fallback = invokeDubboRpc(false, invoker, invocation);
assertEquals("fallback", fallback.getValue());
verifyInvocationStructureForCallFinish(invoker, invocation);
}
|
@Override
@SuppressWarnings("unchecked")
public <T> List<List<T>> toLists(DataTable dataTable, Type itemType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(itemType, "itemType may not be null");
if (dataTable.isEmpty()) {
return emptyList();
}
List<String> problems = new ArrayList<>();
DataTableType tableType = registry.lookupCellTypeByType(itemType);
if (tableType != null) {
return unmodifiableList((List<List<T>>) tableType.transform(dataTable.cells()));
} else {
problems.add(problemNoTableCellTransformer(itemType));
}
tableType = registry.getDefaultTableCellTransformer(itemType);
if (tableType != null) {
return unmodifiableList((List<List<T>>) tableType.transform(dataTable.cells()));
} else {
problems.add(problemNoDefaultTableCellTransformer(itemType));
}
throw listsNoConverterDefined(itemType, problems);
}
|
@Test
void to_lists_of_unknown_type__throws_exception() {
DataTable table = parse("",
" | firstName | lastName | birthDate |",
" | Annie M. G. | Schmidt | 1911-03-20 |",
" | Roald | Dahl | 1916-09-13 |",
" | Astrid | Lindgren | 1907-11-14 |");
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class, () -> converter.toLists(table, Author.class));
assertThat(exception.getMessage(), is("" +
"Can't convert DataTable to List<List<io.cucumber.datatable.DataTableTypeRegistryTableConverterTest$Author>>.\n"
+
"Please review these problems:\n" +
"\n" +
" - There was no table cell transformer registered for io.cucumber.datatable.DataTableTypeRegistryTableConverterTest$Author.\n"
+
" Please consider registering a table cell transformer.\n" +
"\n" +
" - There was no default table cell transformer registered to transform io.cucumber.datatable.DataTableTypeRegistryTableConverterTest$Author.\n"
+
" Please consider registering a default table cell transformer.\n" +
"\n" +
"Note: Usually solving one is enough"));
}
|
public DataSchema getResultDataSchema() {
return _resultDataSchema;
}
|
@Test
public void testLiteralTypeHandling() {
QueryContext queryContext = QueryContextConverterUtils
.getQueryContext("SELECT COUNT(*), 1 FROM testTable GROUP BY d1");
DataSchema dataSchema =
new DataSchema(new String[]{"d1", "count(*)"}, new ColumnDataType[]{ColumnDataType.INT, ColumnDataType.LONG});
PostAggregationHandler postAggregationHandler = new PostAggregationHandler(queryContext, dataSchema);
assertEquals(postAggregationHandler.getResultDataSchema().getColumnDataTypes(),
new ColumnDataType[]{ColumnDataType.LONG, ColumnDataType.INT});
queryContext = QueryContextConverterUtils
.getQueryContext("SELECT COUNT(*), '1' FROM testTable GROUP BY d1");
postAggregationHandler = new PostAggregationHandler(queryContext, dataSchema);
assertEquals(postAggregationHandler.getResultDataSchema().getColumnDataTypes(),
new ColumnDataType[]{ColumnDataType.LONG, ColumnDataType.STRING});
}
|
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException {
return buildFunction(functionDefinition, true);
}
|
@Test
public void testBuildFunctionTransaction() throws Exception {
AbiDefinition functionDefinition =
new AbiDefinition(
false,
Arrays.asList(new NamedType("param", "uint8")),
"functionName",
Collections.emptyList(),
"type",
false);
MethodSpec methodSpec = solidityFunctionWrapper.buildFunction(functionDefinition);
String expected =
"public org.web3j.protocol.core.RemoteFunctionCall<org.web3j.protocol.core.methods.response.TransactionReceipt> functionName(\n"
+ " java.math.BigInteger param) {\n"
+ " final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n"
+ " FUNC_FUNCTIONNAME, \n"
+ " java.util.Arrays.<org.web3j.abi.datatypes.Type>asList(new org.web3j.abi.datatypes.generated.Uint8(param)), \n"
+ " java.util.Collections.<org.web3j.abi.TypeReference<?>>emptyList());\n"
+ " return executeRemoteCallTransaction(function);\n"
+ "}\n";
assertEquals(methodSpec.toString(), (expected));
}
|
@Override
public KeyVersion createKey(final String name, final byte[] material,
final Options options) throws IOException {
return doOp(new ProviderCallable<KeyVersion>() {
@Override
public KeyVersion call(KMSClientProvider provider) throws IOException {
return provider.createKey(name, material, options);
}
}, nextIdx(), false);
}
|
@Test
public void testLoadBalancingWithFailure() throws Exception {
Configuration conf = new Configuration();
KMSClientProvider p1 = mock(KMSClientProvider.class);
when(p1.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p1", "v1", new byte[0]));
when(p1.getKMSUrl()).thenReturn("p1");
// This should not be retried
KMSClientProvider p2 = mock(KMSClientProvider.class);
when(p2.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new NoSuchAlgorithmException("p2"));
when(p2.getKMSUrl()).thenReturn("p2");
KMSClientProvider p3 = mock(KMSClientProvider.class);
when(p3.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p3", "v3", new byte[0]));
when(p3.getKMSUrl()).thenReturn("p3");
// This should be retried
KMSClientProvider p4 = mock(KMSClientProvider.class);
when(p4.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new IOException("p4"));
when(p4.getKMSUrl()).thenReturn("p4");
KeyProvider kp = new LoadBalancingKMSClientProvider(
new KMSClientProvider[] { p1, p2, p3, p4 }, 0, conf);
assertEquals("p1", kp.createKey("test4", new Options(conf)).getName());
// Exceptions other than IOExceptions will not be retried
try {
kp.createKey("test1", new Options(conf)).getName();
fail("Should fail since its not an IOException");
} catch (Exception e) {
assertTrue(e instanceof NoSuchAlgorithmException);
}
assertEquals("p3", kp.createKey("test2", new Options(conf)).getName());
// IOException will trigger retry in next provider
assertEquals("p1", kp.createKey("test3", new Options(conf)).getName());
}
|
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
}
|
@Test
public void when_addNonexistentResourceWithPath_then_throwsException() {
// Given
String path = Paths.get("/i/do/not/exist").toString();
// Then
expectedException.expect(JetException.class);
expectedException.expectMessage("Not an existing, readable file: " + path);
// When
config.addClasspathResource(path);
}
|
private void printQueries(
final List<RunningQuery> queries,
final String type,
final String operation
) {
if (!queries.isEmpty()) {
writer().println(String.format(
"%n%-20s%n%-20s",
"Queries that " + operation + " from this " + type,
"-----------------------------------"
));
for (final RunningQuery writeQuery : queries) {
writer().println(writeQuery.getId()
+ " (" + writeQuery.getState().orElse("N/A")
+ ") : " + writeQuery.getQuerySingleLine());
}
writer().println("\nFor query topology and execution plan please run: EXPLAIN <QueryId>");
}
}
|
@Test
public void testPrintQueries() {
// Given:
final List<RunningQuery> queries = new ArrayList<>();
queries.add(
new RunningQuery(
"select * from t1 emit changes", Collections.singleton("Test"), Collections.singleton("Test topic"), new QueryId("0"), queryStatusCount, KsqlConstants.KsqlQueryType.PUSH));
final KsqlEntityList entityList = new KsqlEntityList(ImmutableList.of(
new Queries("e", queries)
));
// When:
console.printKsqlEntityList(entityList);
// Then:
final String output = terminal.getOutputString();
Approvals.verify(output, approvalOptions);
}
|
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
}
|
@Test
public void testOldStyleResourcesSeparatedBySpacesInvalidUppercaseUnits()
throws Exception {
String value = "2 vcores 5120 MB 555 GB";
expectUnparsableResource(value);
parseResourceConfigValue(value);
}
|
@VisibleForTesting
List<LogFile> applyBundleSizeLogFileLimit(List<LogFile> allLogs) {
final ImmutableList.Builder<LogFile> truncatedLogFileList = ImmutableList.builder();
// Always collect the in-memory log and the newest on-disk log file
// Keep collecting until we pass LOG_COLLECTION_SIZE_LIMIT
final AtomicBoolean oneFileAdded = new AtomicBoolean(false);
final AtomicLong collectedSize = new AtomicLong();
allLogs.stream().sorted(Comparator.comparing(LogFile::lastModified).reversed()).forEach(logFile -> {
if (logFile.id().equals(IN_MEMORY_LOGFILE_ID)) {
truncatedLogFileList.add(logFile);
} else if (!oneFileAdded.get() || collectedSize.get() < LOG_COLLECTION_SIZE_LIMIT) {
truncatedLogFileList.add(logFile);
oneFileAdded.set(true);
collectedSize.addAndGet(logFile.size());
}
});
return truncatedLogFileList.build();
}
|
@Test
public void testLogSizeLimiterWithSpaceForOneZippedFile() {
final List<LogFile> fullLoglist = List.of(
new LogFile("memory", "server.mem.log", 500, Instant.now()),
new LogFile("0", "server.log", 50 * 1024 * 1024, Instant.now()),
new LogFile("1", "server.log.1.gz", 20 * 1024 * 1024, Instant.now().minus(1, ChronoUnit.DAYS)),
new LogFile("2", "server.log.2.gz", 500, Instant.now().minus(2, ChronoUnit.DAYS))
);
final List<LogFile> shrinkedList = supportBundleService.applyBundleSizeLogFileLimit(fullLoglist);
assertThat(shrinkedList).hasSize(3);
assertThat(shrinkedList).extracting(LogFile::id).contains("memory", "0", "1");
}
|
@Override
public int hashCode() {
StringBuilder stringBuilder = new StringBuilder();
for (Entry<String, Object> entry : getAllLocalProperties().entrySet()) {
stringBuilder.append(entry.getKey()).append(entry.getValue());
}
return Objects.hashCode(poolClassName, stringBuilder.toString());
}
|
@Test
void assertDifferentHashCodeWithDifferentProperties() {
assertThat(new DataSourcePoolProperties(MockedDataSource.class.getName(), createUserProperties("foo")).hashCode(),
not(new DataSourcePoolProperties(MockedDataSource.class.getName(), createUserProperties("bar")).hashCode()));
}
|
public Map<String, List<String>> parameters() {
if (params == null) {
params = decodeParams(uri, pathEndIdx(), charset, maxParams, semicolonIsNormalChar);
}
return params;
}
|
@Test
public void testExcludeFragment() {
// a 'fragment' after '#' should be cuted (see RFC 3986)
assertEquals("a", new QueryStringDecoder("?a#anchor").parameters().keySet().iterator().next());
assertEquals("b", new QueryStringDecoder("?a=b#anchor").parameters().get("a").get(0));
assertTrue(new QueryStringDecoder("?#").parameters().isEmpty());
assertTrue(new QueryStringDecoder("?#anchor").parameters().isEmpty());
assertTrue(new QueryStringDecoder("#?a=b#anchor").parameters().isEmpty());
assertTrue(new QueryStringDecoder("?#a=b#anchor").parameters().isEmpty());
}
|
public synchronized void setLevel(Level newLevel) {
if (level == newLevel) {
// nothing to do;
return;
}
if (newLevel == null && isRootLogger()) {
throw new IllegalArgumentException(
"The level of the root logger cannot be set to null");
}
level = newLevel;
if (newLevel == null) {
effectiveLevelInt = parent.effectiveLevelInt;
newLevel = parent.getEffectiveLevel();
} else {
effectiveLevelInt = newLevel.levelInt;
}
if (childrenList != null) {
int len = childrenList.size();
for (int i = 0; i < len; i++) {
Logger child = (Logger) childrenList.get(i);
// tell child to handle parent levelInt change
child.handleParentLevelChange(effectiveLevelInt);
}
}
// inform listeners
loggerContext.fireOnLevelChange(this, newLevel);
}
|
@Test
public void testEnabled_All() throws Exception {
root.setLevel(Level.ALL);
checkLevelThreshold(loggerTest, Level.ALL);
}
|
public void setAgility(int wizard, int amount) {
wizards[wizard].setAgility(amount);
}
|
@Test
void testSetAgility() {
var wizardNumber = 0;
var bytecode = new int[5];
bytecode[0] = LITERAL.getIntValue();
bytecode[1] = wizardNumber;
bytecode[2] = LITERAL.getIntValue();
bytecode[3] = 50; // agility amount
bytecode[4] = SET_AGILITY.getIntValue();
var vm = new VirtualMachine();
vm.execute(bytecode);
assertEquals(50, vm.getWizards()[wizardNumber].getAgility());
}
|
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credentials);
LOGGER.fine("AWS ECS DescribeTasks found the following addresses: %s", taskAddresses);
}
if (!taskAddresses.isEmpty()) {
return awsEc2Api.describeNetworkInterfaces(taskAddresses, credentials);
} else if (DiscoveryMode.Client == awsConfig.getDiscoveryMode() && !awsConfig.anyOfEcsPropertiesConfigured()) {
LOGGER.fine("No tasks found in ECS cluster: '%s'. Trying AWS EC2 Discovery.", cluster);
return awsEc2Api.describeInstances(credentials);
}
return emptyMap();
}
|
@Test
public void getAddressesForEC2Client() {
// given
AwsConfig awsConfig = AwsConfig.builder().setDiscoveryMode(DiscoveryMode.Client).build();
awsEcsClient = new AwsEcsClient(CLUSTER, awsConfig, awsEcsApi, awsEc2Api, awsMetadataApi, awsCredentialsProvider);
Map<String, String> expectedResult = singletonMap("123.12.1.0", "1.4.6.2");
given(awsEcsApi.listTaskPrivateAddresses(CLUSTER, CREDENTIALS)).willReturn(emptyList());
given(awsEc2Api.describeInstances(CREDENTIALS)).willReturn(expectedResult);
// when
Map<String, String> result = awsEcsClient.getAddresses();
// then
assertEquals(expectedResult, result);
}
|
@Override
public Subscriber<Exchange> subscriber(String uri) {
try {
String uuid = context.getUuidGenerator().generateUuid();
RouteBuilder.addRoutes(context, rb -> rb.from("reactive-streams:" + uuid).to(uri));
return streamSubscriber(uuid);
} catch (Exception e) {
throw new IllegalStateException("Unable to create source reactive stream towards direct URI: " + uri, e);
}
}
|
@Test
public void testSubscriber() throws Exception {
context.start();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:reactor").to("mock:result");
}
});
Flowable.just(1, 2, 3).subscribe(crs.subscriber("direct:reactor", Integer.class));
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(3);
mock.assertIsSatisfied();
int idx = 1;
for (Exchange ex : mock.getExchanges()) {
assertEquals(Integer.valueOf(idx++), ex.getIn().getBody(Integer.class));
}
}
|
public boolean isEmpty() {
return map.isEmpty();
}
|
@Test
public void shouldReportEmpty() {
assertThat(map.isEmpty()).isTrue();
}
|
public static Object toBeamObject(Value value, boolean verifyValues) {
return toBeamObject(value, toBeamType(value.getType()), verifyValues);
}
|
@Test
public void testZetaSqlValueToJavaObject() {
assertEquals(
ZetaSqlBeamTranslationUtils.toBeamObject(TEST_VALUE, TEST_FIELD_TYPE, true), TEST_ROW);
}
|
public static DynamicVoter parse(String input) {
input = input.trim();
int atIndex = input.indexOf("@");
if (atIndex < 0) {
throw new IllegalArgumentException("No @ found in dynamic voter string.");
}
if (atIndex == 0) {
throw new IllegalArgumentException("Invalid @ at beginning of dynamic voter string.");
}
String idString = input.substring(0, atIndex);
int nodeId;
try {
nodeId = Integer.parseInt(idString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Failed to parse node id in dynamic voter string.", e);
}
if (nodeId < 0) {
throw new IllegalArgumentException("Invalid negative node id " + nodeId +
" in dynamic voter string.");
}
input = input.substring(atIndex + 1);
if (input.isEmpty()) {
throw new IllegalArgumentException("No hostname found after node id.");
}
String host;
if (input.startsWith("[")) {
int endBracketIndex = input.indexOf("]");
if (endBracketIndex < 0) {
throw new IllegalArgumentException("Hostname began with left bracket, but no right " +
"bracket was found.");
}
host = input.substring(1, endBracketIndex);
input = input.substring(endBracketIndex + 1);
} else {
int endColonIndex = input.indexOf(":");
if (endColonIndex < 0) {
throw new IllegalArgumentException("No colon following hostname could be found.");
}
host = input.substring(0, endColonIndex);
input = input.substring(endColonIndex);
}
if (!input.startsWith(":")) {
throw new IllegalArgumentException("Port section must start with a colon.");
}
input = input.substring(1);
int endColonIndex = input.indexOf(":");
if (endColonIndex < 0) {
throw new IllegalArgumentException("No colon following port could be found.");
}
String portString = input.substring(0, endColonIndex);
int port;
try {
port = Integer.parseInt(portString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Failed to parse port in dynamic voter string.", e);
}
if (port < 0 || port > 65535) {
throw new IllegalArgumentException("Invalid port " + port + " in dynamic voter string.");
}
String directoryIdString = input.substring(endColonIndex + 1);
Uuid directoryId;
try {
directoryId = Uuid.fromString(directoryIdString);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Failed to parse directory ID in dynamic voter string.", e);
}
return new DynamicVoter(directoryId, nodeId, host, port);
}
|
@Test
public void testFailedToParseDirectoryId2() {
assertEquals("Failed to parse directory ID in dynamic voter string.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("5@[2001:4860:4860::8888]:8020:")).
getMessage());
}
|
@Override
protected Mono<Boolean> doMatcher(final ServerWebExchange exchange, final WebFilterChain chain) {
String path = exchange.getRequest().getURI().getRawPath();
return Mono.just(paths.contains(path));
}
|
@Test
public void testDoMatcher() {
ServerWebExchange webExchange =
MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost:8080/fallback/hystrix"));
Mono<Boolean> filter = fallbackFilter.doMatcher(webExchange, webFilterChain);
StepVerifier.create(filter).expectNext(Boolean.TRUE).verifyComplete();
}
|
public int seriesCount() {
return seriesSet.size();
}
|
@Test
public void testSeriesCount() {
cm = new ChartModel(FOO, BAR, ZOO);
assertEquals("Wrong series count", 3, cm.seriesCount());
}
|
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
if(containerService.isContainer(file)) {
final Storage.Buckets.Get request = session.getClient().buckets().get(containerService.getContainer(file).getName());
if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) {
request.setUserProject(session.getHost().getCredentials().getUsername());
}
return this.toAttributes(request.execute());
}
else {
final Storage.Objects.Get get = session.getClient().objects().get(
containerService.getContainer(file).getName(), containerService.getKey(file));
if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) {
get.setUserProject(session.getHost().getCredentials().getUsername());
}
final VersioningConfiguration versioning = null != session.getFeature(Versioning.class) ? session.getFeature(Versioning.class).getConfiguration(
containerService.getContainer(file)
) : VersioningConfiguration.empty();
if(versioning.isEnabled()) {
if(StringUtils.isNotBlank(file.attributes().getVersionId())) {
get.setGeneration(Long.parseLong(file.attributes().getVersionId()));
}
}
final PathAttributes attributes;
try {
attributes = this.toAttributes(get.execute());
}
catch(IOException e) {
if(file.isDirectory()) {
final BackgroundException failure = new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, file);
if(failure instanceof NotfoundException) {
if(log.isDebugEnabled()) {
log.debug(String.format("Search for common prefix %s", file));
}
// File may be marked as placeholder but no placeholder file exists. Check for common prefix returned.
try {
new GoogleStorageObjectListService(session).list(file, new CancellingListProgressListener(), String.valueOf(Path.DELIMITER), 1, VersioningConfiguration.empty());
}
catch(ListCanceledException l) {
// Found common prefix
return PathAttributes.EMPTY;
}
catch(NotfoundException n) {
throw e;
}
// Found common prefix
return PathAttributes.EMPTY;
}
}
throw e;
}
if(versioning.isEnabled()) {
// Determine if latest version
try {
// Duplicate if not latest version
final Storage.Objects.Get request = session.getClient().objects().get(
containerService.getContainer(file).getName(), containerService.getKey(file));
if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) {
request.setUserProject(session.getHost().getCredentials().getUsername());
}
final String latest = this.toAttributes(request.execute()).getVersionId();
if(null != latest) {
attributes.setDuplicate(!latest.equals(attributes.getVersionId()));
}
}
catch(IOException e) {
// Noncurrent versions only appear in requests that explicitly call for object versions to be included
final BackgroundException failure = new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, file);
if(failure instanceof NotfoundException) {
// The latest version is a delete marker
attributes.setDuplicate(true);
}
else {
throw failure;
}
}
}
return attributes;
}
}
catch(IOException e) {
throw new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, file);
}
}
|
@Test(expected = NotfoundException.class)
public void testDeletedWithMarker() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new GoogleStorageTouchFeature(session).touch(new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
assertNotNull(test.attributes().getVersionId());
assertNotEquals(PathAttributes.EMPTY, new GoogleStorageAttributesFinderFeature(session).find(test));
// Add delete marker
new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(new Path(test).withAttributes(PathAttributes.EMPTY)), new DisabledPasswordCallback(), new Delete.DisabledCallback());
assertTrue(new GoogleStorageAttributesFinderFeature(session).find(test).isDuplicate());
try {
// Noncurrent versions only appear in requests that explicitly call for object versions to be included
new GoogleStorageAttributesFinderFeature(session).find(new Path(test).withAttributes(PathAttributes.EMPTY));
fail();
}
catch(NotfoundException e) {
throw e;
}
}
|
protected Bootstrap bootstrap() {
return bootstrap;
}
|
@Test
public void testBootstrap() {
final SimpleChannelPool pool = new SimpleChannelPool(new Bootstrap(), new CountingChannelPoolHandler());
try {
// Checking for the actual bootstrap object doesn't make sense here, since the pool uses a copy with a
// modified channel handler.
assertNotNull(pool.bootstrap());
} finally {
pool.close();
}
}
|
@Override
public ConsumerGroupMetadata groupMetadata() {
acquireAndEnsureOpen();
try {
maybeThrowInvalidGroupIdException();
return groupMetadata.get().get();
} finally {
release();
}
}
|
@Test
public void testGroupMetadataAfterCreationWithGroupIdIsNotNullAndGroupInstanceIdSet() {
final String groupId = "consumerGroupA";
final String groupInstanceId = "groupInstanceId1";
final Properties props = requiredConsumerConfigAndGroupId(groupId);
props.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG, groupInstanceId);
final ConsumerConfig config = new ConsumerConfig(props);
consumer = newConsumer(config);
final ConsumerGroupMetadata groupMetadata = consumer.groupMetadata();
assertEquals(groupId, groupMetadata.groupId());
assertEquals(Optional.of(groupInstanceId), groupMetadata.groupInstanceId());
assertEquals(JoinGroupRequest.UNKNOWN_GENERATION_ID, groupMetadata.generationId());
assertEquals(JoinGroupRequest.UNKNOWN_MEMBER_ID, groupMetadata.memberId());
}
|
public static String convertFromActiveMQDestination(Object value) {
return convertFromActiveMQDestination(value, false);
}
|
@Test
public void testConvertFromActiveMQDestination() {
String result = StringToListOfActiveMQDestinationConverter.convertFromActiveMQDestination(null);
assertNull(result);
}
|
public void detectAndResolve() {
createTopologyGraph();
}
|
@TestTemplate
void testDetectAndResolve() {
// P = InputProperty.DamBehavior.PIPELINED, E = InputProperty.DamBehavior.END_INPUT
// P100 = PIPELINED + priority 100
//
// 0 --------(P0)----> 1 --(P0)-----------> 7
// \ \-(P0)-> 2 -(P0)--/
// \-------(P0)----> 3 --(P1)-----------/
// \------(P0)----> 4 --(P10)---------/
// \ / /
// \ 8 -(P0)-< /
// \ \ /
// \--(E0)----> 5 --(P10)-----/
// 6 ---------(P100)----------------/
TestingBatchExecNode[] nodes = new TestingBatchExecNode[9];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = new TestingBatchExecNode("TestingBatchExecNode" + i);
}
nodes[1].addInput(nodes[0], InputProperty.builder().priority(0).build());
nodes[2].addInput(nodes[1], InputProperty.builder().priority(0).build());
nodes[3].addInput(nodes[0], InputProperty.builder().priority(0).build());
nodes[4].addInput(nodes[8], InputProperty.builder().priority(0).build());
nodes[4].addInput(nodes[0], InputProperty.builder().priority(0).build());
nodes[5].addInput(nodes[8], InputProperty.builder().priority(0).build());
nodes[5].addInput(
nodes[0],
InputProperty.builder()
.damBehavior(InputProperty.DamBehavior.END_INPUT)
.priority(0)
.build());
nodes[7].addInput(nodes[1], InputProperty.builder().priority(0).build());
nodes[7].addInput(nodes[2], InputProperty.builder().priority(0).build());
nodes[7].addInput(nodes[3], InputProperty.builder().priority(1).build());
nodes[7].addInput(nodes[4], InputProperty.builder().priority(10).build());
nodes[7].addInput(nodes[5], InputProperty.builder().priority(10).build());
nodes[7].addInput(nodes[6], InputProperty.builder().priority(100).build());
Configuration configuration = new Configuration();
BatchShuffleMode batchShuffleMode = batchShuffleModeAndStreamExchangeMode.f0;
StreamExchangeMode streamExchangeMode = batchShuffleModeAndStreamExchangeMode.f1;
configuration.set(ExecutionOptions.BATCH_SHUFFLE_MODE, batchShuffleMode);
InputPriorityConflictResolver resolver =
new InputPriorityConflictResolver(
Collections.singletonList(nodes[7]),
InputProperty.DamBehavior.END_INPUT,
streamExchangeMode,
configuration);
resolver.detectAndResolve();
assertThat(nodes[7].getInputNodes().get(0)).isEqualTo(nodes[1]);
assertThat(nodes[7].getInputNodes().get(1)).isEqualTo(nodes[2]);
assertThat(nodes[7].getInputNodes().get(2)).isInstanceOf(BatchExecExchange.class);
assertThat(((BatchExecExchange) nodes[7].getInputNodes().get(2)).getRequiredExchangeMode())
.isEqualTo(Optional.of(streamExchangeMode));
assertThat(nodes[7].getInputNodes().get(2).getInputEdges().get(0).getSource())
.isEqualTo(nodes[3]);
assertThat(nodes[7].getInputNodes().get(3)).isInstanceOf(BatchExecExchange.class);
assertThat(((BatchExecExchange) nodes[7].getInputNodes().get(3)).getRequiredExchangeMode())
.isEqualTo(Optional.of(streamExchangeMode));
assertThat(nodes[7].getInputNodes().get(3).getInputEdges().get(0).getSource())
.isEqualTo(nodes[4]);
assertThat(nodes[7].getInputNodes().get(4)).isEqualTo(nodes[5]);
assertThat(nodes[7].getInputNodes().get(5)).isEqualTo(nodes[6]);
}
|
@Override
public void reset() {
resetCount++;
super.reset();
initEvaluatorMap();
initCollisionMaps();
root.recursiveReset();
resetTurboFilterList();
cancelScheduledTasks();
fireOnReset();
resetListenersExceptResetResistant();
resetStatusListeners();
}
|
@Test
public void resetTest() {
Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
Logger a = lc.getLogger("a");
Logger ab = lc.getLogger("a.b");
ab.setLevel(Level.WARN);
root.setLevel(Level.INFO);
lc.reset();
assertEquals(Level.DEBUG, root.getEffectiveLevel());
assertTrue(root.isDebugEnabled());
assertEquals(Level.DEBUG, a.getEffectiveLevel());
assertEquals(Level.DEBUG, ab.getEffectiveLevel());
assertEquals(Level.DEBUG, root.getLevel());
assertNull(a.getLevel());
assertNull(ab.getLevel());
}
|
@Override
public Expression getExpression(String tableName, Alias tableAlias) {
// 只有有登陆用户的情况下,才进行数据权限的处理
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
if (loginUser == null) {
return null;
}
// 只有管理员类型的用户,才进行数据权限的处理
if (ObjectUtil.notEqual(loginUser.getUserType(), UserTypeEnum.ADMIN.getValue())) {
return null;
}
// 获得数据权限
DeptDataPermissionRespDTO deptDataPermission = loginUser.getContext(CONTEXT_KEY, DeptDataPermissionRespDTO.class);
// 从上下文中拿不到,则调用逻辑进行获取
if (deptDataPermission == null) {
deptDataPermission = permissionApi.getDeptDataPermission(loginUser.getId());
if (deptDataPermission == null) {
log.error("[getExpression][LoginUser({}) 获取数据权限为 null]", JsonUtils.toJsonString(loginUser));
throw new NullPointerException(String.format("LoginUser(%d) Table(%s/%s) 未返回数据权限",
loginUser.getId(), tableName, tableAlias.getName()));
}
// 添加到上下文中,避免重复计算
loginUser.setContext(CONTEXT_KEY, deptDataPermission);
}
// 情况一,如果是 ALL 可查看全部,则无需拼接条件
if (deptDataPermission.getAll()) {
return null;
}
// 情况二,即不能查看部门,又不能查看自己,则说明 100% 无权限
if (CollUtil.isEmpty(deptDataPermission.getDeptIds())
&& Boolean.FALSE.equals(deptDataPermission.getSelf())) {
return new EqualsTo(null, null); // WHERE null = null,可以保证返回的数据为空
}
// 情况三,拼接 Dept 和 User 的条件,最后组合
Expression deptExpression = buildDeptExpression(tableName,tableAlias, deptDataPermission.getDeptIds());
Expression userExpression = buildUserExpression(tableName, tableAlias, deptDataPermission.getSelf(), loginUser.getId());
if (deptExpression == null && userExpression == null) {
// TODO 芋艿:获得不到条件的时候,暂时不抛出异常,而是不返回数据
log.warn("[getExpression][LoginUser({}) Table({}/{}) DeptDataPermission({}) 构建的条件为空]",
JsonUtils.toJsonString(loginUser), tableName, tableAlias, JsonUtils.toJsonString(deptDataPermission));
// throw new NullPointerException(String.format("LoginUser(%d) Table(%s/%s) 构建的条件为空",
// loginUser.getId(), tableName, tableAlias.getName()));
return EXPRESSION_NULL;
}
if (deptExpression == null) {
return userExpression;
}
if (userExpression == null) {
return deptExpression;
}
// 目前,如果有指定部门 + 可查看自己,采用 OR 条件。即,WHERE (dept_id IN ? OR user_id = ?)
return new Parenthesis(new OrExpression(deptExpression, userExpression));
}
|
@Test // 无数据权限时
public void testGetExpression_noDeptDataPermission() {
try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock
= mockStatic(SecurityFrameworkUtils.class)) {
// 准备参数
String tableName = "t_user";
Alias tableAlias = new Alias("u");
// mock 方法
LoginUser loginUser = randomPojo(LoginUser.class, o -> o.setId(1L)
.setUserType(UserTypeEnum.ADMIN.getValue()));
securityFrameworkUtilsMock.when(SecurityFrameworkUtils::getLoginUser).thenReturn(loginUser);
// mock 方法(permissionApi 返回 null)
when(permissionApi.getDeptDataPermission(eq(loginUser.getId()))).thenReturn(null);
// 调用
NullPointerException exception = assertThrows(NullPointerException.class,
() -> rule.getExpression(tableName, tableAlias));
// 断言
assertEquals("LoginUser(1) Table(t_user/u) 未返回数据权限", exception.getMessage());
}
}
|
public AmazonInfo build() {
return new AmazonInfo(Name.Amazon.name(), metadata);
}
|
@Test
public void payloadWithNameBeforeMetadata() throws IOException {
String json = "{"
+ " \"@class\": \"com.netflix.appinfo.AmazonInfo\","
+ " \"name\": \"Amazon\","
+ " \"metadata\": {"
+ " \"instance-id\": \"i-12345\""
+ " }"
+ "}";
AmazonInfo info = newMapper().readValue(json, AmazonInfo.class);
AmazonInfo expected = AmazonInfo.Builder.newBuilder()
.addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345")
.build();
Assert.assertEquals(expected, nonCompact(info));
}
|
@SuppressWarnings("unchecked")
public static List<Object> asList(final Object key) {
final Optional<Windowed<Object>> windowed = key instanceof Windowed
? Optional.of((Windowed<Object>) key)
: Optional.empty();
final Object naturalKey = windowed
.map(Windowed::key)
.orElse(key);
if (naturalKey != null && !(naturalKey instanceof GenericKey)) {
throw new IllegalArgumentException("Non generic key: " + key);
}
final Optional<GenericKey> genericKey = Optional.ofNullable((GenericKey) naturalKey);
final List<Object> data = new ArrayList<>(
genericKey.map(GenericKey::size).orElse(0)
+ (windowed.isPresent() ? 2 : 0)
);
genericKey.ifPresent(k -> data.addAll(k.values()));
windowed
.map(Windowed::window)
.ifPresent(wnd -> {
data.add(wnd.start());
data.add(wnd.end());
});
return data;
}
|
@Test
public void shouldConvertWindowedKeyToList() {
// Given:
final Windowed<GenericKey> key = new Windowed<>(
GenericKey.genericKey(10),
new TimeWindow(1000, 2000)
);
// When:
final List<?> result = KeyUtil.asList(key);
// Then:
assertThat(result, is(ImmutableList.of(10, 1000L, 2000L)));
}
|
public boolean canUserViewTemplates(CaseInsensitiveString username, List<Role> roles, boolean isGroupAdministrator) {
for (PipelineTemplateConfig templateConfig : this) {
if (hasViewAccessToTemplate(templateConfig, username, roles, isGroupAdministrator)) {
return true;
}
}
return false;
}
|
@Test
public void shouldReturnFalseIfUserCannotViewAtLeastOneTemplate() {
CaseInsensitiveString templateViewUser = new CaseInsensitiveString("template-view");
TemplatesConfig templates = configForUserWhoCanViewATemplate();
assertThat(templates.canUserViewTemplates(templateViewUser, null, false), is(false));
}
|
public List<IssueDto> getTaintIssuesOnly(List<IssueDto> issues) {
return filterTaintIssues(issues, true);
}
|
@Test
public void test_getTaintIssuesOnly() {
List<IssueDto> taintIssues = underTest.getTaintIssuesOnly(getIssues());
assertThat(taintIssues).hasSize(6);
assertThat(taintIssues.get(0).getKey()).isEqualTo("taintIssue1");
assertThat(taintIssues.get(1).getKey()).isEqualTo("taintIssue2");
assertThat(taintIssues.get(2).getKey()).isEqualTo("taintIssue3");
assertThat(taintIssues.get(3).getKey()).isEqualTo("taintIssue4");
assertThat(taintIssues.get(4).getKey()).isEqualTo("taintIssue5");
assertThat(taintIssues.get(5).getKey()).isEqualTo("taintIssue6");
}
|
protected BaseNode parse(String input) {
return input.isEmpty() || input.isBlank() ? getNullNode() : parseNotEmptyInput(input);
}
|
@Test
void parse_emptyString() {
assertThat(rangeFunction.parse("")).withFailMessage("Check ``").isInstanceOf(NullNode.class);
}
|
public String computerId() {
return parseString(token(14));
}
|
@Test
public void testCenterSampleWithNonIntegerComputerId() {
CenterRadarHit rh = new CenterRadarHit(SAMPLE_3);
NopTestUtils.triggerLazyParsing(rh);
assertEquals("25F", rh.computerId());
}
|
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
}
|
@Test
@SuppressWarnings("unchecked")
public void testDecodeDynamicStructStaticArray() {
String rawInput =
"0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000160"
+ "0000000000000000000000000000000000000000000000000000000000000220"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000080"
+ "0000000000000000000000000000000000000000000000000000000000000001"
+ "3400000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000009"
+ "6e6573746564466f6f0000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000080"
+ "0000000000000000000000000000000000000000000000000000000000000001"
+ "3400000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000009"
+ "6e6573746564466f6f0000000000000000000000000000000000000000000000";
assertEquals(
FunctionReturnDecoder.decode(
rawInput, AbiV2TestFixture.getNarStaticArrayFunction.getOutputParameters()),
Arrays.asList(
new StaticArray3(
AbiV2TestFixture.Nar.class,
new AbiV2TestFixture.Nar(
new AbiV2TestFixture.Nuu(
new AbiV2TestFixture.Foo("4", "nestedFoo"))),
new AbiV2TestFixture.Nar(
new AbiV2TestFixture.Nuu(new AbiV2TestFixture.Foo("", ""))),
new AbiV2TestFixture.Nar(
new AbiV2TestFixture.Nuu(
new AbiV2TestFixture.Foo("4", "nestedFoo"))))));
}
|
@Override
public Consumer createConsumer(Processor aProcessor) throws Exception {
// validate that all of the endpoint is configured properly
if (getMonitorType() != null) {
if (!isPlatformServer()) {
throw new IllegalArgumentException(ERR_PLATFORM_SERVER);
}
if (ObjectHelper.isEmpty(getObservedAttribute())) {
throw new IllegalArgumentException(ERR_OBSERVED_ATTRIBUTE);
}
if (getMonitorType().equals("string")) {
if (ObjectHelper.isEmpty(getStringToCompare())) {
throw new IllegalArgumentException(ERR_STRING_TO_COMPARE);
}
if (!isNotifyDiffer() && !isNotifyMatch()) {
throw new IllegalArgumentException(ERR_STRING_NOTIFY);
}
} else if (getMonitorType().equals("gauge")) {
if (!isNotifyHigh() && !isNotifyLow()) {
throw new IllegalArgumentException(ERR_GAUGE_NOTIFY);
}
if (getThresholdHigh() == null) {
throw new IllegalArgumentException(ERR_THRESHOLD_HIGH);
}
if (getThresholdLow() == null) {
throw new IllegalArgumentException(ERR_THRESHOLD_LOW);
}
}
JMXMonitorConsumer answer = new JMXMonitorConsumer(this, aProcessor);
configureConsumer(answer);
return answer;
} else {
// shouldn't need any other validation.
JMXConsumer answer = new JMXConsumer(this, aProcessor);
configureConsumer(answer);
return answer;
}
}
|
@Test
public void noStringToCompare() throws Exception {
JMXEndpoint ep = context.getEndpoint(
"jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=string&observedAttribute=foo",
JMXEndpoint.class);
try {
ep.createConsumer(null);
fail("expected exception");
} catch (IllegalArgumentException e) {
assertEquals(JMXEndpoint.ERR_STRING_TO_COMPARE, e.getMessage());
}
}
|
@Override
public boolean match(Message msg, StreamRule rule) {
Object rawField = msg.getField(rule.getField());
if (rawField == null) {
return rule.getInverted();
}
if (rawField instanceof String) {
String field = (String) rawField;
Boolean result = rule.getInverted() ^ !(field.trim().isEmpty());
return result;
}
return !rule.getInverted();
}
|
@Test
public void testInvertedNulledFieldMatch() throws Exception {
String fieldName = "sampleField";
StreamRule rule = getSampleRule();
rule.setField(fieldName);
rule.setType(StreamRuleType.PRESENCE);
rule.setInverted(true);
Message message = getSampleMessage();
message.addField(fieldName, null);
StreamRuleMatcher matcher = getMatcher(rule);
Boolean result = matcher.match(message, rule);
assertTrue(result);
}
|
public OAuthBearerToken token() {
return token;
}
|
@Test
public void testToken() {
OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback();
callback.token(TOKEN);
assertSame(TOKEN, callback.token());
assertNull(callback.errorCode());
assertNull(callback.errorDescription());
assertNull(callback.errorUri());
}
|
public static String beanToXml(Object bean) {
return beanToXml(bean, CharsetUtil.CHARSET_UTF_8, true);
}
|
@Test
public void beanToXmlTest() {
SchoolVo schoolVo = new SchoolVo();
schoolVo.setSchoolName("西安市第一中学");
schoolVo.setSchoolAddress("西安市雁塔区长安堡一号");
SchoolVo.RoomVo roomVo = new SchoolVo.RoomVo();
roomVo.setRoomName("101教室");
roomVo.setRoomNo("101");
schoolVo.setRoom(roomVo);
assertEquals(xmlStr, JAXBUtil.beanToXml(schoolVo));
}
|
@JsonCreator
public static MessageCountRotationStrategyConfig create(@JsonProperty(TYPE_FIELD) String type,
@JsonProperty("max_docs_per_index") @Min(1) int maxDocsPerIndex) {
return new AutoValue_MessageCountRotationStrategyConfig(type, maxDocsPerIndex);
}
|
@Test
public void testCreate() throws Exception {
final MessageCountRotationStrategyConfig config = MessageCountRotationStrategyConfig.create(1000);
assertThat(config.maxDocsPerIndex()).isEqualTo(1000);
}
|
public Value parseWithOffsetInJsonPointer(String json, String offsetInJsonPointer) {
return this.delegate.parseWithOffsetInJsonPointer(json, offsetInJsonPointer);
}
|
@Test
public void testParseWithPointer2() throws Exception {
final JsonParser parser = new JsonParser();
final Value msgpackValue = parser.parseWithOffsetInJsonPointer("{\"a\": [{\"b\": 1}, {\"b\": 2}]}", "/a/1/b");
assertEquals(2, msgpackValue.asIntegerValue().asInt());
}
|
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScenario);
}
afterFeature();
}
}
|
@Test
void testAlign() {
run("align.feature");
match(fr.result.getVariables(), "{ configSource: 'normal', functionFromKarateBase: '#notnull', text: 'hello bar world' , cats: '#notnull', myJson: {}}}");
}
|
public MetaStoreInitListener(Configuration config){
this.conf = config;
}
|
@Test
public void testMetaStoreInitListener() throws Exception {
// DummyMetaStoreInitListener's onInit will be called at HMSHandler
// initialization, and set this to true
Assert.assertTrue(DummyMetaStoreInitListener.wasCalled);
}
|
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
}
|
@Test
public void testListPlaceholderDot() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path placeholder = new S3DirectoryFeature(session, new S3WriteFeature(session, acl), acl).mkdir(
new Path(container, ".", EnumSet.of(Path.Type.directory)), new TransferStatus());
assertTrue(new S3ObjectListService(session, new S3AccessControlListFeature(session)).list(container, new DisabledListProgressListener()).contains(placeholder));
new S3DefaultDeleteFeature(session).delete(Collections.singletonList(placeholder), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
|
public boolean satisfies(final Distribution distribution, final String expression) {
return this.distribution().equals(distribution) && version().satisfies(expression);
}
|
@Test
void satisfies() {
final SearchVersion searchVersion = SearchVersion.create(SearchVersion.Distribution.ELASTICSEARCH, ver("5.1.4"));
assertThat(searchVersion.satisfies(SearchVersion.Distribution.ELASTICSEARCH, "^5.0.0")).isTrue();
assertThat(searchVersion.satisfies(SearchVersion.Distribution.ELASTICSEARCH, "^4.0.0")).isFalse();
assertThat(searchVersion.satisfies(SearchVersion.Distribution.OPENSEARCH, "^5.0.0")).isFalse();
}
|
public static Range<Comparable<?>> safeIntersection(final Range<Comparable<?>> range, final Range<Comparable<?>> connectedRange) {
try {
return range.intersection(connectedRange);
} catch (final ClassCastException ex) {
Class<?> clazz = getRangeTargetNumericType(range, connectedRange);
if (null == clazz) {
throw ex;
}
Range<Comparable<?>> newRange = createTargetNumericTypeRange(range, clazz);
Range<Comparable<?>> newConnectedRange = createTargetNumericTypeRange(connectedRange, clazz);
return newRange.intersection(newConnectedRange);
}
}
|
@Test
void assertSafeIntersectionForBigDecimal() {
Range<Comparable<?>> range = Range.upTo(new BigDecimal("2331.23211"), BoundType.CLOSED);
Range<Comparable<?>> connectedRange = Range.open(135.13F, 45343.23F);
Range<Comparable<?>> newRange = SafeNumberOperationUtils.safeIntersection(range, connectedRange);
assertThat(newRange.lowerEndpoint(), is(new BigDecimal("135.13")));
assertThat(newRange.lowerBoundType(), is(BoundType.OPEN));
assertThat(newRange.upperEndpoint(), is(new BigDecimal("2331.23211")));
assertThat(newRange.upperBoundType(), is(BoundType.CLOSED));
}
|
@Override
public void checkCanSetUser(Identity identity, AccessControlContext context, Optional<Principal> principal, String userName)
{
requireNonNull(principal, "principal is null");
requireNonNull(userName, "userName is null");
if (!principalUserMatchRules.isPresent()) {
return;
}
if (!principal.isPresent()) {
denySetUser(principal, userName);
}
String principalName = principal.get().getName();
for (PrincipalUserMatchRule rule : principalUserMatchRules.get()) {
Optional<Boolean> allowed = rule.match(principalName, userName);
if (allowed.isPresent()) {
if (allowed.get()) {
return;
}
denySetUser(principal, userName);
}
}
denySetUser(principal, userName);
}
|
@Test
public void testCanSetUserOperations() throws IOException
{
TransactionManager transactionManager = createTestTransactionManager();
AccessControlManager accessControlManager = newAccessControlManager(transactionManager, "catalog_principal.json");
try {
accessControlManager.checkCanSetUser(alice, context, Optional.empty(), alice.getUser());
throw new AssertionError("expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
accessControlManager.checkCanSetUser(kerberosValidAlice, context, kerberosValidAlice.getPrincipal(), kerberosValidAlice.getUser());
accessControlManager.checkCanSetUser(kerberosValidNonAsciiUser, context, kerberosValidNonAsciiUser.getPrincipal(), kerberosValidNonAsciiUser.getUser());
try {
accessControlManager.checkCanSetUser(kerberosInvalidAlice, context, kerberosInvalidAlice.getPrincipal(), kerberosInvalidAlice.getUser());
throw new AssertionError("expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
accessControlManager.checkCanSetUser(kerberosValidShare, context, kerberosValidShare.getPrincipal(), kerberosValidShare.getUser());
try {
accessControlManager.checkCanSetUser(kerberosInValidShare, context, kerberosInValidShare.getPrincipal(), kerberosInValidShare.getUser());
throw new AssertionError("expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
accessControlManager.checkCanSetUser(validSpecialRegexWildDot, context, validSpecialRegexWildDot.getPrincipal(), validSpecialRegexWildDot.getUser());
accessControlManager.checkCanSetUser(validSpecialRegexEndQuote, context, validSpecialRegexEndQuote.getPrincipal(), validSpecialRegexEndQuote.getUser());
try {
accessControlManager.checkCanSetUser(invalidSpecialRegex, context, invalidSpecialRegex.getPrincipal(), invalidSpecialRegex.getUser());
throw new AssertionError("expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
TransactionManager transactionManagerNoPatterns = createTestTransactionManager();
AccessControlManager accessControlManagerNoPatterns = newAccessControlManager(transactionManager, "catalog.json");
accessControlManagerNoPatterns.checkCanSetUser(kerberosValidAlice, context, kerberosValidAlice.getPrincipal(), kerberosValidAlice.getUser());
}
|
public static Serializable decode(final ByteBuf byteBuf) {
int valueType = byteBuf.readUnsignedByte() & 0xff;
StringBuilder result = new StringBuilder();
decodeValue(valueType, 1, byteBuf, result);
return result.toString();
}
|
@Test
void assertDecodeLargeJsonArray() {
List<JsonEntry> jsonEntries = new LinkedList<>();
jsonEntries.add(new JsonEntry(JsonValueTypes.INT16, null, 0x00007fff));
jsonEntries.add(new JsonEntry(JsonValueTypes.INT16, null, 0x00008000));
ByteBuf payload = mockJsonArrayByteBuf(jsonEntries, false);
String actual = (String) MySQLJsonValueDecoder.decode(payload);
assertThat(actual, is("[32767,-32768]"));
}
|
public static boolean checkUserInfo( IUser user ) {
return !StringUtils.isBlank( user.getLogin() ) && !StringUtils.isBlank( user.getName() );
}
|
@Test
public void checkUserInfo_BothAreMeaningful() {
assertTrue( RepositoryCommonValidations.checkUserInfo( user( "login", "name" ) ) );
}
|
public void publishRemoved(Cache<K, V> cache, K key, V value) {
publish(cache, EventType.REMOVED, key, /* hasOldValue */ true,
/* oldValue */ value, /* newValue */ value, /* quiet */ false);
}
|
@Test
public void publishRemoved() {
var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run);
registerAll(dispatcher);
dispatcher.publishRemoved(cache, 1, 2);
verify(removedListener, times(4)).onRemoved(any());
assertThat(dispatcher.pending.get()).hasSize(2);
assertThat(dispatcher.dispatchQueues.values().stream()
.flatMap(queue -> queue.entrySet().stream())).isEmpty();
}
|
@Override
public String symmetricEncryptType() {
return "AES";
}
|
@Test
public void symmetricEncryptType() {
SAECEncrypt ecEncrypt = new SAECEncrypt();
Assert.assertEquals("AES", ecEncrypt.symmetricEncryptType());
}
|
public int run() throws IOException {
String[] header = new String[]{"Address", "State", "Start Time", "Last Heartbeat Time",
"Version", "Revision"};
try {
List<ProxyStatus> allProxyStatus = mMetaMasterClient.listProxyStatus();
int liveCount = 0;
int lostCount = 0;
int maxAddressLength = 24;
for (ProxyStatus proxyStatus : allProxyStatus) {
String state = proxyStatus.getState();
if (state.equals("ACTIVE")) {
liveCount++;
} else if (state.equals("LOST")) {
lostCount++;
}
NetAddress address = proxyStatus.getAddress();
String addressStr = address.getHost() + ":" + address.getRpcPort();
if (maxAddressLength < addressStr.length()) {
maxAddressLength = addressStr.length();
}
}
mPrintStream.printf("%s Proxy instances in the cluster, %s serving and %s lost%n%n",
liveCount + lostCount, liveCount, lostCount);
String format = "%-" + maxAddressLength + "s %-8s %-16s %-20s %-32s %-8s%n";
mPrintStream.printf(format, header);
for (ProxyStatus proxyStatus : allProxyStatus) {
NetAddress address = proxyStatus.getAddress();
BuildVersion version = proxyStatus.getVersion();
mPrintStream.printf(format,
address.getHost() + ":" + address.getRpcPort(),
proxyStatus.getState(),
DATETIME_FORMAT.format(Instant.ofEpochMilli(proxyStatus.getStartTime())),
DATETIME_FORMAT.format(Instant.ofEpochMilli(proxyStatus.getLastHeartbeatTime())),
version.getVersion(), version.getRevision());
}
return 0;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
|
@Test
public void listProxyInstancesLongName() throws IOException {
List<ProxyStatus> longInfoList = prepareInfoListLongName();
Mockito.when(mMetaMasterClient.listProxyStatus())
.thenReturn(longInfoList);
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream, true, "utf-8")) {
ProxyCommand proxyCommand = new ProxyCommand(mMetaMasterClient, printStream);
proxyCommand.run();
String output = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
// CHECKSTYLE.OFF: LineLengthExceed - Much more readable
List<String> expectedOutput = Arrays.asList("2 Proxy instances in the cluster, 1 serving and 1 lost",
"",
"Address State Start Time Last Heartbeat Time Version Revision",
"datacenter-namespace-department-proxy-0:12345 ACTIVE 20230421-182944 20230421-183005 1.0 abc ",
"datacenter-namespace-department-proxy-1:23456 LOST 20230421-182707 20230421-190507 1.1 abc ");
// CHECKSTYLE.ON: LineLengthExceed
List<String> testOutput = Arrays.asList(output.split("\n"));
Assert.assertThat(testOutput,
IsIterableContainingInOrder.contains(expectedOutput.toArray()));
}
}
|
@Override
public Object merge(T mergingValue, T existingValue) {
if (existingValue == null) {
return null;
}
return existingValue.getRawValue();
}
|
@Test
public void merge_existingValuePresent() {
MapMergeTypes existing = mergingValueWithGivenValue(EXISTING);
MapMergeTypes merging = mergingValueWithGivenValue(MERGING);
assertEquals(EXISTING, mergePolicy.merge(merging, existing));
}
|
@Override
public String toString() {
return StrUtil.NULL;
}
|
@Test
public void parseNullTest(){
JSONObject bodyjson = JSONUtil.parseObj("{\n" +
" \"device_model\": null,\n" +
" \"device_status_date\": null,\n" +
" \"imsi\": null,\n" +
" \"act_date\": \"2021-07-23T06:23:26.000+00:00\"}");
assertEquals(JSONNull.class, bodyjson.get("device_model").getClass());
assertEquals(JSONNull.class, bodyjson.get("device_status_date").getClass());
assertEquals(JSONNull.class, bodyjson.get("imsi").getClass());
bodyjson.getConfig().setIgnoreNullValue(true);
assertEquals("{\"act_date\":\"2021-07-23T06:23:26.000+00:00\"}", bodyjson.toString());
}
|
public void byteOrder(final ByteOrder byteOrder)
{
if (null == byteOrder)
{
throw new IllegalArgumentException("byteOrder cannot be null");
}
this.byteOrder = byteOrder;
}
|
@Test
void shouldReadUtf() throws Throwable
{
final UnsafeBuffer buffer = toUnsafeBuffer(
(out) ->
{
out.writeLong(0);
out.writeUTF("zażółć gęślą jaźń北查爾斯頓");
out.writeLong(0);
});
final DirectBufferDataInput dataInput = new DirectBufferDataInput(buffer, 8, 47);
dataInput.byteOrder(byteOrder());
assertEquals("zażółć gęślą jaźń北查爾斯頓", dataInput.readUTF());
}
|
@Nullable
DockerCredentialHelper getCredentialHelperFor(String registry) {
List<Predicate<String>> registryMatchers = getRegistryMatchersFor(registry);
Map.Entry<String, String> firstCredHelperMatch =
findFirstInMapByKey(dockerConfigTemplate.getCredHelpers(), registryMatchers);
if (firstCredHelperMatch != null) {
return new DockerCredentialHelper(
firstCredHelperMatch.getKey(),
Paths.get("docker-credential-" + firstCredHelperMatch.getValue()));
}
if (dockerConfigTemplate.getCredsStore() != null) {
return new DockerCredentialHelper(
registry, Paths.get("docker-credential-" + dockerConfigTemplate.getCredsStore()));
}
return null;
}
|
@Test
public void testGetCredentialHelperFor_correctSuffixMatching()
throws URISyntaxException, IOException {
Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI());
DockerConfig dockerConfig =
new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerConfigTemplate.class));
// Should fall back to credsStore
Assert.assertEquals(
Paths.get("docker-credential-some credential store"),
dockerConfig.getCredentialHelperFor("example").getCredentialHelper());
Assert.assertEquals(
Paths.get("docker-credential-some credential store"),
dockerConfig.getCredentialHelperFor("another.example").getCredentialHelper());
}
|
@Override
public long selectNextWorker() throws NonRecoverableException {
ComputeNode worker;
worker = getNextWorker(availableID2ComputeNode, DefaultSharedDataWorkerProvider::getNextComputeNodeIndex);
if (worker == null) {
reportWorkerNotFoundException();
}
Preconditions.checkNotNull(worker);
selectWorkerUnchecked(worker.getId());
return worker.getId();
}
|
@Test
public void testSelectNextWorker() throws UserException {
HostBlacklist blockList = SimpleScheduler.getHostBlacklist();
blockList.hostBlacklist.clear();
SystemInfoService sysInfo = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo();
List<Long> availList = prepareNodeAliveAndBlock(sysInfo, blockList);
{ // test backend nodes only
ImmutableMap.Builder<Long, ComputeNode> builder = new ImmutableMap.Builder<>();
for (long backendId : id2Backend.keySet()) {
if (availList.contains(backendId)) {
builder.put(backendId, id2Backend.get(backendId));
}
}
ImmutableMap<Long, ComputeNode> availableId2ComputeNode = builder.build();
WorkerProvider workerProvider =
new DefaultSharedDataWorkerProvider(ImmutableMap.copyOf(id2Backend), availableId2ComputeNode);
testSelectNextWorkerHelper(workerProvider, availableId2ComputeNode);
}
{ // test compute nodes only
ImmutableMap.Builder<Long, ComputeNode> builder = new ImmutableMap.Builder<>();
for (long backendId : id2ComputeNode.keySet()) {
if (availList.contains(backendId)) {
builder.put(backendId, id2ComputeNode.get(backendId));
}
}
ImmutableMap<Long, ComputeNode> availableId2ComputeNode = builder.build();
WorkerProvider workerProvider =
new DefaultSharedDataWorkerProvider(ImmutableMap.copyOf(id2ComputeNode), availableId2ComputeNode);
testSelectNextWorkerHelper(workerProvider, availableId2ComputeNode);
}
{ // test both backends and compute nodes
ImmutableMap.Builder<Long, ComputeNode> builder = new ImmutableMap.Builder<>();
for (long backendId : id2AllNodes.keySet()) {
if (availList.contains(backendId)) {
builder.put(backendId, id2AllNodes.get(backendId));
}
}
ImmutableMap<Long, ComputeNode> availableId2ComputeNode = builder.build();
WorkerProvider workerProvider =
new DefaultSharedDataWorkerProvider(ImmutableMap.copyOf(id2AllNodes), availableId2ComputeNode);
testSelectNextWorkerHelper(workerProvider, availableId2ComputeNode);
}
{ // test no available worker to select
WorkerProvider workerProvider =
new DefaultSharedDataWorkerProvider(ImmutableMap.copyOf(id2AllNodes), ImmutableMap.of());
Assert.assertThrows(NonRecoverableException.class, workerProvider::selectNextWorker);
}
}
|
@Override
public void serialize(Asn1OutputStream out, Class<? extends Object> type, Object instance, Asn1ObjectMapper mapper)
throws IOException {
writeFields(mapper, out, type, instance);
}
|
@Test
public void shouldSerializeWithOptional() {
assertArrayEquals(
new byte[] { (byte) 0x81, 1, 0x01, (byte) 0x82, 1, 0x02, (byte) 0x83, 1, 0x03 },
serialize(new SetConverter(), Set.class, new Set(1, 2, 3))
);
}
|
@Override
public String getDescription() {
return "time: " + time
+ ", threshold_type: " + thresholdType.toString().toLowerCase(Locale.ENGLISH)
+ ", threshold: " + threshold
+ ", grace: " + grace
+ ", repeat notifications: " + repeatNotifications;
}
|
@Test
public void testConstructor() throws Exception {
final Map<String, Object> parameters = getParametersMap(0, 0, MessageCountAlertCondition.ThresholdType.MORE, 0);
final MessageCountAlertCondition messageCountAlertCondition = getMessageCountAlertCondition(parameters, alertConditionTitle);
assertNotNull(messageCountAlertCondition);
assertNotNull(messageCountAlertCondition.getDescription());
final String thresholdType = (String) messageCountAlertCondition.getParameters().get("threshold_type");
assertEquals(thresholdType, thresholdType.toUpperCase(Locale.ENGLISH));
}
|
@Override
public ScheduledExecutor getScheduledExecutor() {
return internalScheduledExecutor;
}
|
@Test
void testScheduleRunnable() throws Exception {
final OneShotLatch latch = new OneShotLatch();
final long delay = 100L;
final long start = System.nanoTime();
ScheduledFuture<?> scheduledFuture =
pekkoRpcService
.getScheduledExecutor()
.schedule(latch::trigger, delay, TimeUnit.MILLISECONDS);
scheduledFuture.get();
assertThat(latch.isTriggered()).isTrue();
final long stop = System.nanoTime();
assertThat(((stop - start) / 1000000))
.as("call was not properly delayed")
.isGreaterThanOrEqualTo(delay);
}
|
public static void applyDataChangeEvent(DataChangeEvent event) {
ValuesTable table = globalTables.get(event.tableId());
Preconditions.checkNotNull(table, event.tableId() + " is not existed");
table.applyDataChangeEvent(event);
LOG.info("apply DataChangeEvent: " + event);
}
|
@Test
public void testApplyDataChangeEvent() {
List<String> results = new ArrayList<>();
results.add("default.default.table1:col1=1;col2=1");
results.add("default.default.table1:col1=2;col2=2");
results.add("default.default.table1:col1=3;col2=3");
Assert.assertEquals(results, ValuesDatabase.getResults(table1));
BinaryRecordDataGenerator generator =
new BinaryRecordDataGenerator(RowType.of(DataTypes.STRING(), DataTypes.STRING()));
DataChangeEvent deleteEvent =
DataChangeEvent.deleteEvent(
table1,
generator.generate(
new Object[] {
BinaryStringData.fromString("1"),
BinaryStringData.fromString("1")
}));
ValuesDatabase.applyDataChangeEvent(deleteEvent);
results.clear();
results.add("default.default.table1:col1=2;col2=2");
results.add("default.default.table1:col1=3;col2=3");
Assert.assertEquals(results, ValuesDatabase.getResults(table1));
DataChangeEvent updateEvent =
DataChangeEvent.updateEvent(
table1,
generator.generate(
new Object[] {
BinaryStringData.fromString("2"),
BinaryStringData.fromString("2")
}),
generator.generate(
new Object[] {
BinaryStringData.fromString("2"),
BinaryStringData.fromString("x")
}));
ValuesDatabase.applyDataChangeEvent(updateEvent);
results.clear();
results.add("default.default.table1:col1=2;col2=x");
results.add("default.default.table1:col1=3;col2=3");
Assert.assertEquals(results, ValuesDatabase.getResults(table1));
}
|
public static UTypeVarIdent create(CharSequence name) {
return new AutoValue_UTypeVarIdent(StringName.of(name));
}
|
@Test
public void serialization() {
SerializableTester.reserializeAndAssert(UTypeVarIdent.create("E"));
}
|
public static UUnary create(Kind unaryOp, UExpression expression) {
checkArgument(
UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp);
return new AutoValue_UUnary(unaryOp, expression);
}
|
@Test
public void preDecrement() {
assertUnifiesAndInlines("--foo", UUnary.create(Kind.PREFIX_DECREMENT, fooIdent));
}
|
@Override
public BundleData getBundleDataOrDefault(final String bundle) {
BundleData bundleData = null;
try {
Optional<BundleData> optBundleData =
pulsarResources.getLoadBalanceResources().getBundleDataResources().getBundleData(bundle).join();
if (optBundleData.isPresent()) {
return optBundleData.get();
}
Optional<ResourceQuota> optQuota = pulsarResources.getLoadBalanceResources().getQuotaResources()
.getQuota(bundle).join();
if (optQuota.isPresent()) {
ResourceQuota quota = optQuota.get();
bundleData = new BundleData(NUM_SHORT_SAMPLES, NUM_LONG_SAMPLES);
// Initialize from existing resource quotas if new API ZNodes do not exist.
final TimeAverageMessageData shortTermData = bundleData.getShortTermData();
final TimeAverageMessageData longTermData = bundleData.getLongTermData();
shortTermData.setMsgRateIn(quota.getMsgRateIn());
shortTermData.setMsgRateOut(quota.getMsgRateOut());
shortTermData.setMsgThroughputIn(quota.getBandwidthIn());
shortTermData.setMsgThroughputOut(quota.getBandwidthOut());
longTermData.setMsgRateIn(quota.getMsgRateIn());
longTermData.setMsgRateOut(quota.getMsgRateOut());
longTermData.setMsgThroughputIn(quota.getBandwidthIn());
longTermData.setMsgThroughputOut(quota.getBandwidthOut());
// Assume ample history.
shortTermData.setNumSamples(NUM_SHORT_SAMPLES);
longTermData.setNumSamples(NUM_LONG_SAMPLES);
}
} catch (Exception e) {
log.warn("Error when trying to find bundle {} on metadata store: {}", bundle, e);
}
if (bundleData == null) {
bundleData = new BundleData(NUM_SHORT_SAMPLES, NUM_LONG_SAMPLES, defaultStats);
}
return bundleData;
}
|
@Test(dataProvider = "isV1")
public void testBundleDataDefaultValue(boolean isV1) throws Exception {
final String cluster = "use";
final String tenant = "my-tenant";
final String namespace = "my-ns";
NamespaceName ns = isV1 ? NamespaceName.get(tenant, cluster, namespace) : NamespaceName.get(tenant, namespace);
admin1.clusters().createCluster(cluster, ClusterData.builder().serviceUrl(pulsar1.getWebServiceAddress()).build());
admin1.tenants().createTenant(tenant,
new TenantInfoImpl(Sets.newHashSet("appid1", "appid2"), Sets.newHashSet(cluster)));
admin1.namespaces().createNamespace(ns.toString(), 16);
// set resourceQuota to the first bundle range.
BundlesData bundlesData = admin1.namespaces().getBundles(ns.toString());
NamespaceBundle namespaceBundle = nsFactory.getBundle(ns,
Range.range(Long.decode(bundlesData.getBoundaries().get(0)), BoundType.CLOSED, Long.decode(bundlesData.getBoundaries().get(1)),
BoundType.OPEN));
ResourceQuota quota = new ResourceQuota();
quota.setMsgRateIn(1024.1);
quota.setMsgRateOut(1024.2);
quota.setBandwidthIn(1024.3);
quota.setBandwidthOut(1024.4);
quota.setMemory(1024.0);
admin1.resourceQuotas().setNamespaceBundleResourceQuota(ns.toString(), namespaceBundle.getBundleRange(), quota);
ModularLoadManagerWrapper loadManagerWrapper = (ModularLoadManagerWrapper) pulsar1.getLoadManager().get();
ModularLoadManagerImpl lm = (ModularLoadManagerImpl) loadManagerWrapper.getLoadManager();
// get the bundleData of the first bundle range.
// The default value of the bundleData be the same as resourceQuota because the resourceQuota is present.
BundleData defaultBundleData = lm.getBundleDataOrDefault(namespaceBundle.toString());
TimeAverageMessageData shortTermData = defaultBundleData.getShortTermData();
TimeAverageMessageData longTermData = defaultBundleData.getLongTermData();
assertEquals(shortTermData.getMsgRateIn(), 1024.1);
assertEquals(shortTermData.getMsgRateOut(), 1024.2);
assertEquals(shortTermData.getMsgThroughputIn(), 1024.3);
assertEquals(shortTermData.getMsgThroughputOut(), 1024.4);
assertEquals(longTermData.getMsgRateIn(), 1024.1);
assertEquals(longTermData.getMsgRateOut(), 1024.2);
assertEquals(longTermData.getMsgThroughputIn(), 1024.3);
assertEquals(longTermData.getMsgThroughputOut(), 1024.4);
}
|
String storeSink() {
return storeSink;
}
|
@Test
public void testStoreSinkIsQuoted() {
Queries queries = new Queries(mapping, idColumn, columnMetadata);
String result = queries.storeSink();
assertEquals("SINK INTO \"mymapping\" (\"id\", \"name\", \"address\") VALUES (?, ?, ?)", result);
}
|
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
List<AclEntry> foundAclSpecEntries =
Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry> providedMask =
Maps.newEnumMap(AclEntryScope.class);
EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class);
EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class);
for (AclEntry existingEntry: existingAcl) {
AclEntry aclSpecEntry = aclSpec.findByKey(existingEntry);
if (aclSpecEntry != null) {
foundAclSpecEntries.add(aclSpecEntry);
scopeDirty.add(aclSpecEntry.getScope());
if (aclSpecEntry.getType() == MASK) {
providedMask.put(aclSpecEntry.getScope(), aclSpecEntry);
maskDirty.add(aclSpecEntry.getScope());
} else {
aclBuilder.add(aclSpecEntry);
}
} else {
if (existingEntry.getType() == MASK) {
providedMask.put(existingEntry.getScope(), existingEntry);
} else {
aclBuilder.add(existingEntry);
}
}
}
// ACL spec entries that were not replacements are new additions.
for (AclEntry newEntry: aclSpec) {
if (Collections.binarySearch(foundAclSpecEntries, newEntry,
ACL_ENTRY_COMPARATOR) < 0) {
scopeDirty.add(newEntry.getScope());
if (newEntry.getType() == MASK) {
providedMask.put(newEntry.getScope(), newEntry);
maskDirty.add(newEntry.getScope());
} else {
aclBuilder.add(newEntry);
}
}
}
copyDefaultsIfNeeded(aclBuilder);
calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty);
return buildAndValidateAcl(aclBuilder);
}
|
@Test
public void testMergeAclEntriesMultipleNewBeforeExisting()
throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "diana", READ))
.add(aclEntry(ACCESS, GROUP, READ_EXECUTE))
.add(aclEntry(ACCESS, MASK, READ_EXECUTE))
.add(aclEntry(ACCESS, OTHER, NONE))
.build();
List<AclEntry> aclSpec = Lists.newArrayList(
aclEntry(ACCESS, USER, "bruce", READ_EXECUTE),
aclEntry(ACCESS, USER, "clark", READ_EXECUTE),
aclEntry(ACCESS, USER, "diana", READ_EXECUTE));
List<AclEntry> expected = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", READ_EXECUTE))
.add(aclEntry(ACCESS, USER, "clark", READ_EXECUTE))
.add(aclEntry(ACCESS, USER, "diana", READ_EXECUTE))
.add(aclEntry(ACCESS, GROUP, READ_EXECUTE))
.add(aclEntry(ACCESS, MASK, READ_EXECUTE))
.add(aclEntry(ACCESS, OTHER, NONE))
.build();
assertEquals(expected, mergeAclEntries(existing, aclSpec));
}
|
protected HttpUriRequest setupConnection(final String method, final String bucketName,
final String objectKey, final Map<String, String> requestParameters) throws S3ServiceException {
return this.setupConnection(HTTP_METHOD.valueOf(method), bucketName, objectKey, requestParameters);
}
|
@Test
public void testSetupConnectionVirtualHost() throws Exception {
final RequestEntityRestStorageService service = new RequestEntityRestStorageService(virtualhost, new HttpConnectionPoolBuilder(virtualhost.getHost(),
new ThreadLocalHostnameDelegatingTrustManager(new DisabledX509TrustManager(), session.getHost().getHostname()),
new DefaultX509KeyManager(), new DisabledProxyFinder()).build(new DisabledProxyFinder(), new DisabledTranscriptListener(), new DisabledLoginCallback()));
final RegionEndpointCache cache = service.getRegionEndpointCache();
cache.clear();
final String key = new AlphanumericRandomStringService().random();
{
final HttpUriRequest request = service.setupConnection("GET", "", key, Collections.emptyMap());
assertEquals(String.format("https://test-eu-west-3-cyberduck.s3.amazonaws.com:443/%s", key), request.getURI().toString());
}
}
|
@Override
public void close() throws IOException {
if(close.get()) {
log.warn(String.format("Skip double close of stream %s", this));
return;
}
try {
if(buffer.size() > 0) {
proxy.write(buffer.toByteArray());
}
// Re-use buffer
buffer.reset();
super.close();
}
finally {
close.set(true);
}
}
|
@Test
public void testCopy1() throws Exception {
final ByteArrayOutputStream proxy = new ByteArrayOutputStream(20);
final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768);
final byte[] content = RandomUtils.nextBytes(40500);
out.write(content, 0, 32800);
assertEquals(32768, proxy.toByteArray().length);
out.write(content, 32800, 7700);
out.close();
assertArrayEquals(content, proxy.toByteArray());
}
|
public static boolean isLazyFailedWritesCleanPolicy(Configuration conf) {
// get all keys with alternatives as strings from Hudi's ConfigProperty
List<String> allKeys = new ArrayList<>();
allKeys.add(HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.key());
allKeys.addAll(HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.getAlternatives());
// and check them in Flink's Configuration for all key variations support
for (String key : allKeys) {
if (conf.containsKey(key)) {
return conf.getString(key, "").equalsIgnoreCase(HoodieFailedWritesCleaningPolicy.LAZY.name());
}
}
return HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.defaultValue().equalsIgnoreCase(HoodieFailedWritesCleaningPolicy.LAZY.name());
}
|
@Test
void testIsLazyFailedWritesCleanPolicy() {
Configuration conf = new Configuration();
// add any parameter
conf.set(FlinkOptions.CLEAN_ASYNC_ENABLED, true);
// add value for FAILED_WRITES_CLEANER_POLICY using default key
conf.setString(HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.key(), HoodieFailedWritesCleaningPolicy.NEVER.name());
assertFalse(OptionsResolver.isLazyFailedWritesCleanPolicy(conf));
if (!HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.getAlternatives().isEmpty()) {
conf = new Configuration();
// add any parameter
conf.set(FlinkOptions.CLEAN_ASYNC_ENABLED, true);
// add value for FAILED_WRITES_CLEANER_POLICY using alternative key
conf.setString(HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.getAlternatives().get(0), HoodieFailedWritesCleaningPolicy.LAZY.name());
assertTrue(OptionsResolver.isLazyFailedWritesCleanPolicy(conf));
}
}
|
private static VerificationResult verifyChecksums(String expectedDigest, String actualDigest, boolean caseSensitive) {
if (expectedDigest == null) {
return VerificationResult.NOT_PROVIDED;
}
if (actualDigest == null) {
return VerificationResult.NOT_COMPUTED;
}
if (caseSensitive) {
if (MessageDigest.isEqual(expectedDigest.getBytes(StandardCharsets.US_ASCII), actualDigest.getBytes(StandardCharsets.US_ASCII))) {
return VerificationResult.PASS;
}
} else {
if (MessageDigest.isEqual(expectedDigest.toLowerCase().getBytes(StandardCharsets.US_ASCII), actualDigest.toLowerCase().getBytes(StandardCharsets.US_ASCII))) {
return VerificationResult.PASS;
}
}
return VerificationResult.FAIL;
}
|
@Test
public void noOverlapForComputedAndProvidedChecksums() {
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null),
buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example")));
assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage());
}
|
public static <K, V> Read<K, V> read() {
return new AutoValue_KafkaIO_Read.Builder<K, V>()
.setTopics(new ArrayList<>())
.setTopicPartitions(new ArrayList<>())
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES)
.setMaxNumRecords(Long.MAX_VALUE)
.setCommitOffsetsInFinalizeEnabled(false)
.setDynamicRead(false)
.setTimestampPolicyFactory(TimestampPolicyFactory.withProcessingTime())
.setConsumerPollingTimeout(2L)
.setRedistributed(false)
.setAllowDuplicates(false)
.setRedistributeNumKeys(0)
.build();
}
|
@Test
public void testUnboundedSourceWithExplicitPartitions() {
int numElements = 1000;
String topic = "test";
List<String> topics = ImmutableList.of(topic);
String bootStrapServer = "none";
KafkaIO.Read<byte[], Long> reader =
KafkaIO.<byte[], Long>read()
.withBootstrapServers(bootStrapServer)
.withTopicPartitions(ImmutableList.of(new TopicPartition(topic, 5)))
.withConsumerFactoryFn(
new ConsumerFactoryFn(
topics, 10, numElements, OffsetResetStrategy.EARLIEST)) // 10 partitions
.withKeyDeserializer(ByteArrayDeserializer.class)
.withValueDeserializer(LongDeserializer.class)
.withMaxNumRecords(numElements / 10);
PCollection<Long> input = p.apply(reader.withoutMetadata()).apply(Values.create());
// assert that every element is a multiple of 5.
PAssert.that(input).satisfies(new AssertMultipleOf(5));
PAssert.thatSingleton(input.apply(Count.globally())).isEqualTo(numElements / 10L);
PipelineResult result = p.run();
assertThat(
Lineage.query(result.metrics(), Lineage.Type.SOURCE),
hasItem(String.format("kafka:%s.%s", bootStrapServer, topic)));
}
|
void portAddedHelper(DeviceEvent event) {
log.debug("Instance port {} is detected from {}",
event.port().annotations().value(PORT_NAME),
event.subject().id());
// we check the existence of openstack port, in case VM creation
// event comes before port creation
if (osNetworkService.port(event.port()) != null) {
processPortAdded(event.port());
}
}
|
@Test
public void testProcessPortAddedForNewAddition() {
org.onosproject.net.Port port = new DefaultPort(DEV2, P1, true, ANNOTATIONS);
DeviceEvent event = new DeviceEvent(DeviceEvent.Type.PORT_ADDED, DEV2, port);
target.portAddedHelper(event);
HostId hostId = HostId.hostId(HOST_MAC2);
HostDescription hostDesc = new DefaultHostDescription(
HOST_MAC2,
VlanId.NONE,
new HostLocation(CP21, System.currentTimeMillis()),
ImmutableSet.of(HOST_IP11),
ANNOTATIONS
);
verifyHostResult(hostId, hostDesc);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.