focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public static SimpleTransform add(double operand) {
return new SimpleTransform(Operation.add,operand);
} | @Test
public void testAdd() {
TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.add(5)),new HashMap<>());
testSimple(t,(double a) -> a + 5);
} |
@Override
public void onEvent(ReplicaMigrationEvent event) {
switch (event.getPartitionId()) {
case MIGRATION_STARTED_PARTITION_ID:
migrationListener.migrationStarted(event.getMigrationState());
break;
case MIGRATION_FINISHED_PARTITION_ID:
migrationListener.migrationFinished(event.getMigrationState());
break;
default:
if (event.isSuccess()) {
migrationListener.replicaMigrationCompleted(event);
} else {
migrationListener.replicaMigrationFailed(event);
}
}
} | @Test
public void test_migrationProcessStarted() {
MigrationState migrationSchedule = new MigrationStateImpl();
ReplicaMigrationEvent event = new ReplicaMigrationEventImpl(migrationSchedule, MIGRATION_STARTED_PARTITION_ID, 0, null, null, true, 0L);
adapter.onEvent(event);
verify(listener).migrationStarted(migrationSchedule);
verify(listener, never()).migrationFinished(any(MigrationStateImpl.class));
verify(listener, never()).replicaMigrationCompleted(any(ReplicaMigrationEvent.class));
verify(listener, never()).replicaMigrationFailed(any(ReplicaMigrationEvent.class));
} |
public static void bind(ServerSocket socket, InetSocketAddress address,
int backlog) throws IOException {
bind(socket, address, backlog, null, null);
} | @Test
public void testBindError() throws Exception {
Configuration conf = new Configuration();
ServerSocket socket = new ServerSocket();
InetSocketAddress address = new InetSocketAddress("0.0.0.0",0);
socket.bind(address);
try {
int min = socket.getLocalPort();
conf.set("TestRange", min+"-"+min);
ServerSocket socket2 = new ServerSocket();
InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
boolean caught = false;
try {
Server.bind(socket2, address2, 10, conf, "TestRange");
} catch (BindException e) {
caught = true;
} finally {
socket2.close();
}
assertTrue("Failed to catch the expected bind exception",caught);
} finally {
socket.close();
}
} |
public List<HDPath> ancestors() {
return ancestors(false);
} | @Test
public void testAncestors() {
HDPath path = HDPath.parsePath("m/0H/1H/0H/1/0");
List<HDPath> ancestors = path.ancestors();
assertEquals(4, ancestors.size());
assertEquals(HDPath.parsePath("m/0H"), ancestors.get(0));
assertEquals(HDPath.parsePath("m/0H/1H"), ancestors.get(1));
assertEquals(HDPath.parsePath("m/0H/1H/0H"), ancestors.get(2));
assertEquals(HDPath.parsePath("m/0H/1H/0H/1"), ancestors.get(3));
List<HDPath> ancestorsWithSelf = path.ancestors(true);
assertEquals(5, ancestorsWithSelf.size());
assertEquals(HDPath.parsePath("m/0H"), ancestorsWithSelf.get(0));
assertEquals(HDPath.parsePath("m/0H/1H"), ancestorsWithSelf.get(1));
assertEquals(HDPath.parsePath("m/0H/1H/0H"), ancestorsWithSelf.get(2));
assertEquals(HDPath.parsePath("m/0H/1H/0H/1"), ancestorsWithSelf.get(3));
assertEquals(HDPath.parsePath("m/0H/1H/0H/1/0"), ancestorsWithSelf.get(4));
HDPath rootPath = HDPath.parsePath("m/0H");
List<HDPath> empty = rootPath.ancestors();
assertEquals(0, empty.size());
List<HDPath> self = rootPath.ancestors(true);
assertEquals(1, self.size());
assertEquals(rootPath, self.get(0));
HDPath emptyPath = HDPath.m();
List<HDPath> empty2 = emptyPath.ancestors();
assertEquals(0, empty2.size());
List<HDPath> empty3 = emptyPath.ancestors(true);
assertEquals(0, empty3.size());
} |
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException {
if (StringUtils.isBlank(filter)) {
return true;
}
Script script;
try {
script = ENGINE.createScript(filter);
} catch (JexlException e) {
throw new FeedEntryFilterException("Exception while parsing expression " + filter, e);
}
JexlContext context = new MapContext();
context.set("title", entry.getContent().getTitle() == null ? "" : Jsoup.parse(entry.getContent().getTitle()).text().toLowerCase());
context.set("author", entry.getContent().getAuthor() == null ? "" : entry.getContent().getAuthor().toLowerCase());
context.set("content",
entry.getContent().getContent() == null ? "" : Jsoup.parse(entry.getContent().getContent()).text().toLowerCase());
context.set("url", entry.getUrl() == null ? "" : entry.getUrl().toLowerCase());
context.set("categories", entry.getContent().getCategories() == null ? "" : entry.getContent().getCategories().toLowerCase());
context.set("year", Year.now().getValue());
Callable<Object> callable = script.callable(context);
Future<Object> future = executor.submit(callable);
Object result;
try {
result = future.get(config.feedRefresh().filteringExpressionEvaluationTimeout().toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new FeedEntryFilterException("interrupted while evaluating expression " + filter, e);
} catch (ExecutionException e) {
throw new FeedEntryFilterException("Exception while evaluating expression " + filter, e);
} catch (TimeoutException e) {
throw new FeedEntryFilterException("Took too long evaluating expression " + filter, e);
}
try {
return (boolean) result;
} catch (ClassCastException e) {
throw new FeedEntryFilterException(e.getMessage(), e);
}
} | @Test
void dotClassIsDisabled() throws FeedEntryFilterException {
Assertions.assertTrue(service.filterMatchesEntry("null eq ''.class", entry));
} |
@Override
public List<Decorator> findForStream(String streamId) {
return toInterfaceList(coll.find(DBQuery.is(DecoratorImpl.FIELD_STREAM, Optional.of(streamId))).toArray());
} | @Test
@MongoDBFixtures("DecoratorServiceImplTest.json")
public void findForStreamReturnsDecoratorsForStream() {
assertThat(decoratorService.findForStream("000000000000000000000001"))
.hasSize(2)
.extracting(Decorator::id)
.containsExactly("588bcafebabedeadbeef0001", "588bcafebabedeadbeef0002");
assertThat(decoratorService.findForStream("000000000000000000000002")).isEmpty();
} |
@Override
public void readData(ObjectDataInput in) throws IOException {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testReadData() throws Exception {
dataEvent.readData(null);
} |
public static BeamSqlEnvBuilder builder(TableProvider tableProvider) {
return new BeamSqlEnvBuilder(tableProvider);
} | @Test
public void testCreateExternalTableInNestedTableProvider() throws Exception {
TestTableProvider root = new TestTableProvider();
TestTableProvider nested = new TestTableProvider();
TestTableProvider anotherOne = new TestTableProvider();
BeamSqlEnv env =
BeamSqlEnv.builder(root)
.addSchema("nested", nested)
.addSchema("anotherOne", anotherOne)
.setPipelineOptions(PipelineOptionsFactory.create())
.build();
Connection connection = env.connection;
connection.createStatement().execute("CREATE EXTERNAL TABLE nested.person (id INT) TYPE test");
connection.createStatement().execute("INSERT INTO nested.person(id) VALUES (1), (2), (6)");
ResultSet rs = connection.createStatement().executeQuery("SELECT SUM(id) FROM nested.person");
rs.next();
assertEquals(9, rs.getInt(1));
} |
protected Dependency getMainGemspecDependency(Dependency dependency1, Dependency dependency2) {
if (dependency1 != null && dependency2 != null
&& Ecosystem.RUBY.equals(dependency1.getEcosystem())
&& Ecosystem.RUBY.equals(dependency2.getEcosystem())
&& isSameRubyGem(dependency1, dependency2)) {
final File lFile = dependency1.getActualFile();
final File left = lFile.getParentFile();
if (left != null && left.getName().equalsIgnoreCase("specifications")) {
return dependency1;
}
return dependency2;
}
return null;
} | @Test
public void testGetMainGemspecDependency() {
Dependency dependency1 = null;
Dependency dependency2 = null;
DependencyMergingAnalyzer instance = new DependencyMergingAnalyzer();
Dependency expResult = null;
Dependency result = instance.getMainGemspecDependency(dependency1, dependency2);
assertEquals(expResult, result);
dependency1 = new Dependency(new File("specifications/some.gemspec"), true);
dependency1.setPackagePath("path");
dependency1.setEcosystem(Ecosystem.RUBY);
dependency2 = new Dependency(new File("another.gemspec"), true);
dependency2.setEcosystem(Ecosystem.RUBY);
dependency2.setPackagePath("path");
expResult = dependency1;
result = instance.getMainGemspecDependency(dependency1, dependency2);
assertEquals(expResult, result);
dependency1 = new Dependency(new File("some.gemspec"), true);
dependency1.setEcosystem(Ecosystem.RUBY);
dependency1.setPackagePath("path");
dependency2 = new Dependency(new File("specifications/another.gemspec"), true);
dependency2.setEcosystem(Ecosystem.RUBY);
dependency2.setPackagePath("path");
expResult = dependency2;
result = instance.getMainGemspecDependency(dependency1, dependency2);
assertEquals(expResult, result);
} |
@GetMapping("/list")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
public Result<Page<ConfigHistoryInfo>> listConfigHistory(@RequestParam("dataId") String dataId,
@RequestParam("group") String group,
@RequestParam(value = "namespaceId", required = false, defaultValue = StringUtils.EMPTY) String namespaceId,
@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", required = false, defaultValue = "100") Integer pageSize) {
pageSize = Math.min(500, pageSize);
//fix issue #9783
namespaceId = NamespaceUtil.processNamespaceParameter(namespaceId);
return Result.success(historyService.listConfigHistory(dataId, group, namespaceId, pageNo, pageSize));
} | @Test
void testListConfigHistoryWhenNameSpaceIsPublic() throws Exception {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId(TEST_DATA_ID);
configHistoryInfo.setGroup(TEST_GROUP);
configHistoryInfo.setContent(TEST_CONTENT);
configHistoryInfo.setCreatedTime(new Timestamp(new Date().getTime()));
configHistoryInfo.setLastModifiedTime(new Timestamp(new Date().getTime()));
List<ConfigHistoryInfo> configHistoryInfoList = new ArrayList<>();
configHistoryInfoList.add(configHistoryInfo);
Page<ConfigHistoryInfo> page = new Page<>();
page.setTotalCount(15);
page.setPageNumber(1);
page.setPagesAvailable(2);
page.setPageItems(configHistoryInfoList);
when(historyService.listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1, 10)).thenReturn(page);
Result<Page<ConfigHistoryInfo>> pageResult = historyControllerV2.listConfigHistory(TEST_DATA_ID, TEST_GROUP,
TEST_NAMESPACE_ID_PUBLIC, 1, 10);
verify(historyService).listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1, 10);
List<ConfigHistoryInfo> resultList = pageResult.getData().getPageItems();
ConfigHistoryInfo resConfigHistoryInfo = resultList.get(0);
assertEquals(ErrorCode.SUCCESS.getCode(), pageResult.getCode());
assertEquals(configHistoryInfoList.size(), resultList.size());
assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId());
assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup());
assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent());
} |
@Override
public ExportResult<MediaContainerResource> export(UUID jobId, AD authData,
Optional<ExportInformation> exportInfo) throws Exception {
ExportResult<PhotosContainerResource> per = exportPhotos(jobId, authData, exportInfo);
if (per.getThrowable().isPresent()) {
return new ExportResult<>(per.getThrowable().get());
}
ExportResult<VideosContainerResource> ver = exportVideos(jobId, authData, exportInfo);
if (ver.getThrowable().isPresent()) {
return new ExportResult<>(ver.getThrowable().get());
}
return mergeResults(per, ver);
} | @Test
public void shouldHandleErrorInVideos() throws Exception {
Exception throwable = new Exception();
mediaExporter =
new MediaExporterDecorator<>(photosExporter, (id, ad, ei) -> new ExportResult<>(throwable));
MediaContainerResource mcr = new MediaContainerResource(albums, photos, videos);
Optional<ExportInformation> ei = Optional.of(new ExportInformation(null, mcr));
ExportResult<MediaContainerResource> res = mediaExporter.export(null, null, ei);
assertEquals(new ExportResult<>(throwable), res);
} |
public void isNotEqualTo(@Nullable Object unexpected) {
standardIsNotEqualTo(unexpected);
} | @SuppressWarnings("TruthSelfEquals")
@Test
public void isNotEqualToSameInstanceBadEqualsImplementation() {
Object o = new ThrowsOnEquals();
expectFailure.whenTesting().that(o).isNotEqualTo(o);
} |
public List<PlatformSpec> getPlatforms() {
return platforms;
} | @Test
public void testBaseImageSpec_nullCollections() throws JsonProcessingException {
String data = "image: gcr.io/example/jib\n";
BaseImageSpec baseImageSpec = mapper.readValue(data, BaseImageSpec.class);
Assert.assertEquals(ImmutableList.of(), baseImageSpec.getPlatforms());
} |
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(final PushNotification notification) {
final String topic = switch (notification.tokenType()) {
case APN -> bundleId;
case APN_VOIP -> bundleId + ".voip";
default -> throw new IllegalArgumentException("Unsupported token type: " + notification.tokenType());
};
final boolean isVoip = notification.tokenType() == PushNotification.TokenType.APN_VOIP;
final String payload = switch (notification.notificationType()) {
case NOTIFICATION -> {
if (isVoip) {
yield APN_VOIP_NOTIFICATION_PAYLOAD;
} else {
yield notification.urgent() ? APN_NSE_NOTIFICATION_PAYLOAD : APN_BACKGROUND_PAYLOAD;
}
}
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> new SimpleApnsPayloadBuilder()
.setMutableContent(true)
.setLocalizedAlertMessage("APN_Message")
.addCustomProperty("attemptLoginContext", notification.data())
.build();
case CHALLENGE -> new SimpleApnsPayloadBuilder()
.setContentAvailable(true)
.addCustomProperty("challenge", notification.data())
.build();
case RATE_LIMIT_CHALLENGE -> new SimpleApnsPayloadBuilder()
.setContentAvailable(true)
.addCustomProperty("rateLimitChallenge", notification.data())
.build();
};
final PushType pushType = switch (notification.notificationType()) {
case NOTIFICATION -> {
if (isVoip) {
yield PushType.VOIP;
} else {
yield notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
}
}
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> PushType.ALERT;
case CHALLENGE, RATE_LIMIT_CHALLENGE -> PushType.BACKGROUND;
};
final DeliveryPriority deliveryPriority;
if (pushType == PushType.BACKGROUND) {
deliveryPriority = DeliveryPriority.CONSERVE_POWER;
} else {
deliveryPriority = (notification.urgent() || isVoip)
? DeliveryPriority.IMMEDIATE
: DeliveryPriority.CONSERVE_POWER;
}
final String collapseId =
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent() && !isVoip)
? "incoming-message" : null;
final Instant start = Instant.now();
return apnsClient.sendNotification(new SimpleApnsPushNotification(notification.deviceToken(),
topic,
payload,
MAX_EXPIRATION,
deliveryPriority,
pushType,
collapseId))
.whenComplete((response, throwable) -> {
// Note that we deliberately run this small bit of non-blocking measurement on the "send notification" thread
// to avoid any measurement noise that could arise from dispatching to another executor and waiting in its
// queue
SEND_NOTIFICATION_TIMER.record(Duration.between(start, Instant.now()));
})
.thenApplyAsync(response -> {
final boolean accepted;
final Optional<String> rejectionReason;
final boolean unregistered;
if (response.isAccepted()) {
accepted = true;
rejectionReason = Optional.empty();
unregistered = false;
} else {
accepted = false;
rejectionReason = response.getRejectionReason();
unregistered = response.getRejectionReason().map(reason -> "Unregistered".equals(reason) || "BadDeviceToken".equals(reason) || "ExpiredToken".equals(reason))
.orElse(false);
}
return new SendPushNotificationResult(accepted, rejectionReason, unregistered, response.getTokenInvalidationTimestamp());
}, executor);
} | @Test
void testGenericFailure() {
PushNotificationResponse<SimpleApnsPushNotification> response = mock(PushNotificationResponse.class);
when(response.isAccepted()).thenReturn(false);
when(response.getRejectionReason()).thenReturn(Optional.of("BadTopic"));
when(apnsClient.sendNotification(any(SimpleApnsPushNotification.class)))
.thenAnswer(
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN_VOIP,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
final SendPushNotificationResult result = apnSender.sendNotification(pushNotification).join();
ArgumentCaptor<SimpleApnsPushNotification> notification = ArgumentCaptor.forClass(SimpleApnsPushNotification.class);
verify(apnsClient).sendNotification(notification.capture());
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_VOIP_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
assertThat(result.accepted()).isFalse();
assertThat(result.errorCode()).hasValue("BadTopic");
assertThat(result.unregistered()).isFalse();
} |
public boolean initWithCommittedOffsetsIfNeeded(Timer timer) {
final Set<TopicPartition> initializingPartitions = subscriptions.initializingPartitions();
final Map<TopicPartition, OffsetAndMetadata> offsets = fetchCommittedOffsets(initializingPartitions, timer);
// "offsets" will be null if the offset fetch requests did not receive responses within the given timeout
if (offsets == null)
return false;
refreshCommittedOffsets(offsets, this.metadata, this.subscriptions);
return true;
} | @Test
public void testNoCoordinatorDiscoveryIfPositionsKnown() {
assertTrue(coordinator.coordinatorUnknown());
subscriptions.assignFromUser(singleton(t1p));
subscriptions.seek(t1p, 500L);
coordinator.initWithCommittedOffsetsIfNeeded(time.timer(Long.MAX_VALUE));
assertEquals(Collections.emptySet(), subscriptions.initializingPartitions());
assertTrue(subscriptions.hasAllFetchPositions());
assertEquals(500L, subscriptions.position(t1p).offset);
assertTrue(coordinator.coordinatorUnknown());
} |
List<DataflowPackage> stageClasspathElements(
Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) {
return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions);
} | @Test
public void testPackageUploadIsNotSkippedWhenSizesAreDifferent() throws Exception {
Pipe pipe = Pipe.open();
File tmpDirectory = tmpFolder.newFolder("folder");
tmpFolder.newFolder("folder", "empty_directory");
tmpFolder.newFolder("folder", "directory");
makeFileWithContents("folder/file.txt", "This is a test!");
makeFileWithContents("folder/directory/file.txt", "This is also a test!");
when(mockGcsUtil.getObjects(anyListOf(GcsPath.class)))
.thenReturn(
ImmutableList.of(
StorageObjectOrIOException.create(
createStorageObject(STAGING_PATH, Long.MAX_VALUE))));
when(mockGcsUtil.create(any(GcsPath.class), any(GcsUtil.CreateOptions.class)))
.thenReturn(pipe.sink());
defaultPackageUtil.stageClasspathElements(
ImmutableList.of(makeStagedFile(tmpDirectory.getAbsolutePath())),
STAGING_PATH,
createOptions);
verify(mockGcsUtil).getObjects(anyListOf(GcsPath.class));
verify(mockGcsUtil).create(any(GcsPath.class), any(GcsUtil.CreateOptions.class));
verifyNoMoreInteractions(mockGcsUtil);
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
@SuppressWarnings("unchecked")
public void testDecodeDynamicStructDynamicArray2() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000003"
+ "0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000160"
+ "0000000000000000000000000000000000000000000000000000000000000260"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000080"
+ "0000000000000000000000000000000000000000000000000000000000000001"
+ "3400000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000009"
+ "6e6573746564466f6f0000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000080"
+ "0000000000000000000000000000000000000000000000000000000000000001"
+ "3400000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000009"
+ "6e6573746564466f6f0000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000";
assertEquals(
FunctionReturnDecoder.decode(
rawInput,
AbiV2TestFixture.getNarDynamicArrayFunction.getOutputParameters()),
Arrays.asList(
new DynamicArray(
AbiV2TestFixture.Nar.class,
new AbiV2TestFixture.Nar(
new AbiV2TestFixture.Nuu(
new AbiV2TestFixture.Foo("4", "nestedFoo"))),
new AbiV2TestFixture.Nar(
new AbiV2TestFixture.Nuu(
new AbiV2TestFixture.Foo("4", "nestedFoo"))),
new AbiV2TestFixture.Nar(
new AbiV2TestFixture.Nuu(
new AbiV2TestFixture.Foo("", ""))))));
} |
public static String toLowerCase(@Nullable String value) {
if (value == null) {
throw new IllegalArgumentException("String value cannot be null");
}
return value.toLowerCase(Locale.ENGLISH);
} | @Test
public void testToLowerCase() {
//noinspection DataFlowIssue
assertThatThrownBy(() -> toLowerCase(null)).isInstanceOf(IllegalArgumentException.class);
assertThat(toLowerCase("")).isEqualTo("");
assertThat(toLowerCase(" ")).isEqualTo(" ");
assertThat(toLowerCase("Hello")).isEqualTo("hello");
} |
public Set<? extends AuthenticationRequest> getRequest(final Host bookmark, final LoginCallback prompt)
throws LoginCanceledException {
final StringBuilder url = new StringBuilder();
url.append(bookmark.getProtocol().getScheme().toString()).append("://");
url.append(bookmark.getHostname());
if(!(bookmark.getProtocol().getScheme().getPort() == bookmark.getPort())) {
url.append(":").append(bookmark.getPort());
}
final String context = PathNormalizer.normalize(bookmark.getProtocol().getContext());
// Custom authentication context
url.append(context);
if(bookmark.getProtocol().getDefaultHostname().endsWith("identity.api.rackspacecloud.com")
|| bookmark.getHostname().endsWith("identity.api.rackspacecloud.com")) {
return Collections.singleton(new Authentication20RAXUsernameKeyRequest(
URI.create(url.toString()),
bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword(), null)
);
}
final LoginOptions options = new LoginOptions(bookmark.getProtocol()).password(false).anonymous(false).publickey(false);
if(context.contains("1.0")) {
return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()),
bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword()));
}
else if(context.contains("1.1")) {
return Collections.singleton(new Authentication11UsernameKeyRequest(URI.create(url.toString()),
bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword()));
}
else if(context.contains("2.0")) {
// Prompt for tenant
final String user;
final String tenant;
if(StringUtils.contains(bookmark.getCredentials().getUsername(), ':')) {
final String[] parts = StringUtils.splitPreserveAllTokens(bookmark.getCredentials().getUsername(), ':');
tenant = parts[0];
user = parts[1];
}
else {
user = bookmark.getCredentials().getUsername();
tenant = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(),
LocaleFactory.localizedString("Provide additional login credentials", "Credentials"),
LocaleFactory.localizedString("Tenant Name", "Mosso"), options
.usernamePlaceholder(LocaleFactory.localizedString("Tenant Name", "Mosso"))).getUsername();
// Save tenant in username
bookmark.getCredentials().setUsername(String.format("%s:%s", tenant, bookmark.getCredentials().getUsername()));
}
final Set<AuthenticationRequest> requests = new LinkedHashSet<>();
requests.add(new Authentication20UsernamePasswordRequest(
URI.create(url.toString()),
user, bookmark.getCredentials().getPassword(), tenant)
);
requests.add(new Authentication20UsernamePasswordTenantIdRequest(
URI.create(url.toString()),
user, bookmark.getCredentials().getPassword(), tenant)
);
requests.add(new Authentication20AccessKeySecretKeyRequest(
URI.create(url.toString()),
user, bookmark.getCredentials().getPassword(), tenant));
return requests;
}
else if(context.contains("3")) {
// Prompt for project
final String user;
final String project;
final String domain;
if(StringUtils.contains(bookmark.getCredentials().getUsername(), ':')) {
final String[] parts = StringUtils.splitPreserveAllTokens(bookmark.getCredentials().getUsername(), ':');
if(parts.length == 3) {
project = parts[0];
domain = parts[1];
user = parts[2];
}
else {
project = parts[0];
user = parts[1];
domain = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(),
LocaleFactory.localizedString("Provide additional login credentials", "Credentials"),
LocaleFactory.localizedString("Project Domain Name", "Mosso"), options
.usernamePlaceholder(LocaleFactory.localizedString("Project Domain Name", "Mosso"))).getUsername();
// Save project name and domain in username
bookmark.getCredentials().setUsername(String.format("%s:%s:%s", project, domain, bookmark.getCredentials().getUsername()));
}
}
else {
user = bookmark.getCredentials().getUsername();
final Credentials projectName = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(),
LocaleFactory.localizedString("Provide additional login credentials", "Credentials"),
LocaleFactory.localizedString("Project Name", "Mosso"), options
.usernamePlaceholder(LocaleFactory.localizedString("Project Name", "Mosso")));
if(StringUtils.contains(bookmark.getCredentials().getUsername(), ':')) {
final String[] parts = StringUtils.splitPreserveAllTokens(projectName.getUsername(), ':');
project = parts[0];
domain = parts[1];
}
else {
project = projectName.getUsername();
domain = prompt.prompt(bookmark, bookmark.getCredentials().getUsername(),
LocaleFactory.localizedString("Provide additional login credentials", "Credentials"),
LocaleFactory.localizedString("Project Domain Name", "Mosso"), options
.usernamePlaceholder(LocaleFactory.localizedString("Project Domain Name", "Mosso"))).getUsername();
}
// Save project name and domain in username
bookmark.getCredentials().setUsername(String.format("%s:%s:%s", project, domain, bookmark.getCredentials().getUsername()));
}
final Set<AuthenticationRequest> requests = new LinkedHashSet<>();
requests.add(new Authentication3UsernamePasswordProjectRequest(
URI.create(url.toString()),
user, bookmark.getCredentials().getPassword(), project, domain)
);
return requests;
}
else {
log.warn(String.format("Unknown context version in %s. Default to v1 authentication.", context));
// Default to 1.0
return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()),
bookmark.getCredentials().getUsername(), bookmark.getCredentials().getPassword()));
}
} | @Test
public void testGetDefault2() throws Exception {
final SwiftAuthenticationService s = new SwiftAuthenticationService();
final SwiftProtocol protocol = new SwiftProtocol() {
@Override
public String getContext() {
return "/v2.0/tokens";
}
};
assertEquals(Client.AuthVersion.v20,
s.getRequest(new Host(protocol, "region-b.geo-1.identity.hpcloudsvc.com", new Credentials("tenant:u", "P")),
new DisabledLoginCallback()).iterator().next().getVersion());
assertEquals(Client.AuthVersion.v20,
s.getRequest(new Host(protocol, "myhost", new Credentials("tenant:u", "P")),
new DisabledLoginCallback()).iterator().next().getVersion());
assertEquals(Authentication20UsernamePasswordRequest.class,
new ArrayList<AuthenticationRequest>(s.getRequest(new Host(protocol, "myhost", new Credentials("tenant:u", "P")),
new DisabledLoginCallback())).get(0).getClass());
} |
@DataPermission(enable = false) // 忽略数据权限,避免因为过滤,导致找不到候选人
public Set<Long> calculateUsers(DelegateExecution execution) {
Integer strategy = BpmnModelUtils.parseCandidateStrategy(execution.getCurrentFlowElement());
String param = BpmnModelUtils.parseCandidateParam(execution.getCurrentFlowElement());
// 1.1 计算任务的候选人
Set<Long> userIds = getCandidateStrategy(strategy).calculateUsers(execution, param);
// 1.2 移除被禁用的用户
removeDisableUsers(userIds);
// 2. 校验是否有候选人
if (CollUtil.isEmpty(userIds)) {
log.error("[calculateUsers][流程任务({}/{}/{}) 任务规则({}/{}) 找不到候选人]", execution.getId(),
execution.getProcessDefinitionId(), execution.getCurrentActivityId(), strategy, param);
throw exception(TASK_CREATE_FAIL_NO_CANDIDATE_USER);
}
return userIds;
} | @Test
public void testCalculateUsers() {
// 准备参数
String param = "1,2";
DelegateExecution execution = mock(DelegateExecution.class);
// mock 方法(DelegateExecution)
UserTask userTask = mock(UserTask.class);
when(execution.getCurrentFlowElement()).thenReturn(userTask);
when(userTask.getAttributeValue(eq(BpmnModelConstants.NAMESPACE), eq(BpmnModelConstants.USER_TASK_CANDIDATE_STRATEGY)))
.thenReturn(BpmTaskCandidateStrategyEnum.USER.getStrategy().toString());
when(userTask.getAttributeValue(eq(BpmnModelConstants.NAMESPACE), eq(BpmnModelConstants.USER_TASK_CANDIDATE_PARAM)))
.thenReturn(param);
// mock 方法(adminUserApi)
AdminUserRespDTO user1 = randomPojo(AdminUserRespDTO.class, o -> o.setId(1L)
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
AdminUserRespDTO user2 = randomPojo(AdminUserRespDTO.class, o -> o.setId(2L)
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
Map<Long, AdminUserRespDTO> userMap = MapUtil.builder(user1.getId(), user1)
.put(user2.getId(), user2).build();
when(adminUserApi.getUserMap(eq(asSet(1L, 2L)))).thenReturn(userMap);
// 调用
Set<Long> results = taskCandidateInvoker.calculateUsers(execution);
// 断言
assertEquals(asSet(1L, 2L), results);
} |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws
RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final EndTransactionRequestHeader requestHeader =
(EndTransactionRequestHeader) request.decodeCommandCustomHeader(EndTransactionRequestHeader.class);
LOGGER.debug("Transaction request:{}", requestHeader);
if (BrokerRole.SLAVE == brokerController.getMessageStoreConfig().getBrokerRole()) {
response.setCode(ResponseCode.SLAVE_NOT_AVAILABLE);
LOGGER.warn("Message store is slave mode, so end transaction is forbidden. ");
return response;
}
if (requestHeader.getFromTransactionCheck()) {
switch (requestHeader.getCommitOrRollback()) {
case MessageSysFlag.TRANSACTION_NOT_TYPE: {
LOGGER.warn("Check producer[{}] transaction state, but it's pending status."
+ "RequestHeader: {} Remark: {}",
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
requestHeader.toString(),
request.getRemark());
return null;
}
case MessageSysFlag.TRANSACTION_COMMIT_TYPE: {
LOGGER.warn("Check producer[{}] transaction state, the producer commit the message."
+ "RequestHeader: {} Remark: {}",
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
requestHeader.toString(),
request.getRemark());
break;
}
case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE: {
LOGGER.warn("Check producer[{}] transaction state, the producer rollback the message."
+ "RequestHeader: {} Remark: {}",
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
requestHeader.toString(),
request.getRemark());
break;
}
default:
return null;
}
} else {
switch (requestHeader.getCommitOrRollback()) {
case MessageSysFlag.TRANSACTION_NOT_TYPE: {
LOGGER.warn("The producer[{}] end transaction in sending message, and it's pending status."
+ "RequestHeader: {} Remark: {}",
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
requestHeader.toString(),
request.getRemark());
return null;
}
case MessageSysFlag.TRANSACTION_COMMIT_TYPE: {
break;
}
case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE: {
LOGGER.warn("The producer[{}] end transaction in sending message, rollback the message."
+ "RequestHeader: {} Remark: {}",
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
requestHeader.toString(),
request.getRemark());
break;
}
default:
return null;
}
}
OperationResult result = new OperationResult();
if (MessageSysFlag.TRANSACTION_COMMIT_TYPE == requestHeader.getCommitOrRollback()) {
result = this.brokerController.getTransactionalMessageService().commitMessage(requestHeader);
if (result.getResponseCode() == ResponseCode.SUCCESS) {
if (rejectCommitOrRollback(requestHeader, result.getPrepareMessage())) {
response.setCode(ResponseCode.ILLEGAL_OPERATION);
LOGGER.warn("Message commit fail [producer end]. currentTimeMillis - bornTime > checkImmunityTime, msgId={},commitLogOffset={}, wait check",
requestHeader.getMsgId(), requestHeader.getCommitLogOffset());
return response;
}
RemotingCommand res = checkPrepareMessage(result.getPrepareMessage(), requestHeader);
if (res.getCode() == ResponseCode.SUCCESS) {
MessageExtBrokerInner msgInner = endMessageTransaction(result.getPrepareMessage());
msgInner.setSysFlag(MessageSysFlag.resetTransactionValue(msgInner.getSysFlag(), requestHeader.getCommitOrRollback()));
msgInner.setQueueOffset(requestHeader.getTranStateTableOffset());
msgInner.setPreparedTransactionOffset(requestHeader.getCommitLogOffset());
msgInner.setStoreTimestamp(result.getPrepareMessage().getStoreTimestamp());
MessageAccessor.clearProperty(msgInner, MessageConst.PROPERTY_TRANSACTION_PREPARED);
RemotingCommand sendResult = sendFinalMessage(msgInner);
if (sendResult.getCode() == ResponseCode.SUCCESS) {
this.brokerController.getTransactionalMessageService().deletePrepareMessage(result.getPrepareMessage());
// successful committed, then total num of half-messages minus 1
this.brokerController.getTransactionalMessageService().getTransactionMetrics().addAndGet(msgInner.getTopic(), -1);
BrokerMetricsManager.commitMessagesTotal.add(1, BrokerMetricsManager.newAttributesBuilder()
.put(LABEL_TOPIC, msgInner.getTopic())
.build());
// record the commit latency.
Long commitLatency = (System.currentTimeMillis() - result.getPrepareMessage().getBornTimestamp()) / 1000;
BrokerMetricsManager.transactionFinishLatency.record(commitLatency, BrokerMetricsManager.newAttributesBuilder()
.put(LABEL_TOPIC, msgInner.getTopic())
.build());
}
return sendResult;
}
return res;
}
} else if (MessageSysFlag.TRANSACTION_ROLLBACK_TYPE == requestHeader.getCommitOrRollback()) {
result = this.brokerController.getTransactionalMessageService().rollbackMessage(requestHeader);
if (result.getResponseCode() == ResponseCode.SUCCESS) {
if (rejectCommitOrRollback(requestHeader, result.getPrepareMessage())) {
response.setCode(ResponseCode.ILLEGAL_OPERATION);
LOGGER.warn("Message rollback fail [producer end]. currentTimeMillis - bornTime > checkImmunityTime, msgId={},commitLogOffset={}, wait check",
requestHeader.getMsgId(), requestHeader.getCommitLogOffset());
return response;
}
RemotingCommand res = checkPrepareMessage(result.getPrepareMessage(), requestHeader);
if (res.getCode() == ResponseCode.SUCCESS) {
this.brokerController.getTransactionalMessageService().deletePrepareMessage(result.getPrepareMessage());
// roll back, then total num of half-messages minus 1
this.brokerController.getTransactionalMessageService().getTransactionMetrics().addAndGet(result.getPrepareMessage().getProperty(MessageConst.PROPERTY_REAL_TOPIC), -1);
BrokerMetricsManager.rollBackMessagesTotal.add(1, BrokerMetricsManager.newAttributesBuilder()
.put(LABEL_TOPIC, result.getPrepareMessage().getProperty(MessageConst.PROPERTY_REAL_TOPIC))
.build());
}
return res;
}
}
response.setCode(result.getResponseCode());
response.setRemark(result.getResponseRemark());
return response;
} | @Test
public void testProcessRequest() throws RemotingCommandException {
when(transactionMsgService.commitMessage(any(EndTransactionRequestHeader.class))).thenReturn(createResponse(ResponseCode.SUCCESS));
when(messageStore.putMessage(any(MessageExtBrokerInner.class)))
.thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, createAppendMessageResult(AppendMessageStatus.PUT_OK)));
RemotingCommand request = createEndTransactionMsgCommand(MessageSysFlag.TRANSACTION_COMMIT_TYPE, false);
RemotingCommand response = endTransactionProcessor.processRequest(handlerContext, request);
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
assertThat(brokerController.getBrokerStatsManager().getStatsItem(Stats.BROKER_PUT_NUMS, brokerController.getBrokerConfig().getBrokerClusterName()).getValue().sum()).isEqualTo(1);
assertThat(brokerController.getBrokerStatsManager().getStatsItem(Stats.TOPIC_PUT_NUMS, TOPIC).getValue().sum()).isEqualTo(1L);
assertThat(brokerController.getBrokerStatsManager().getStatsItem(Stats.TOPIC_PUT_SIZE, TOPIC).getValue().sum()).isEqualTo(1L);
} |
@Override
@MethodNotAvailable
public CompletionStage<Boolean> deleteAsync(K key) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testDeleteAsync() {
adapter.deleteAsync(23);
} |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 1) {
if ("dateIntToTs".equals(methodName)) {
return dateIntToTs(args[0]);
} else if ("tsToDateInt".equals(methodName)) {
return tsToDateInt(args[0]);
}
} else if (args.length == 2) {
if ("incrementDateInt".equals(methodName)) {
return incrementDateInt(args[0], args[1]);
} else if ("timeoutForDateTimeDeadline".equals(methodName)) {
return timeoutForDateTimeDeadline(args[0], args[1]);
} else if ("timeoutForDateIntDeadline".equals(methodName)) {
return timeoutForDateIntDeadline(args[0], args[1]);
}
} else if (args.length == 3) {
if ("dateIntsBetween".equals(methodName)) {
return dateIntsBetween(args[0], args[1], args[2]);
} else if ("intsBetween".equals(methodName)) {
return intsBetween(args[0], args[1], args[2]);
}
} else if (args.length == 5 && "dateIntHourToTs".equals(methodName)) {
return dateIntHourToTs(args);
}
throw new UnsupportedOperationException(
type()
+ " DO NOT support calling method: "
+ methodName
+ " with args: "
+ Arrays.toString(args));
} | @Test(expected = ClassCastException.class)
public void testCallIncrementDateIntInvalid() {
SelUtilFunc.INSTANCE.call(
"incrementDateInt", new SelType[] {SelString.of("20190101"), SelString.of("5")});
} |
@Asn1Property(tagNo = 0x30, converter = DigestsConverter.class)
public Map<Integer, byte[]> getDigests() {
return digests;
} | @Test
public void readDl1Cms() throws Exception {
final LdsSecurityObject ldsSecurityObject = mapper.read(
readFromCms("dl1"), LdsSecurityObject.class);
assertEquals(ImmutableSet.of(1, 5, 6, 11, 12, 13), ldsSecurityObject.getDigests().keySet());
} |
@VisibleForTesting
void retryRebalanceTable(String tableNameWithType, Map<String, Map<String, String>> allJobMetadata)
throws Exception {
// Skip retry for the table if rebalance job is still running or has completed, in specific:
// 1) Skip retry if any rebalance job is actively running. Being actively running means the job is at IN_PROGRESS
// status, and has updated its status kept in ZK within the heartbeat timeout. It's possible that more than one
// rebalance jobs are running for the table, but that's fine with idempotent rebalance algorithm.
// 2) Skip retry if the most recently started rebalance job has completed with DONE or NO_OP. It's possible that
// jobs started earlier may be still running, but they are ignored here.
//
// Otherwise, we can get a list of failed rebalance jobs, i.e. those at FAILED status; or IN_PROGRESS status but
// haven't updated their status kept in ZK within the heartbeat timeout. For those candidate jobs to retry:
// 1) Firstly, group them by the original jobIds they retry for so that we can skip those exceeded maxRetry.
// 2) For the remaining jobs, we take the one started most recently and retry it with its original configs.
// 3) If configured, we can abort the other rebalance jobs for the table by setting their status to FAILED.
Map<String/*original jobId*/, Set<Pair<TableRebalanceContext/*job attempts*/, Long
/*startTime*/>>> candidateJobs = getCandidateJobs(tableNameWithType, allJobMetadata);
if (candidateJobs.isEmpty()) {
LOGGER.info("Found no failed rebalance jobs for table: {}. Skip retry", tableNameWithType);
return;
}
_controllerMetrics.addMeteredTableValue(tableNameWithType, ControllerMeter.TABLE_REBALANCE_FAILURE_DETECTED, 1L);
Pair<TableRebalanceContext, Long> jobContextAndStartTime = getLatestJob(candidateJobs);
if (jobContextAndStartTime == null) {
LOGGER.info("Rebalance has been retried too many times for table: {}. Skip retry", tableNameWithType);
_controllerMetrics.addMeteredTableValue(tableNameWithType, ControllerMeter.TABLE_REBALANCE_RETRY_TOO_MANY_TIMES,
1L);
return;
}
TableRebalanceContext jobCtx = jobContextAndStartTime.getLeft();
String prevJobId = jobCtx.getJobId();
RebalanceConfig rebalanceConfig = jobCtx.getConfig();
long jobStartTimeMs = jobContextAndStartTime.getRight();
long retryDelayMs = getRetryDelayInMs(rebalanceConfig.getRetryInitialDelayInMs(), jobCtx.getAttemptId());
if (jobStartTimeMs + retryDelayMs > System.currentTimeMillis()) {
LOGGER.info("Delay retry for failed rebalance job: {} that started at: {}, by: {}ms", prevJobId, jobStartTimeMs,
retryDelayMs);
return;
}
abortExistingJobs(tableNameWithType, _pinotHelixResourceManager);
// Get tableConfig only when the table needs to retry rebalance, and get it before submitting rebalance to another
// thread, in order to avoid unnecessary ZK reads and making too many ZK reads in a short time.
TableConfig tableConfig = _pinotHelixResourceManager.getTableConfig(tableNameWithType);
Preconditions.checkState(tableConfig != null, "Failed to find table config for table: %s", tableNameWithType);
_executorService.submit(() -> {
// Retry rebalance in another thread as rebalance can take time.
try {
retryRebalanceTableWithContext(tableNameWithType, tableConfig, jobCtx);
} catch (Throwable t) {
LOGGER.error("Failed to retry rebalance for table: {} asynchronously", tableNameWithType, t);
}
});
} | @Test
public void testRetryRebalance()
throws Exception {
String tableName = "table01";
LeadControllerManager leadController = mock(LeadControllerManager.class);
ControllerMetrics metrics = mock(ControllerMetrics.class);
ExecutorService exec = MoreExecutors.newDirectExecutorService();
ControllerConf cfg = new ControllerConf();
Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
// Original job run as job1, and all its retry jobs failed too.
RebalanceConfig jobCfg = new RebalanceConfig();
jobCfg.setMaxAttempts(4);
TableRebalanceProgressStats stats = new TableRebalanceProgressStats();
stats.setStatus(RebalanceResult.Status.FAILED);
stats.setStartTimeMs(1000);
TableRebalanceContext jobCtx = TableRebalanceContext.forInitialAttempt("job1", jobCfg);
Map<String, String> jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, "job1", stats, jobCtx);
allJobMetadata.put("job1", jobMetadata);
// 3 failed retry runs for job1
jobMetadata = createDummyJobMetadata(tableName, "job1", 2, 1100, RebalanceResult.Status.FAILED);
allJobMetadata.put("job1_2", jobMetadata);
jobMetadata = createDummyJobMetadata(tableName, "job1", 3, 1200, RebalanceResult.Status.FAILED);
allJobMetadata.put("job1_3", jobMetadata);
jobMetadata = createDummyJobMetadata(tableName, "job1", 4, 5300, RebalanceResult.Status.FAILED);
allJobMetadata.put("job1_4", jobMetadata);
// Original job run as job2, and its retry job job2_1 completed.
jobCfg = new RebalanceConfig();
jobCfg.setMaxAttempts(4);
stats = new TableRebalanceProgressStats();
stats.setStatus(RebalanceResult.Status.FAILED);
stats.setStartTimeMs(2000);
jobCtx = TableRebalanceContext.forInitialAttempt("job2", jobCfg);
jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, "job2", stats, jobCtx);
allJobMetadata.put("job2", jobMetadata);
jobMetadata = createDummyJobMetadata(tableName, "job2", 2, 2100, RebalanceResult.Status.DONE);
allJobMetadata.put("job2_2", jobMetadata);
// Original job run as job3, and failed to send out heartbeat in time.
jobCfg = new RebalanceConfig();
jobCfg.setMaxAttempts(4);
stats = new TableRebalanceProgressStats();
stats.setStatus(RebalanceResult.Status.IN_PROGRESS);
stats.setStartTimeMs(3000);
jobCtx = TableRebalanceContext.forInitialAttempt("job3", jobCfg);
jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, "job3", stats, jobCtx);
jobMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS, "3000");
allJobMetadata.put("job3", jobMetadata);
TableConfig tableConfig = mock(TableConfig.class);
PinotHelixResourceManager helixManager = mock(PinotHelixResourceManager.class);
when(helixManager.getTableConfig(tableName)).thenReturn(tableConfig);
when(helixManager.getAllJobs(any(), any())).thenReturn(allJobMetadata);
RebalanceChecker checker = new RebalanceChecker(helixManager, leadController, cfg, metrics, exec);
// Although job1_3 was submitted most recently but job1 had exceeded maxAttempts. Chose job3 to retry, which got
// stuck at in progress status.
checker.retryRebalanceTable(tableName, allJobMetadata);
// The new retry job is for job3 and attemptId is increased to 2.
ArgumentCaptor<ZkBasedTableRebalanceObserver> observerCaptor =
ArgumentCaptor.forClass(ZkBasedTableRebalanceObserver.class);
verify(helixManager, times(1)).rebalanceTable(eq(tableName), any(), anyString(), any(), observerCaptor.capture());
ZkBasedTableRebalanceObserver observer = observerCaptor.getValue();
jobCtx = observer.getTableRebalanceContext();
assertEquals(jobCtx.getOriginalJobId(), "job3");
assertEquals(jobCtx.getAttemptId(), 2);
} |
@Override
public int hashCode() {
return Objects.hash(path, json);
} | @Test
void testHashCode() {
ArchivedJson original = new ArchivedJson("path", "json");
ArchivedJson twin = new ArchivedJson("path", "json");
assertThat(original).isEqualTo(original);
assertThat(twin).isEqualTo(original);
assertThat(twin).hasSameHashCodeAs(original);
} |
@SafeVarargs
public static <T> Set<T> intersectionDistinct(Collection<T> coll1, Collection<T> coll2, Collection<T>... otherColls) {
final Set<T> result;
if (isEmpty(coll1) || isEmpty(coll2)) {
// 有一个空集合就直接返回空
return new LinkedHashSet<>();
} else {
result = new LinkedHashSet<>(coll1);
}
if (ArrayUtil.isNotEmpty(otherColls)) {
for (Collection<T> otherColl : otherColls) {
if (isNotEmpty(otherColl)) {
result.retainAll(otherColl);
} else {
// 有一个空集合就直接返回空
return new LinkedHashSet<>();
}
}
}
result.retainAll(coll2);
return result;
} | @Test
public void intersectionDistinctTest() {
final ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
final ArrayList<String> list3 = CollUtil.newArrayList();
final Collection<String> intersectionDistinct = CollUtil.intersectionDistinct(list1, list2);
assertEquals(CollUtil.newLinkedHashSet("a", "b", "c", "d"), intersectionDistinct);
final Collection<String> intersectionDistinct2 = CollUtil.intersectionDistinct(list1, list2, list3);
assertTrue(intersectionDistinct2.isEmpty());
} |
Collection<OutputFile> compile() {
List<OutputFile> out = new ArrayList<>(queue.size() + 1);
for (Schema schema : queue) {
out.add(compile(schema));
}
if (protocol != null) {
out.add(compileInterface(protocol));
}
return out;
} | @Test
void logicalTypesWithMultipleFieldsDateTime() throws Exception {
Schema logicalTypesWithMultipleFields = new Schema.Parser()
.parse(new File("src/test/resources/logical_types_with_multiple_fields.avsc"));
assertCompilesWithJavaCompiler(new File(this.outputFile, "testLogicalTypesWithMultipleFieldsDateTime"),
new SpecificCompiler(logicalTypesWithMultipleFields).compile());
} |
public Rule<ProjectNode> projectNodeRule()
{
return new PullUpExpressionInLambdaProjectNodeRule();
} | @Test
public void testIfExpressionOnValue()
{
tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).projectNodeRule())
.setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true")
.on(p ->
{
p.variable("col1", new ArrayType(BOOLEAN));
p.variable("col2", new ArrayType(BIGINT));
p.variable("col3");
return p.project(
Assignments.builder().put(p.variable("expr", VARCHAR), p.rowExpression(
"transform(col1, x -> if(x, col3 - 2, 0))")).build(),
p.values(p.variable("col1", new ArrayType(BOOLEAN)), p.variable("col2", new ArrayType(BIGINT)), p.variable("col3")));
}).doesNotFire();
} |
@Override
public void write(T record) {
recordConsumer.startMessage();
try {
messageWriter.writeTopLevelMessage(record);
} catch (RuntimeException e) {
Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record;
LOG.error("Cannot write message {}: {}", e.getMessage(), m);
throw e;
}
recordConsumer.endMessage();
} | @Test
public void testProto3DateTimeMessageRoundTrip() throws Exception {
Timestamp timestamp = Timestamps.parse("2021-05-02T15:04:03.748Z");
LocalDate date = LocalDate.of(2021, 5, 2);
LocalTime time = LocalTime.of(15, 4, 3, 748_000_000);
com.google.type.Date protoDate = com.google.type.Date.newBuilder()
.setYear(date.getYear())
.setMonth(date.getMonthValue())
.setDay(date.getDayOfMonth())
.build();
com.google.type.TimeOfDay protoTime = com.google.type.TimeOfDay.newBuilder()
.setHours(time.getHour())
.setMinutes(time.getMinute())
.setSeconds(time.getSecond())
.setNanos(time.getNano())
.build();
TestProto3.DateTimeMessage msg = TestProto3.DateTimeMessage.newBuilder()
.setTimestamp(timestamp)
.setDate(protoDate)
.setTime(protoTime)
.build();
// Write them out and read them back
Path tmpFilePath = TestUtils.someTemporaryFilePath();
ParquetWriter<MessageOrBuilder> writer = ProtoParquetWriter.<MessageOrBuilder>builder(tmpFilePath)
.withMessage(TestProto3.DateTimeMessage.class)
.config(ProtoWriteSupport.PB_UNWRAP_PROTO_WRAPPERS, "true")
.build();
writer.write(msg);
writer.close();
List<TestProto3.DateTimeMessage> gotBack =
TestUtils.readMessages(tmpFilePath, TestProto3.DateTimeMessage.class);
TestProto3.DateTimeMessage gotBackFirst = gotBack.get(0);
assertEquals(timestamp, gotBackFirst.getTimestamp());
assertEquals(protoDate, gotBackFirst.getDate());
assertEquals(protoTime, gotBackFirst.getTime());
} |
@Override
public void updateInputPartitions(final Set<TopicPartition> topicPartitions, final Map<String, List<String>> allTopologyNodesToSourceTopics) {
super.updateInputPartitions(topicPartitions, allTopologyNodesToSourceTopics);
partitionGroup.updatePartitions(topicPartitions, recordQueueCreator::createQueue);
processorContext.getProcessorMetadata().setNeedsCommit(true);
} | @Test
public void shouldUpdatePartitions() {
when(stateManager.taskId()).thenReturn(taskId);
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
task = createStatelessTask(createConfig());
final Set<TopicPartition> newPartitions = new HashSet<>(task.inputPartitions());
newPartitions.add(new TopicPartition("newTopic", 0));
task.updateInputPartitions(newPartitions, mkMap(
mkEntry(source1.name(), asList(topic1, "newTopic")),
mkEntry(source2.name(), singletonList(topic2)))
);
assertThat(task.inputPartitions(), equalTo(newPartitions));
} |
@PublicAPI(usage = ACCESS)
public URI asURI() {
return uri.toURI();
} | @Test
public void asUri() throws URISyntaxException {
URL url = getClass().getResource(".");
assertThat(Location.of(url).asURI()).isEqualTo(url.toURI());
} |
public static Object convert(final Object o) {
if (o == null) {
return RubyUtil.RUBY.getNil();
}
final Class<?> cls = o.getClass();
final Valuefier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return converter.convert(o);
}
return fallbackConvert(o, cls);
} | @Test
public void testArrayJavaProxy() {
IRubyObject[] array = new IRubyObject[]{RubyString.newString(RubyUtil.RUBY, "foo")};
RubyClass proxyClass = (RubyClass) Java.getProxyClass(RubyUtil.RUBY, String[].class);
ArrayJavaProxy ajp = new ArrayJavaProxy(RubyUtil.RUBY, proxyClass, array);
Object result = Valuefier.convert(ajp);
assertEquals(ConvertedList.class, result.getClass());
List<Object> a = (ConvertedList) result;
} |
public QueuePath getParentObject() {
return hasParent() ? new QueuePath(parent) : null;
} | @Test
public void testGetParentObject() {
Assert.assertEquals(new QueuePath("root.level_1.level_2"),
TEST_QUEUE_PATH.getParentObject());
Assert.assertEquals(ROOT_PATH, new QueuePath("root.level_1").getParentObject());
Assert.assertNull(ROOT_PATH.getParentObject());
} |
public static String getScesimFileName(String fileFullPath) {
if (fileFullPath == null) {
return null;
}
int idx = fileFullPath.replace("\\", "/").lastIndexOf('/');
String fileName = idx >= 0 ? fileFullPath.substring(idx + 1) : fileFullPath;
return fileName.endsWith(ConstantsHolder.SCESIM_EXTENSION) ?
fileName.substring(0, fileName.lastIndexOf(ConstantsHolder.SCESIM_EXTENSION)) :
fileName;
} | @Test
public void getScesimFileName() {
assertThat(AbstractScenarioRunner.getScesimFileName("src/test/Test.scesim")).isEqualTo("Test");
assertThat(AbstractScenarioRunner.getScesimFileName("Test.scesim")).isEqualTo("Test");
assertThat(AbstractScenarioRunner.getScesimFileName("Test")).isEqualTo("Test");
assertThat(AbstractScenarioRunner.getScesimFileName("src/test/Test.1.scesim")).isEqualTo("Test.1");
assertThat(AbstractScenarioRunner.getScesimFileName(null)).isEqualTo(null);
} |
@Override
public DbEntitiesCatalog get() {
final Stopwatch stopwatch = Stopwatch.createStarted();
final DbEntitiesCatalog catalog = scan(packagesToScan, packagesToExclude, chainingClassLoader);
stopwatch.stop();
LOG.info("{} entities have been scanned and added to DB Entity Catalog, it took {}", catalog.size(), stopwatch);
return catalog;
} | @Test
void testScansEntitiesWithCustomTitleFieldProperly() {
DbEntitiesScanner scanner = new DbEntitiesScanner(new String[]{"org.graylog2.users"}, new String[]{});
final DbEntitiesCatalog dbEntitiesCatalog = scanner.get();
final DbEntityCatalogEntry entryByCollectionName = dbEntitiesCatalog.getByCollectionName(UserImpl.COLLECTION_NAME).get();
assertEquals(new DbEntityCatalogEntry(UserImpl.COLLECTION_NAME, UserImpl.USERNAME, UserImpl.class, USERS_READ), entryByCollectionName);
} |
@Override
public ProjectRepositories load(String projectKey, @Nullable String branchBase) {
GetRequest request = new GetRequest(getUrl(projectKey, branchBase));
try (WsResponse response = wsClient.call(request)) {
try (InputStream is = response.contentStream()) {
return processStream(is);
} catch (IOException e) {
throw new IllegalStateException("Couldn't load project repository for " + projectKey, e);
}
} catch (RuntimeException e) {
if (shouldThrow(e)) {
throw e;
}
LOG.debug("Project repository not available - continuing without it");
return new SingleProjectRepository();
}
} | @Test
public void passAndEncodeProjectKeyParameter() {
loader.load(PROJECT_KEY, null);
WsTestUtil.verifyCall(wsClient, "/batch/project.protobuf?key=foo%3F");
} |
void handleLine(final String line) {
final String trimmedLine = Optional.ofNullable(line).orElse("").trim();
if (trimmedLine.isEmpty()) {
return;
}
handleStatements(trimmedLine);
} | @Test
public void shouldThrowWhenTryingToSetDeniedProperty() throws Exception {
// Given
final KsqlRestClient mockRestClient = givenMockRestClient();
when(mockRestClient.makeIsValidRequest("ksql.service.id"))
.thenReturn(RestResponse.erroneous(
NOT_ACCEPTABLE.code(),
new KsqlErrorMessage(Errors.toErrorCode(NOT_ACCEPTABLE.code()),
"Property cannot be set")));
// When:
assertThrows(IllegalArgumentException.class, () ->
localCli.handleLine("set 'ksql.service.id'='test';"));
} |
@Override
public String lbType() {
return "Random";
} | @Test
public void lbType() {
Assert.assertEquals(new RandomLoadbalancer().lbType(), "Random");
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为操作一个部门,涉及到多个缓存
public Long createDept(DeptSaveReqVO createReqVO) {
if (createReqVO.getParentId() == null) {
createReqVO.setParentId(DeptDO.PARENT_ID_ROOT);
}
// 校验父部门的有效性
validateParentDept(null, createReqVO.getParentId());
// 校验部门名的唯一性
validateDeptNameUnique(null, createReqVO.getParentId(), createReqVO.getName());
// 插入部门
DeptDO dept = BeanUtils.toBean(createReqVO, DeptDO.class);
deptMapper.insert(dept);
return dept.getId();
} | @Test
public void testCreateDept() {
// 准备参数
DeptSaveReqVO reqVO = randomPojo(DeptSaveReqVO.class, o -> {
o.setId(null); // 防止 id 被设置
o.setParentId(DeptDO.PARENT_ID_ROOT);
o.setStatus(randomCommonStatus());
});
// 调用
Long deptId = deptService.createDept(reqVO);
// 断言
assertNotNull(deptId);
// 校验记录的属性是否正确
DeptDO deptDO = deptMapper.selectById(deptId);
assertPojoEquals(reqVO, deptDO, "id");
} |
@Override
public boolean put(K key, V value) {
return get(putAsync(key, value));
} | @Test
public void testPut() {
RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("{multi.map}.some.key");
map.put(new SimpleKey("0"), new SimpleValue("1"));
map.put(new SimpleKey("0"), new SimpleValue("2"));
map.put(new SimpleKey("0"), new SimpleValue("3"));
map.put(new SimpleKey("0"), new SimpleValue("3"));
map.put(new SimpleKey("3"), new SimpleValue("4"));
assertThat(map.size()).isEqualTo(5);
List<SimpleValue> s1 = map.get(new SimpleKey("0"));
assertThat(s1).containsExactly(new SimpleValue("1"), new SimpleValue("2"), new SimpleValue("3"), new SimpleValue("3"));
List<SimpleValue> allValues = map.getAll(new SimpleKey("0"));
assertThat(allValues).containsExactly(new SimpleValue("1"), new SimpleValue("2"), new SimpleValue("3"), new SimpleValue("3"));
List<SimpleValue> s2 = map.get(new SimpleKey("3"));
assertThat(s2).containsExactly(new SimpleValue("4"));
} |
public List<StorageLocation> check(
final Configuration conf,
final Collection<StorageLocation> dataDirs)
throws InterruptedException, IOException {
final HashMap<StorageLocation, Boolean> goodLocations =
new LinkedHashMap<>();
final Set<StorageLocation> failedLocations = new HashSet<>();
final Map<StorageLocation, ListenableFuture<VolumeCheckResult>> futures =
Maps.newHashMap();
final LocalFileSystem localFS = FileSystem.getLocal(conf);
final CheckContext context = new CheckContext(localFS, expectedPermission);
// Start parallel disk check operations on all StorageLocations.
for (StorageLocation location : dataDirs) {
goodLocations.put(location, true);
Optional<ListenableFuture<VolumeCheckResult>> olf =
delegateChecker.schedule(location, context);
if (olf.isPresent()) {
futures.put(location, olf.get());
}
}
if (maxVolumeFailuresTolerated >= dataDirs.size()) {
throw new HadoopIllegalArgumentException("Invalid value configured for "
+ DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY + " - "
+ maxVolumeFailuresTolerated + ". Value configured is >= "
+ "to the number of configured volumes (" + dataDirs.size() + ").");
}
final long checkStartTimeMs = timer.monotonicNow();
// Retrieve the results of the disk checks.
for (Map.Entry<StorageLocation,
ListenableFuture<VolumeCheckResult>> entry : futures.entrySet()) {
// Determine how much time we can allow for this check to complete.
// The cumulative wait time cannot exceed maxAllowedTimeForCheck.
final long waitSoFarMs = (timer.monotonicNow() - checkStartTimeMs);
final long timeLeftMs = Math.max(0,
maxAllowedTimeForCheckMs - waitSoFarMs);
final StorageLocation location = entry.getKey();
try {
final VolumeCheckResult result =
entry.getValue().get(timeLeftMs, TimeUnit.MILLISECONDS);
switch (result) {
case HEALTHY:
break;
case DEGRADED:
LOG.warn("StorageLocation {} appears to be degraded.", location);
break;
case FAILED:
LOG.warn("StorageLocation {} detected as failed.", location);
failedLocations.add(location);
goodLocations.remove(location);
break;
default:
LOG.error("Unexpected health check result {} for StorageLocation {}",
result, location);
}
} catch (ExecutionException|TimeoutException e) {
LOG.warn("Exception checking StorageLocation " + location,
e.getCause());
failedLocations.add(location);
goodLocations.remove(location);
}
}
if (maxVolumeFailuresTolerated == DataNode.MAX_VOLUME_FAILURE_TOLERATED_LIMIT) {
if (dataDirs.size() == failedLocations.size()) {
throw new DiskErrorException("Too many failed volumes - "
+ "current valid volumes: " + goodLocations.size()
+ ", volumes configured: " + dataDirs.size()
+ ", volumes failed: " + failedLocations.size()
+ ", volume failures tolerated: " + maxVolumeFailuresTolerated);
}
} else {
if (failedLocations.size() > maxVolumeFailuresTolerated) {
throw new DiskErrorException("Too many failed volumes - "
+ "current valid volumes: " + goodLocations.size()
+ ", volumes configured: " + dataDirs.size()
+ ", volumes failed: " + failedLocations.size()
+ ", volume failures tolerated: " + maxVolumeFailuresTolerated);
}
}
if (goodLocations.size() == 0) {
throw new DiskErrorException("All directories in "
+ DFS_DATANODE_DATA_DIR_KEY + " are invalid: "
+ failedLocations);
}
return new ArrayList<>(goodLocations.keySet());
} | @Test(timeout=30000)
public void testFailedLocationsBelowThreshold() throws Exception {
final List<StorageLocation> locations =
makeMockLocations(HEALTHY, HEALTHY, FAILED); // 2 healthy, 1 failed.
final Configuration conf = new HdfsConfiguration();
conf.setInt(DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, 1);
StorageLocationChecker checker =
new StorageLocationChecker(conf, new FakeTimer());
List<StorageLocation> filteredLocations = checker.check(conf, locations);
assertThat(filteredLocations.size(), is(2));
} |
@Override
public MaterialPollResult responseMessageForLatestRevisionsSince(String responseBody) {
if (isEmpty(responseBody)) return new MaterialPollResult();
Map responseBodyMap = getResponseMap(responseBody);
return new MaterialPollResult(toMaterialDataMap(responseBodyMap), toSCMRevisions(responseBodyMap));
} | @Test
public void shouldBuildNullSCMRevisionFromLatestRevisionsSinceWhenEmptyResponse() throws Exception {
MaterialPollResult pollResult = messageHandler.responseMessageForLatestRevisionsSince("");
assertThat(pollResult.getRevisions(), nullValue());
assertThat(pollResult.getMaterialData(), nullValue());
pollResult = messageHandler.responseMessageForLatestRevisionsSince(null);
assertThat(pollResult.getRevisions(), nullValue());
assertThat(pollResult.getMaterialData(), nullValue());
} |
@Deprecated
@Override
public ProducerBuilder<T> maxPendingMessagesAcrossPartitions(int maxPendingMessagesAcrossPartitions) {
conf.setMaxPendingMessagesAcrossPartitions(maxPendingMessagesAcrossPartitions);
return this;
} | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "maxPendingMessagesAcrossPartitions needs to be >= maxPendingMessages")
public void testProducerBuilderImplWhenMaxPendingMessagesAcrossPartitionsPropertyIsInvalidErrorMessages() {
producerBuilderImpl.maxPendingMessagesAcrossPartitions(-1);
} |
@Override
@Nonnull
public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks)
throws ExecutionException {
throwRejectedExecutionExceptionIfShutdown();
Exception exception = null;
for (Callable<T> task : tasks) {
try {
return task.call();
} catch (Exception e) {
// try next task
exception = e;
}
}
throw new ExecutionException("No tasks finished successfully.", exception);
} | @Test
void testInvokeAny() {
final CompletableFuture<Thread> future = new CompletableFuture<>();
testTaskSubmissionBeforeShutdown(
testInstance -> testInstance.invokeAny(callableCollectionFromFuture(future)));
assertThat(future).isCompletedWithValue(Thread.currentThread());
} |
public static void checkSchemaCompatible(
Schema tableSchema,
Schema writerSchema,
boolean shouldValidate,
boolean allowProjection,
Set<String> dropPartitionColNames) throws SchemaCompatibilityException {
if (!allowProjection) {
List<Schema.Field> missingFields = findMissingFields(tableSchema, writerSchema, dropPartitionColNames);
if (!missingFields.isEmpty()) {
throw new MissingSchemaFieldException(missingFields.stream().map(Schema.Field::name).collect(Collectors.toList()), writerSchema, tableSchema);
}
}
// TODO(HUDI-4772) re-enable validations in case partition columns
// being dropped from the data-file after fixing the write schema
if (dropPartitionColNames.isEmpty() && shouldValidate) {
AvroSchemaCompatibility.SchemaPairCompatibility result =
AvroSchemaCompatibility.checkReaderWriterCompatibility(writerSchema, tableSchema, true);
if (result.getType() != AvroSchemaCompatibility.SchemaCompatibilityType.COMPATIBLE) {
throw new SchemaBackwardsCompatibilityException(result, writerSchema, tableSchema);
}
}
} | @Test
public void testBrokenSchema() {
assertThrows(SchemaBackwardsCompatibilityException.class,
() -> AvroSchemaUtils.checkSchemaCompatible(FULL_SCHEMA, BROKEN_SCHEMA, true, false, Collections.emptySet()));
} |
public static void validateHostAndPort(final String type, final PluginConfiguration pluginConfig) {
validateHost(type, pluginConfig);
validatePort(type, pluginConfig);
} | @Test
void assertValidateHostAndPortSuccess() {
PluginConfigurationValidator.validateHostAndPort("foo_type", new PluginConfiguration("localhost", 8080, "pwd", null));
} |
public static ImmutableSet<HttpUrl> allSubPaths(String url) {
return allSubPaths(HttpUrl.parse(url));
} | @Test
public void allSubPaths_whenInvalidUrl_returnsEmptyList() {
assertThat(allSubPaths("invalid_url")).isEmpty();
} |
@VisibleForTesting
static Object scalarToProtoValue(FieldType beamFieldType, Object value) {
if (beamFieldType.getTypeName() == TypeName.LOGICAL_TYPE) {
@Nullable LogicalType<?, ?> logicalType = beamFieldType.getLogicalType();
if (logicalType == null) {
throw new RuntimeException("Unexpectedly null logical type " + beamFieldType);
}
@Nullable
BiFunction<LogicalType<?, ?>, Object, Object> logicalTypeEncoder =
LOGICAL_TYPE_ENCODERS.get(logicalType.getIdentifier());
if (logicalTypeEncoder == null) {
throw new RuntimeException("Unsupported logical type " + logicalType.getIdentifier());
}
return logicalTypeEncoder.apply(logicalType, value);
} else {
@Nullable
Function<Object, Object> encoder = PRIMITIVE_ENCODERS.get(beamFieldType.getTypeName());
if (encoder == null) {
throw new RuntimeException("Unexpected beam type " + beamFieldType);
}
return encoder.apply(value);
}
} | @Test
public void testScalarToProtoValue() {
Map<FieldType, Iterable<Pair<Object, Object>>> testCases =
ImmutableMap.<FieldType, Iterable<Pair<Object, Object>>>builder()
.put(
FieldType.BYTES,
ImmutableList.of(
Pair.create(BYTES, ByteString.copyFrom(BYTES)),
Pair.create(ByteBuffer.wrap(BYTES), ByteString.copyFrom(BYTES)),
Pair.create(
new String(BYTES, StandardCharsets.UTF_8), ByteString.copyFrom(BYTES))))
.build();
for (Map.Entry<FieldType, Iterable<Pair<Object, Object>>> entry : testCases.entrySet()) {
entry
.getValue()
.forEach(
p -> {
assertEquals(
p.getValue(),
BeamRowToStorageApiProto.scalarToProtoValue(entry.getKey(), p.getKey()));
});
}
} |
public static int indexOf(byte[] array, byte[] target) {
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
} | @Test
public void testIndexOf() {
byte[] array = new byte[] {(byte) 0x9b, 0, 0x18, 0x65, 0x2e, (byte) 0xf3};
assertEquals(0, IOUtils.indexOf(array, new byte[] {}));
assertEquals(0, IOUtils.indexOf(array, new byte[] {(byte) 0x9b, 0}));
assertEquals(2, IOUtils.indexOf(array, new byte[] {0x18, 0x65, 0x2e}));
assertEquals(4, IOUtils.indexOf(array, new byte[] {0x2e, (byte) 0xf3}));
assertEquals(-1, IOUtils.indexOf(array, new byte[] {0x2e, (byte) 0xf3, 0x31}));
assertEquals(-1, IOUtils.indexOf(array, new byte[] {0x31}));
} |
@Deprecated
public static String updateSerializedOptions(
String serializedOptions, Map<String, String> runtimeValues) {
ObjectNode root, options;
try {
root = PipelineOptionsFactory.MAPPER.readValue(serializedOptions, ObjectNode.class);
options = (ObjectNode) root.get("options");
checkNotNull(options, "Unable to locate 'options' in %s", serializedOptions);
} catch (IOException e) {
throw new RuntimeException(String.format("Unable to parse %s", serializedOptions), e);
}
for (Map.Entry<String, String> entry : runtimeValues.entrySet()) {
options.put(entry.getKey(), entry.getValue());
}
try {
return PipelineOptionsFactory.MAPPER.writeValueAsString(root);
} catch (IOException e) {
throw new RuntimeException("Unable to parse re-serialize options", e);
}
} | @Test
public void testUpdateSerializeExistingValue() throws Exception {
TestOptions submitOptions =
PipelineOptionsFactory.fromArgs("--string=baz", "--otherString=quux").as(TestOptions.class);
String serializedOptions = MAPPER.writeValueAsString(submitOptions);
String updatedOptions =
ValueProviders.updateSerializedOptions(serializedOptions, ImmutableMap.of("string", "bar"));
TestOptions runtime =
MAPPER.readValue(updatedOptions, PipelineOptions.class).as(TestOptions.class);
assertEquals("bar", runtime.getString());
assertEquals("quux", runtime.getOtherString());
} |
@SuppressWarnings("WeakerAccess")
public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) {
final Map<String, Object> consumerProps = getCommonConsumerConfigs();
// Get main consumer override configs
final Map<String, Object> mainConsumerProps = originalsWithPrefix(MAIN_CONSUMER_PREFIX);
consumerProps.putAll(mainConsumerProps);
// this is a hack to work around StreamsConfig constructor inside StreamsPartitionAssignor to avoid casting
consumerProps.put(APPLICATION_ID_CONFIG, groupId);
// add group id, client id with stream client id prefix, and group instance id
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
consumerProps.put(CommonClientConfigs.CLIENT_ID_CONFIG, clientId);
final String groupInstanceId = (String) consumerProps.get(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG);
// Suffix each thread consumer with thread.id to enforce uniqueness of group.instance.id.
if (groupInstanceId != null) {
consumerProps.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG, groupInstanceId + "-" + threadIdx);
}
// add configs required for stream partition assignor
consumerProps.put(UPGRADE_FROM_CONFIG, getString(UPGRADE_FROM_CONFIG));
consumerProps.put(REPLICATION_FACTOR_CONFIG, getInt(REPLICATION_FACTOR_CONFIG));
consumerProps.put(APPLICATION_SERVER_CONFIG, getString(APPLICATION_SERVER_CONFIG));
consumerProps.put(NUM_STANDBY_REPLICAS_CONFIG, getInt(NUM_STANDBY_REPLICAS_CONFIG));
consumerProps.put(ACCEPTABLE_RECOVERY_LAG_CONFIG, getLong(ACCEPTABLE_RECOVERY_LAG_CONFIG));
consumerProps.put(MAX_WARMUP_REPLICAS_CONFIG, getInt(MAX_WARMUP_REPLICAS_CONFIG));
consumerProps.put(PROBING_REBALANCE_INTERVAL_MS_CONFIG, getLong(PROBING_REBALANCE_INTERVAL_MS_CONFIG));
consumerProps.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, StreamsPartitionAssignor.class.getName());
consumerProps.put(WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG, getLong(WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG));
consumerProps.put(RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG, getInt(RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG));
consumerProps.put(RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG, getString(RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG));
consumerProps.put(RACK_AWARE_ASSIGNMENT_TAGS_CONFIG, getList(RACK_AWARE_ASSIGNMENT_TAGS_CONFIG));
consumerProps.put(RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG, getInt(RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG));
consumerProps.put(TASK_ASSIGNOR_CLASS_CONFIG, getString(TASK_ASSIGNOR_CLASS_CONFIG));
// disable auto topic creation
consumerProps.put(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG, "false");
// verify that producer batch config is no larger than segment size, then add topic configs required for creating topics
final Map<String, Object> topicProps = originalsWithPrefix(TOPIC_PREFIX, false);
final Map<String, Object> producerProps = getClientPropsWithPrefix(PRODUCER_PREFIX, ProducerConfig.configNames());
if (topicProps.containsKey(topicPrefix(TopicConfig.SEGMENT_BYTES_CONFIG)) &&
producerProps.containsKey(ProducerConfig.BATCH_SIZE_CONFIG)) {
final int segmentSize = Integer.parseInt(topicProps.get(topicPrefix(TopicConfig.SEGMENT_BYTES_CONFIG)).toString());
final int batchSize = Integer.parseInt(producerProps.get(ProducerConfig.BATCH_SIZE_CONFIG).toString());
if (segmentSize < batchSize) {
throw new IllegalArgumentException(String.format("Specified topic segment size %d is is smaller than the configured producer batch size %d, this will cause produced batch not able to be appended to the topic",
segmentSize,
batchSize));
}
}
consumerProps.putAll(topicProps);
return consumerProps;
} | @SuppressWarnings("deprecation")
@Test
public void shouldNotSetInternalThrowOnFetchStableOffsetUnsupportedConfigToFalseInConsumerForEosBeta() {
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, EXACTLY_ONCE_BETA);
final StreamsConfig streamsConfig = new StreamsConfig(props);
final Map<String, Object> consumerConfigs = streamsConfig.getMainConsumerConfigs(groupId, clientId, threadIdx);
assertThat(consumerConfigs.get("internal.throw.on.fetch.stable.offset.unsupported"), is(true));
} |
public static Class<?> getLiteral(String className, String literal) {
LiteralAnalyzer analyzer = ANALYZERS.get( className );
Class result = null;
if ( analyzer != null ) {
analyzer.validate( literal );
result = analyzer.getLiteral();
}
return result;
} | @Test
public void testIntegerLiteralFromJLS() {
// largest positive int: dec / octal / int / binary
assertThat( getLiteral( int.class.getCanonicalName(), "2147483647" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "2147483647" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x7fff_ffff" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0177_7777_7777" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0b0111_1111_1111_1111_1111_1111_1111_1111" ) )
.isNotNull();
// most negative int: dec / octal / int / binary
// NOTE parseInt should be changed to parseUnsignedInt in Java, than the - sign can disssapear (java8)
// and the function will be true to what the compiler shows.
assertThat( getLiteral( int.class.getCanonicalName(), "-2147483648" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x8000_0000" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0200_0000_0000" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0b1000_0000_0000_0000_0000_0000_0000_0000" ) )
.isNotNull();
// -1 representation int: dec / octal / int / binary
assertThat( getLiteral( int.class.getCanonicalName(), "-1" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0xffff_ffff" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0377_7777_7777" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0b1111_1111_1111_1111_1111_1111_1111_1111" ) )
.isNotNull();
// largest positive long: dec / octal / int / binary
assertThat( getLiteral( long.class.getCanonicalName(), "9223372036854775807L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x7fff_ffff_ffff_ffffL" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "07_7777_7777_7777_7777_7777L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_"
+ "1111_1111_1111_1111_1111_1111L" ) ).isNotNull();
// most negative long: dec / octal / int / binary
assertThat( getLiteral( long.class.getCanonicalName(), "-9223372036854775808L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x8000_0000_0000_0000L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "010_0000_0000_0000_0000_0000L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_"
+ "0000_0000_0000_0000_0000_0000L" ) ).isNotNull();
// -1 representation long: dec / octal / int / binary
assertThat( getLiteral( long.class.getCanonicalName(), "-1L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xffff_ffff_ffff_ffffL" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "017_7777_7777_7777_7777_7777L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_"
+ "1111_1111_1111_1111_1111_1111L" ) ).isNotNull();
// some examples of ints
assertThat( getLiteral( int.class.getCanonicalName(), "0" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "2" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0372" ) ).isNotNull();
//assertThat( getLiteral( int.class.getCanonicalName(), "0xDada_Cafe" ) ).isNotNull(); java8
assertThat( getLiteral( int.class.getCanonicalName(), "1996" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x00_FF__00_FF" ) ).isNotNull();
// some examples of longs
assertThat( getLiteral( long.class.getCanonicalName(), "0777l" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x100000000L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "2_147_483_648L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xC0B0L" ) ).isNotNull();
} |
@Override
public ExecutionResult execute(final TaskConfig config, final TaskExecutionContext taskExecutionContext) {
return pluginRequestHelper.submitRequest(pluginId, TaskExtension.EXECUTION_REQUEST, new DefaultPluginInteractionCallback<>() {
@Override
public String requestBody(String resolvedExtensionVersion) {
return handlerMap.get(resolvedExtensionVersion).getTaskExecutionBody(config, taskExecutionContext);
}
@Override
public ExecutionResult onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) {
return handlerMap.get(resolvedExtensionVersion).toExecutionResult(responseBody);
}
});
} | @Test
public void shouldConstructExecutionRequestWithRequiredDetails() {
String workingDir = "working-dir";
com.thoughtworks.go.plugin.api.task.Console console = mock(com.thoughtworks.go.plugin.api.task.Console.class);
when(context.workingDir()).thenReturn(workingDir);
EnvironmentVariables environment = getEnvironmentVariables();
when(context.environment()).thenReturn(environment);
when(context.console()).thenReturn(console);
final GoPluginApiRequest[] executionRequest = new GoPluginApiRequest[1];
when(response.responseBody()).thenReturn("{\"success\":true,\"messages\":[\"message1\",\"message2\"]}");
doAnswer(invocationOnMock -> {
GoPluginApiRequest request = (GoPluginApiRequest) invocationOnMock.getArguments()[2];
executionRequest[0] = request;
return response;
}).when(pluginManager).submitTo(eq(pluginId), eq(PLUGGABLE_TASK_EXTENSION), any(GoPluginApiRequest.class));
handler = new JsonBasedTaskExtensionHandler_V1();
handlerHashMap.put("1.0", handler);
new JsonBasedTaskExecutor(pluginId, pluginRequestHelper, handlerHashMap).execute(config(), context);
assertTrue(executionRequest.length == 1);
Map result = (Map) new GsonBuilder().create().fromJson(executionRequest[0].requestBody(), Object.class);
Map context = (Map) result.get("context");
assertThat(context.get("workingDirectory"), is(workingDir));
Map environmentVariables = (Map) context.get("environmentVariables");
assertThat(environmentVariables.size(), is(2));
assertThat(environmentVariables.get("ENV1").toString(), is("VAL1"));
assertThat(environmentVariables.get("ENV2").toString(), is("VAL2"));
assertThat(executionRequest[0].requestParameters().size(), is(0));
} |
public Number evaluate(final List<KiePMMLDefineFunction> defineFunctions,
final List<KiePMMLDerivedField> derivedFields,
final List<KiePMMLOutputField> outputFields,
final Map<String, Object> inputData) {
final List<KiePMMLNameValue> kiePMMLNameValues = getKiePMMLNameValuesFromInputDataMap(inputData);
ProcessingDTO processingDTO = new ProcessingDTO(defineFunctions, derivedFields, outputFields, Collections.emptyList(), kiePMMLNameValues, Collections.emptyList(), Collections.emptyList());
Object toReturn = expression.evaluate(processingDTO);
return toReturn != null ? (Number) toReturn : null;
} | @Test
void evaluateFromConstant() {
// <ComplexPartialScore>
// <Constant>100.0</Constant>
// </ComplexPartialScore>
final KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant(PARAM_1, Collections.emptyList(), value1, null);
final KiePMMLComplexPartialScore complexPartialScore = new KiePMMLComplexPartialScore(CUSTOM_FIELD, Collections.emptyList(),
kiePMMLConstant1);
Object retrieved = complexPartialScore.evaluate(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
Collections.emptyMap());
assertThat(retrieved).isEqualTo(value1);
} |
@Override
public GetClusterNodesResponse getClusterNodes(GetClusterNodesRequest request)
throws YarnException, IOException {
if (request == null) {
routerMetrics.incrClusterNodesFailedRetrieved();
String msg = "Missing getClusterNodes request.";
RouterAuditLogger.logFailure(user.getShortUserName(), GET_CLUSTERNODES, UNKNOWN,
TARGET_CLIENT_RM_SERVICE, msg);
RouterServerUtil.logAndThrowException(msg, null);
}
long startTime = clock.getTime();
ClientMethod remoteMethod = new ClientMethod("getClusterNodes",
new Class[]{GetClusterNodesRequest.class}, new Object[]{request});
try {
Collection<GetClusterNodesResponse> clusterNodes =
invokeConcurrent(remoteMethod, GetClusterNodesResponse.class);
long stopTime = clock.getTime();
routerMetrics.succeededGetClusterNodesRetrieved(stopTime - startTime);
RouterAuditLogger.logSuccess(user.getShortUserName(), GET_CLUSTERNODES,
TARGET_CLIENT_RM_SERVICE);
return RouterYarnClientUtils.mergeClusterNodesResponse(clusterNodes);
} catch (Exception ex) {
routerMetrics.incrClusterNodesFailedRetrieved();
String msg = "Unable to get cluster nodes due to exception.";
RouterAuditLogger.logFailure(user.getShortUserName(), GET_CLUSTERNODES, UNKNOWN,
TARGET_CLIENT_RM_SERVICE, msg);
RouterServerUtil.logAndThrowException(msg, ex);
}
throw new YarnException("Unable to get cluster nodes.");
} | @Test
public void testGetClusterNodesRequest() throws Exception {
LOG.info("Test FederationClientInterceptor : Get Cluster Nodes request.");
// null request
LambdaTestUtils.intercept(YarnException.class, "Missing getClusterNodes request.",
() -> interceptor.getClusterNodes(null));
// normal request.
GetClusterNodesResponse response =
interceptor.getClusterNodes(GetClusterNodesRequest.newInstance());
Assert.assertEquals(subClusters.size(), response.getNodeReports().size());
} |
@Override
public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, LayoutFactory<ILoggingEvent> layoutFactory,
LevelFilterFactory<ILoggingEvent> levelFilterFactory, AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) {
final SyslogAppender appender = new SyslogAppender();
appender.setName("syslog-appender");
appender.setContext(context);
if (logFormat != null && !logFormat.isEmpty()) {
appender.setSuffixPattern(logFormat
.replace(LOG_TOKEN_PID, pid)
.replace(LOG_TOKEN_NAME, Matcher.quoteReplacement(applicationName)));
}
appender.setSyslogHost(host);
appender.setPort(port);
appender.setFacility(facility.toString().toLowerCase(Locale.ENGLISH));
appender.setThrowableExcluded(!includeStackTrace);
appender.setStackTracePattern(stackTracePrefix);
appender.addFilter(levelFilterFactory.build(threshold));
getFilterFactories().forEach(f -> appender.addFilter(f.build()));
appender.start();
return wrapAsync(appender, asyncAppenderFactory);
} | @Test
void appenderContextIsSet() {
final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final SyslogAppenderFactory appenderFactory = new SyslogAppenderFactory();
final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(),
new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(appender.getContext()).isEqualTo(root.getLoggerContext());
} |
@Override
public String[] split(String text) {
for (Pattern regexp : CONTRACTIONS2)
text = regexp.matcher(text).replaceAll("$1 $2");
for (Pattern regexp : CONTRACTIONS3)
text = regexp.matcher(text).replaceAll("$1 $2 $3");
text = DELIMITERS[0].matcher(text).replaceAll(" $1 ");
text = DELIMITERS[1].matcher(text).replaceAll(" $1");
text = DELIMITERS[2].matcher(text).replaceAll(" $1");
text = DELIMITERS[3].matcher(text).replaceAll(" . ");
String[] words = WHITESPACE.split(text);
if (words.length > 1 && words[words.length-1].equals(".")) {
if (EnglishAbbreviations.contains(words[words.length-2])) {
words[words.length-2] = words[words.length-2] + ".";
}
}
return words;
} | @Test
public void testTokenizeDiacritizedWords() {
System.out.println("tokenize words with diacritized chars (both composite and combining)");
String text = "The naïve résumé of Raúl Ibáñez; re\u0301sume\u0301.";
String[] expResult = {"The", "naïve", "résumé", "of", "Raúl", "Ibáñez", ";", "re\u0301sume\u0301", "."};
SimpleTokenizer instance = new SimpleTokenizer();
String[] result = instance.split(text);
assertEquals(expResult.length, result.length);
for (int i = 0; i < result.length; i++) {
assertEquals(expResult[i], result[i]);
}
} |
public static List<String> detectClassPathResourcesToStage(
ClassLoader classLoader, PipelineOptions options) {
PipelineResourcesOptions artifactsRelatedOptions = options.as(PipelineResourcesOptions.class);
List<String> detectedResources =
artifactsRelatedOptions.getPipelineResourcesDetector().detect(classLoader);
return detectedResources.stream().filter(isStageable()).collect(Collectors.toList());
} | @Test
public void testDetectedResourcesListDoNotContainNotStageableResources() throws IOException {
File unstageableResource = tmpFolder.newFolder(".gradle/wrapper/unstageableResource");
URLClassLoader classLoader =
new URLClassLoader(new URL[] {unstageableResource.toURI().toURL()});
PipelineResourcesOptions options =
PipelineOptionsFactory.create().as(PipelineResourcesOptions.class);
List<String> detectedResources =
PipelineResources.detectClassPathResourcesToStage(classLoader, options);
assertThat(detectedResources, not(contains(unstageableResource.getAbsolutePath())));
} |
public boolean matches(String groupAccessCode) {
return code.equals(Encoder.encode(groupAccessCode));
} | @Test
void 코드_일치_여부를_판단한다() {
// given
String code = "hello";
GroupAccessCode groupAccessCode = new GroupAccessCode(code);
// when, then
assertThat(groupAccessCode.matches("hello")).isTrue();
} |
public static String[] splitByComma(String input, boolean allowEmpty) {
if (input == null) {
return null;
}
String[] splitWithEmptyValues = trim(input).split("\\s*,\\s*", -1);
return allowEmpty ? splitWithEmptyValues : subtraction(splitWithEmptyValues, new String[]{""});
} | @Test
void testSplitByComma() {
assertNull(StringUtil.splitByComma(null, true));
assertArrayEquals(arr(""), StringUtil.splitByComma("", true));
assertArrayEquals(arr(""), StringUtil.splitByComma(" ", true));
assertArrayEquals(arr(), StringUtil.splitByComma(" ", false));
assertArrayEquals(arr("a"), StringUtil.splitByComma("a", true));
assertArrayEquals(arr("a"), StringUtil.splitByComma("a", false));
assertArrayEquals(arr("aa", "bbb", "c"), StringUtil.splitByComma("aa,bbb,c", true));
assertArrayEquals(arr("aa", "bbb", "c", ""), StringUtil.splitByComma(" aa\t,\nbbb ,\r c, ", true));
assertArrayEquals(arr("aa", "bbb", "c"), StringUtil.splitByComma(" aa ,\n,\r\tbbb ,c , ", false));
} |
@Override
public Optional<AuthenticatedDevice> authenticate(BasicCredentials basicCredentials) {
boolean succeeded = false;
String failureReason = null;
try {
final UUID accountUuid;
final byte deviceId;
{
final Pair<String, Byte> identifierAndDeviceId = getIdentifierAndDeviceId(basicCredentials.getUsername());
accountUuid = UUID.fromString(identifierAndDeviceId.first());
deviceId = identifierAndDeviceId.second();
}
Optional<Account> account = accountsManager.getByAccountIdentifier(accountUuid);
if (account.isEmpty()) {
failureReason = "noSuchAccount";
return Optional.empty();
}
Optional<Device> device = account.get().getDevice(deviceId);
if (device.isEmpty()) {
failureReason = "noSuchDevice";
return Optional.empty();
}
SaltedTokenHash deviceSaltedTokenHash = device.get().getAuthTokenHash();
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
succeeded = true;
Account authenticatedAccount = updateLastSeen(account.get(), device.get());
if (deviceSaltedTokenHash.getVersion() != SaltedTokenHash.CURRENT_VERSION) {
OLD_TOKEN_VERSION_COUNTER.increment();
authenticatedAccount = accountsManager.updateDeviceAuthentication(
authenticatedAccount,
device.get(),
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
}
return Optional.of(new AuthenticatedDevice(authenticatedAccount, device.get()));
} else {
failureReason = "incorrectPassword";
return Optional.empty();
}
} catch (IllegalArgumentException | InvalidAuthorizationHeaderException iae) {
failureReason = "invalidHeader";
return Optional.empty();
} finally {
Tags tags = Tags.of(
AUTHENTICATION_SUCCEEDED_TAG_NAME, String.valueOf(succeeded));
if (StringUtils.isNotBlank(failureReason)) {
tags = tags.and(AUTHENTICATION_FAILURE_REASON_TAG_NAME, failureReason);
}
Metrics.counter(AUTHENTICATION_COUNTER_NAME, tags).increment();
}
} | @Test
void testAuthenticateNonDefaultDevice() {
final UUID uuid = UUID.randomUUID();
final byte deviceId = 2;
final String password = "12345";
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(device.getId()).thenReturn(deviceId);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
final Optional<AuthenticatedDevice> maybeAuthenticatedAccount =
accountAuthenticator.authenticate(new BasicCredentials(uuid + "." + deviceId, password));
assertThat(maybeAuthenticatedAccount).isPresent();
assertThat(maybeAuthenticatedAccount.get().getAccount().getUuid()).isEqualTo(uuid);
assertThat(maybeAuthenticatedAccount.get().getAuthenticatedDevice()).isEqualTo(device);
verify(accountsManager, never()).updateDeviceAuthentication(any(), any(), any());
} |
@Deprecated
public static void validateEntityId(EntityId entityId, String errorMessage) {
if (entityId == null || entityId.getId() == null) {
throw new IncorrectParameterException(errorMessage);
}
} | @Test
void validateEntityIdTest() {
Validator.validateEntityId(TenantId.SYS_TENANT_ID, id -> "Incorrect entityId " + id);
Validator.validateEntityId(goodDeviceId, id -> "Incorrect entityId " + id);
assertThatThrownBy(() -> Validator.validateEntityId(null, id -> "Incorrect entityId " + id))
.as("EntityId is null")
.isInstanceOf(IncorrectParameterException.class)
.hasMessageContaining("Incorrect entityId null");
assertThatThrownBy(() -> Validator.validateEntityId(nullUserId, id -> "Incorrect entityId " + id))
.as("EntityId with null UUID")
.isInstanceOf(IncorrectParameterException.class)
.hasMessageContaining("Incorrect entityId null");
} |
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml4(input));
} | @Test
public void shouldDecorateBlockquote() {
assertThat(Markdown.convertToHtml("> Yesterday <br/> it worked\n> Today it is not working\r\n> Software is like that\r"))
.isEqualTo("<blockquote>Yesterday <br/> it worked<br/>\nToday it is not working<br/>\r\nSoftware is like that<br/>\r</blockquote>");
assertThat(Markdown.convertToHtml("HTML elements should <em>not</em> be quoted!"))
.isEqualTo("HTML elements should <em>not</em> be quoted!");
} |
public String getServiceUUID(Connection connection, String serviceEntityId, int consumingServiceIdx) {
if (connection == null || serviceEntityId == null)
return null;
EntityDescriptor serviceEntityDescriptor = resolveEntityDescriptorFromMetadata(connection, serviceEntityId);
if (serviceEntityDescriptor == null || serviceEntityDescriptor.getRoleDescriptors() == null) {
return null;
}
List<XMLObject> list = serviceEntityDescriptor.getRoleDescriptors().get(0).getOrderedChildren();
if (list == null) {
return null;
}
Optional<XMLObject> xmlObject = list
.stream()
.filter(obj -> obj instanceof AttributeConsumingService && ((AttributeConsumingService) obj).getIndex() == consumingServiceIdx)
.findFirst();
if (xmlObject.isEmpty()) {
return null;
}
AttributeConsumingService attributeConsumingService = (AttributeConsumingService) xmlObject.get();
Optional<RequestedAttribute> requestedAttribute = attributeConsumingService.getRequestedAttributes()
.stream()
.filter(o -> o.getName().equals(SAML_SERVICE_UUID_NAME))
.findFirst();
return requestedAttribute.isEmpty() ? null : ((XSAny) requestedAttribute.get().getAttributeValues().get(0)).getTextContent();
} | @Test
void getServiceUUID() throws InitializationException {
setupParserPool();
String result = metadataRetrieverServiceMock.getServiceUUID(newConnection(SAML_COMBICONNECT, true, true, true), newMetadataRequest().getServiceEntityId(), 0);
assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", result);
} |
public @Nullable String formatDiff(A actual, E expected) {
return null;
} | @Test
public void testFormattingDiffsUsing_formatDiff() {
assertThat(LENGTHS_WITH_DIFF.formatDiff("foo", 4)).isEqualTo("-1");
assertThat(LENGTHS_WITH_DIFF.formatDiff("foot", 3)).isEqualTo("1");
} |
public static Object withCompatibleSchema(final Schema schema, final Object object) {
if (object == null) {
return null;
}
switch (schema.type()) {
case ARRAY:
final List<Object> ksqlArray = new ArrayList<>(((List) object).size());
((List) object).forEach(
e -> ksqlArray.add(withCompatibleSchema(schema.valueSchema(), e)));
return ksqlArray;
case MAP:
final Map<Object, Object> ksqlMap = new HashMap<>();
((Map<Object, Object>) object).forEach(
(key, value) -> ksqlMap.put(
withCompatibleSchema(schema.keySchema(), key),
withCompatibleSchema(schema.valueSchema(), value)
));
return ksqlMap;
case STRUCT:
return withCompatibleRowSchema((Struct) object, schema);
case BYTES:
if (DecimalUtil.isDecimal(schema)) {
return DecimalUtil.ensureFit((BigDecimal) object, schema);
} else {
return object;
}
default:
return object;
}
} | @Test
public void shouldMakeStructSchemaCompatible() {
// Given:
final Schema oldSchema = new ConnectSchema(
Type.STRUCT, false, null, "oldSchema", 1, "");
final Struct struct = new Struct(oldSchema);
// When:
final Schema newSchema = new ConnectSchema(
Type.STRUCT, false, null, "newSchema", 1, "");;
final Struct structWithNewSchema = (Struct) ConnectSchemas.withCompatibleSchema(newSchema, struct);
// Then:
assertThat(structWithNewSchema.schema(), is(newSchema));
} |
public long remainingMs() {
timer.update();
return timer.remainingMs();
} | @Test
public void testRemainingMs() {
TimedRequestState state = new TimedRequestState(
new LogContext(),
this.getClass().getSimpleName(),
100,
1000,
time.timer(DEFAULT_TIMEOUT_MS)
);
assertEquals(DEFAULT_TIMEOUT_MS, state.remainingMs());
time.sleep(DEFAULT_TIMEOUT_MS);
assertEquals(0, state.remainingMs());
} |
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException {
final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest);
if (samlRequest instanceof AuthenticationRequest) {
dcMetadataResponseMapper.dcMetadataToAuthenticationRequest((AuthenticationRequest) samlRequest, metadataFromDc, samlRequest.getServiceEntityId());
} else {
dcMetadataResponseMapper.dcMetadataToSamlRequest(samlRequest, metadataFromDc);
}
} | @Test
public void resolveAuthenticationDcMetadataTest() throws DienstencatalogusException {
when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(stubDcResponse());
SamlRequest request = new AuthenticationRequest();
request.setConnectionEntityId(CONNECTION_ENTITY_ID);
request.setServiceEntityId(SERVICE_ENTITY_ID);
dcMetadataService.resolveDcMetadata(request);
assertEquals("federation1", request.getFederationName());
assertEquals(1, request.getLegacyWebserviceId());
assertEquals(10, ((AuthenticationRequest) request).getMinimumRequestedAuthLevel());
assertEquals("serviceUUID", request.getServiceUuid());
assertEquals("permissionQuestion", request.getPermissionQuestion());
assertEquals(true, ((AuthenticationRequest) request).getAppActive());
assertEquals("appReturnUrl", ((AuthenticationRequest) request).getAppReturnUrl());
assertEquals("serviceName", ((AuthenticationRequest) request).getServiceName());
assertEquals("urn:nl-eid-gdi:1:0:entities:00000009999999999001", ((AuthenticationRequest) request).getEntityId());
assertEquals(10, ((AuthenticationRequest) request).getMinimumRequestedAuthLevel());
assertEquals("BSN", ((AuthenticationRequest) request).getEncryptionIdType());
assertNotNull(request.getConnectionEntity());
assertNotNull(request.getServiceEntity());
} |
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) {
List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext()
? createShardingConditionsWithInsertValues(sqlStatementContext, params)
: createShardingConditionsWithInsertSelect(sqlStatementContext, params);
appendGeneratedKeyConditions(sqlStatementContext, result);
return result;
} | @Test
void assertCreateShardingConditionsWithCaseSensitiveField() {
when(shardingRule.findShardingColumn("foo_Col_3", "foo_table")).thenReturn(Optional.of("foo_Col_3"));
List<ShardingCondition> actual = shardingConditionEngine.createShardingConditions(insertStatementContext, Collections.emptyList());
assertThat(actual.size(), is(1));
} |
public static String buildApiPath(String interfaceName, String version, String methodName) {
if (version == null || "".equals(version) || ABSENT_VERSION.equals(version)) {
return interfaceName + "." + methodName;
}
// io.sermant.dubbotest.service.CTest:version.methodName
return interfaceName + ":" + version + "." + methodName;
} | @Test
public void testBuildPath() {
Assert.assertEquals(
ConvertUtils.buildApiPath("com.test.interface", "1.0.0", "methodName"),
"com.test.interface:1.0.0.methodName");
Assert.assertEquals(
ConvertUtils.buildApiPath("com.test.interface", "", "methodName"),
"com.test.interface.methodName");
} |
@Override
public <T> TableConfig set(ConfigOption<T> option, T value) {
configuration.set(option, value);
return this;
} | @Test
void testGetInvalidLocalTimeZoneUTC() {
CONFIG_BY_CONFIGURATION.set("table.local-time-zone", "UTC+8");
assertThatThrownBy(CONFIG_BY_CONFIGURATION::getLocalTimeZone)
.isInstanceOf(ValidationException.class)
.hasMessageContaining("Invalid time zone.");
} |
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path)
{
if (inputFormat instanceof TextInputFormat) {
return getCompressionCodec((TextInputFormat) inputFormat, path)
.map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec))
.orElse(true);
}
return false;
} | @Test
public void testIsCompressionCodecSupported()
{
assertTrue(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject.gz")));
assertTrue(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject")));
assertFalse(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject.lz4")));
assertFalse(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject.snappy")));
assertTrue(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject.bz2")));
} |
@VisibleForTesting
Integer convertSmsTemplateAuditStatus(int templateStatus) {
switch (templateStatus) {
case 1: return SmsTemplateAuditStatusEnum.CHECKING.getStatus();
case 0: return SmsTemplateAuditStatusEnum.SUCCESS.getStatus();
case -1: return SmsTemplateAuditStatusEnum.FAIL.getStatus();
default: throw new IllegalArgumentException(String.format("未知审核状态(%d)", templateStatus));
}
} | @Test
public void testConvertSmsTemplateAuditStatus() {
assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(),
smsClient.convertSmsTemplateAuditStatus(0));
assertEquals(SmsTemplateAuditStatusEnum.CHECKING.getStatus(),
smsClient.convertSmsTemplateAuditStatus(1));
assertEquals(SmsTemplateAuditStatusEnum.FAIL.getStatus(),
smsClient.convertSmsTemplateAuditStatus(-1));
assertThrows(IllegalArgumentException.class, () -> smsClient.convertSmsTemplateAuditStatus(3),
"未知审核状态(3)");
} |
public static int nextCapacity(int current) {
assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two.";
if (current < MIN_CAPACITY / 2) {
current = MIN_CAPACITY / 2;
}
current <<= 1;
if (current < 0) {
throw new RuntimeException("Maximum capacity exceeded.");
}
return current;
} | @Test
public void testNextCapacity_withInt() {
int capacity = 16;
int nextCapacity = nextCapacity(capacity);
assertEquals(32, nextCapacity);
} |
public SmbFile getFile() {
return file;
} | @Test
public void getFile() {
assertEquals(file, ss.getFile());
} |
@Override
public URL getResource(final String name) {
try {
final Enumeration<URL> resources = getResources(name);
if (resources.hasMoreElements()) {
return resources.nextElement();
}
} catch (IOException ignored) {
// mimics the behavior of the JDK
}
return null;
} | @Test
void testOwnerFirstResourceFoundIgnoresComponent() throws IOException {
String resourceToLoad =
TempDirUtils.newFile(tempFolder, "tmpfile" + UUID.randomUUID()).getName();
TestUrlClassLoader owner =
new TestUrlClassLoader(resourceToLoad, RESOURCE_RETURNED_BY_OWNER);
final ComponentClassLoader componentClassLoader =
new ComponentClassLoader(
new URL[] {},
owner,
new String[] {resourceToLoad},
new String[0],
Collections.emptyMap());
final URL loadedResource = componentClassLoader.getResource(resourceToLoad);
assertThat(loadedResource).isSameAs(RESOURCE_RETURNED_BY_OWNER);
} |
@Override
public void executeWithLock(Runnable task, LockConfiguration lockConfig) {
try {
executeWithLock((Task) task::run, lockConfig);
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable throwable) {
// Should not happen
throw new IllegalStateException(throwable);
}
} | @Test
void lockShouldBeReentrantForMultipleDifferentLocks() {
mockLockFor(lockConfig);
mockLockFor(lockConfig2);
AtomicBoolean called = new AtomicBoolean(false);
executor.executeWithLock(
(Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), lockConfig2), lockConfig);
assertThat(called.get()).isTrue();
} |
@Override
public void putAll(Map<? extends CharSequence, ? extends V> otherMap) {
otherMap.forEach(this::put);
} | @Test
public void testPutAll() {
CharSequenceMap<String> map = CharSequenceMap.create();
map.putAll(ImmutableMap.of("key1", "value1", "key2", "value2"));
assertThat(map).containsEntry("key1", "value1");
assertThat(map).containsEntry("key2", "value2");
} |
public boolean couldHoldIgnoringSharedMemory(NormalizedResources other, double thisTotalMemoryMb, double otherTotalMemoryMb) {
if (this.cpu < other.getTotalCpu()) {
return false;
}
return couldHoldIgnoringSharedMemoryAndCpu(other, thisTotalMemoryMb, otherTotalMemoryMb);
} | @Test
public void testCouldHoldWithMissingResource() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.emptyMap()));
NormalizedResources resourcesToCheck = new NormalizedResources(normalize(Collections.singletonMap(gpuResourceName, 1)));
boolean couldHold = resources.couldHoldIgnoringSharedMemory(resourcesToCheck, 100, 1);
assertThat(couldHold, is(false));
} |
public byte[] poll(long timeout, TimeUnit unit) throws Exception {
return internalPoll(timeout, unit);
} | @Test
public void testPollWithTimeout() throws Exception {
CuratorFramework clients[] = null;
try {
String dir = "/testOffer1";
final int num_clients = 1;
clients = new CuratorFramework[num_clients];
SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients];
for (int i = 0; i < clients.length; i++) {
clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
clients[i].start();
queueHandles[i] = new SimpleDistributedQueue(clients[i], dir);
}
assertNull(queueHandles[0].poll(3, TimeUnit.SECONDS));
} finally {
closeAll(clients);
}
} |
public static void setDeepLinkCallback(SensorsDataDeepLinkCallback callback) {
mDeepLinkCallback = callback;
} | @Test
public void setDeepLinkCallback() {
DeepLinkManager.setDeepLinkCallback(null);
} |
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
this.jsonPath = jsonPath;
this.resultMatcher = resultMatcher;
} | @Test
public void shouldMatchExistingCompiledJsonPath() {
assertThat(BOOKS_JSON, withJsonPath(compile("$.expensive")));
assertThat(BOOKS_JSON, withJsonPath(compile("$.store.bicycle")));
assertThat(BOOKS_JSON, withJsonPath(compile("$.store.book[2].title")));
assertThat(BOOKS_JSON, withJsonPath(compile("$.store.book[*].author")));
} |
static void publishMessagesInBatch() throws Exception {
try (Connection connection = createConnection()) {
Channel ch = connection.createChannel();
String queue = UUID.randomUUID().toString();
ch.queueDeclare(queue, false, false, true, null);
ch.confirmSelect();
int batchSize = 100;
int outstandingMessageCount = 0;
long start = System.nanoTime();
for (int i = 0; i < MESSAGE_COUNT; i++) {
String body = String.valueOf(i);
ch.basicPublish("", queue, null, body.getBytes());
outstandingMessageCount++;
if (outstandingMessageCount == batchSize) {
ch.waitForConfirmsOrDie(5_000);
outstandingMessageCount = 0;
}
}
if (outstandingMessageCount > 0) {
ch.waitForConfirmsOrDie(5_000);
}
long end = System.nanoTime();
System.out.format("Published %,d messages in batch in %,d ms%n", MESSAGE_COUNT, Duration.ofNanos(end - start).toMillis());
}
} | @Test
@DisplayName("publish messages in batch")
void publishMessagesInBatch() throws Exception {
Channel ch = connection.createChannel();
ch.confirmSelect();
int batchSize = 100;
int outstandingMessageCount = 0;
for (int i = 0; i < messageCount; i++) {
String body = String.valueOf(i);
ch.basicPublish("", queue, null, body.getBytes());
outstandingMessageCount++;
if (outstandingMessageCount == batchSize) {
ch.waitForConfirmsOrDie(5_000);
outstandingMessageCount = 0;
}
meter.mark();
}
if (outstandingMessageCount > 0) {
ch.waitForConfirmsOrDie(5_000);
}
ch.close();
CountDownLatch latch = new CountDownLatch(messageCount);
ch = connection.createChannel();
ch.basicConsume(queue, true, ((consumerTag, message) -> latch.countDown()), consumerTag -> {
});
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
} |
@Override
public MutableNetwork<Node, Edge> apply(MapTask mapTask) {
List<ParallelInstruction> parallelInstructions = Apiary.listOrEmpty(mapTask.getInstructions());
MutableNetwork<Node, Edge> network =
NetworkBuilder.directed()
.allowsSelfLoops(false)
.allowsParallelEdges(true)
.expectedNodeCount(parallelInstructions.size() * 2)
.build();
// Add all the instruction nodes and output nodes
ParallelInstructionNode[] instructionNodes =
new ParallelInstructionNode[parallelInstructions.size()];
InstructionOutputNode[][] outputNodes =
new InstructionOutputNode[parallelInstructions.size()][];
for (int i = 0; i < parallelInstructions.size(); ++i) {
// InstructionOutputNode's are the source of truth on instruction outputs.
// Clear the instruction's outputs to reduce chance for confusion.
List<InstructionOutput> outputs =
Apiary.listOrEmpty(parallelInstructions.get(i).getOutputs());
outputNodes[i] = new InstructionOutputNode[outputs.size()];
JsonFactory factory =
MoreObjects.firstNonNull(mapTask.getFactory(), Transport.getJsonFactory());
ParallelInstruction parallelInstruction =
clone(factory, parallelInstructions.get(i)).setOutputs(null);
ParallelInstructionNode instructionNode =
ParallelInstructionNode.create(parallelInstruction, Nodes.ExecutionLocation.UNKNOWN);
instructionNodes[i] = instructionNode;
network.addNode(instructionNode);
// Connect the instruction node output to the output PCollection node
for (int j = 0; j < outputs.size(); ++j) {
InstructionOutput instructionOutput = outputs.get(j);
InstructionOutputNode outputNode =
InstructionOutputNode.create(
instructionOutput, "generatedPcollection" + this.idGenerator.getId());
network.addNode(outputNode);
if (parallelInstruction.getParDo() != null) {
network.addEdge(
instructionNode,
outputNode,
MultiOutputInfoEdge.create(
parallelInstruction.getParDo().getMultiOutputInfos().get(j)));
} else {
network.addEdge(instructionNode, outputNode, DefaultEdge.create());
}
outputNodes[i][j] = outputNode;
}
}
// Connect PCollections as inputs to instructions
for (ParallelInstructionNode instructionNode : instructionNodes) {
ParallelInstruction parallelInstruction = instructionNode.getParallelInstruction();
if (parallelInstruction.getFlatten() != null) {
for (InstructionInput input :
Apiary.listOrEmpty(parallelInstruction.getFlatten().getInputs())) {
attachInput(input, network, instructionNode, outputNodes);
}
} else if (parallelInstruction.getParDo() != null) {
attachInput(
parallelInstruction.getParDo().getInput(), network, instructionNode, outputNodes);
} else if (parallelInstruction.getPartialGroupByKey() != null) {
attachInput(
parallelInstruction.getPartialGroupByKey().getInput(),
network,
instructionNode,
outputNodes);
} else if (parallelInstruction.getRead() != null) {
// Reads have no inputs so nothing to do
} else if (parallelInstruction.getWrite() != null) {
attachInput(
parallelInstruction.getWrite().getInput(), network, instructionNode, outputNodes);
} else {
throw new IllegalArgumentException(
String.format(
"Unknown type of instruction %s for map task %s", parallelInstruction, mapTask));
}
}
return network;
} | @Test
public void testParDo() {
InstructionOutput readOutput = createInstructionOutput("Read.out");
ParallelInstruction read = createParallelInstruction("Read", readOutput);
read.setRead(new ReadInstruction());
MultiOutputInfo parDoMultiOutput = createMultiOutputInfo("output");
ParDoInstruction parDoInstruction = new ParDoInstruction();
parDoInstruction.setInput(createInstructionInput(0, 0)); // Read.out
parDoInstruction.setMultiOutputInfos(ImmutableList.of(parDoMultiOutput));
InstructionOutput parDoOutput = createInstructionOutput("ParDo.out");
ParallelInstruction parDo = createParallelInstruction("ParDo", parDoOutput);
parDo.setParDo(parDoInstruction);
MapTask mapTask = new MapTask();
mapTask.setInstructions(ImmutableList.of(read, parDo));
mapTask.setFactory(Transport.getJsonFactory());
Network<Node, Edge> network =
new MapTaskToNetworkFunction(IdGenerators.decrementingLongs()).apply(mapTask);
assertNetworkProperties(network);
assertEquals(4, network.nodes().size());
assertEquals(3, network.edges().size());
ParallelInstructionNode readNode = get(network, read);
InstructionOutputNode readOutputNode = getOnlySuccessor(network, readNode);
assertEquals(readOutput, readOutputNode.getInstructionOutput());
ParallelInstructionNode parDoNode = getOnlySuccessor(network, readOutputNode);
InstructionOutputNode parDoOutputNode = getOnlySuccessor(network, parDoNode);
assertEquals(parDoOutput, parDoOutputNode.getInstructionOutput());
assertEquals(
parDoMultiOutput,
((MultiOutputInfoEdge)
Iterables.getOnlyElement(network.edgesConnecting(parDoNode, parDoOutputNode)))
.getMultiOutputInfo());
} |
@Override
public void preflight(final Path workdir, final String filename) throws BackgroundException {
if(workdir.isRoot() || new DeepboxPathContainerService(session).isDeepbox(workdir) || new DeepboxPathContainerService(session).isBox(workdir)) {
throw new AccessDeniedException(MessageFormat.format(LocaleFactory.localizedString("Cannot create {0}", "Error"), filename)).withFile(workdir);
}
final Acl acl = workdir.attributes().getAcl();
if(Acl.EMPTY == acl) {
// Missing initialization
log.warn(String.format("Unknown ACLs on %s", workdir));
return;
}
if(!acl.get(new Acl.CanonicalUser()).contains(CANADDCHILDREN)) {
if(log.isWarnEnabled()) {
log.warn(String.format("ACL %s for %s does not include %s", acl, workdir, CANADDCHILDREN));
}
throw new AccessDeniedException(MessageFormat.format(LocaleFactory.localizedString("Cannot create {0}", "Error"), filename)).withFile(workdir);
}
} | @Test
public void testAddChildrenInbox() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final Path folder = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Inbox/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final PathAttributes attributes = new DeepboxAttributesFinderFeature(session, nodeid).find(folder);
assertTrue(new BoxRestControllerApi(session.getClient()).getBox(ORG4, ORG4_BOX1).getBoxPolicy().isCanAddQueue());
assertTrue(attributes.getAcl().get(new Acl.CanonicalUser()).contains(CANADDCHILDREN));
// assert no fail
new DeepboxTouchFeature(session, nodeid).preflight(folder.withAttributes(attributes), new AlphanumericRandomStringService().random());
// DeepBox inbox is flat
assertThrows(AccessDeniedException.class, () -> new DeepboxDirectoryFeature(session, nodeid).preflight(folder.withAttributes(attributes), new AlphanumericRandomStringService().random()));
} |
public static List<PropertyDefinition> all() {
return asList(
PropertyDefinition.builder(PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY)
.defaultValue("24")
.name("Keep only one analysis a day after")
.description("After this number of hours, if there are several analyses during the same day, "
+ "the DbCleaner keeps the most recent one and fully deletes the other ones.")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(1)
.build(),
PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK)
.defaultValue("4")
.name("Keep only one analysis a week after")
.description("After this number of weeks, if there are several analyses during the same week, "
+ "the DbCleaner keeps the most recent one and fully deletes the other ones")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(2)
.build(),
PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH)
.defaultValue("52")
.name("Keep only one analysis a month after")
.description("After this number of weeks, if there are several analyses during the same month, "
+ "the DbCleaner keeps the most recent one and fully deletes the other ones.")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(3)
.build(),
PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ANALYSES_WITH_VERSION)
.defaultValue("104")
.name("Keep only analyses with a version event after")
.description("After this number of weeks, the DbCleaner keeps only analyses with a version event associated.")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(4)
.build(),
PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS)
.defaultValue("260")
.name("Delete all analyses after")
.description("After this number of weeks, all analyses are fully deleted.")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(5)
.build(),
PropertyDefinition.builder(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES)
.defaultValue("30")
.name("Delete closed issues after")
.description("Issues that have been closed for more than this number of days will be deleted.")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(6)
.build(),
PropertyDefinition.builder(PurgeConstants.DAYS_BEFORE_DELETING_ANTICIPATED_TRANSITIONS)
.defaultValue("30")
.name("Delete anticipated transitions after")
.description("Anticipated transitions that have not been applied for more than this number of days will be deleted.")
.type(PropertyType.INTEGER)
.onQualifiers(Qualifiers.PROJECT)
.category(CoreProperties.CATEGORY_HOUSEKEEPING)
.subCategory(CoreProperties.SUBCATEGORY_GENERAL)
.index(7)
.build());
} | @Test
public void shouldGetExtensions() {
assertThat(PurgeProperties.all()).hasSize(7);
} |
static <E extends Enum<E>> int untetheredSubscriptionStateChangeLength(final E from, final E to)
{
return stateTransitionStringLength(from, to) + SIZE_OF_LONG + 2 * SIZE_OF_INT;
} | @Test
void untetheredSubscriptionStateChangeLengthComputesLengthBasedOnProvidedState()
{
final ClusterTimeUnit from = ClusterTimeUnit.MILLIS;
final ClusterTimeUnit to = ClusterTimeUnit.NANOS;
assertEquals(stateTransitionStringLength(from, to) + SIZE_OF_LONG + 2 * SIZE_OF_INT,
untetheredSubscriptionStateChangeLength(from, to));
} |
@Override
Class<?> getReturnType() {
throw new UnsupportedOperationException();
} | @Test
public void getReturnType() {
// GIVEN
ExtractorGetter getter = new ExtractorGetter(UNUSED, mock(ValueExtractor.class), "argument");
// WHEN
assertThrows(UnsupportedOperationException.class, getter::getReturnType);
} |
public final void isNotIn(Range<T> range) {
if (range.contains(checkNotNull(actual))) {
failWithActual("expected not to be in range", range);
}
} | @Test
public void isNotInRange() {
Range<Integer> oneToFive = Range.closed(1, 5);
assertThat(6).isNotIn(oneToFive);
expectFailureWhenTestingThat(4).isNotIn(oneToFive);
assertThat(expectFailure.getFailure())
.factValue("expected not to be in range")
.isEqualTo(oneToFive.toString());
} |
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
} | @Test
public void testIsNullOrEmpty() {
assertTrue(isNullOrEmpty(null));
assertTrue(isNullOrEmpty(""));
assertTrue(isNullOrEmpty(StringUtil.EMPTY_STRING));
assertFalse(isNullOrEmpty(" "));
assertFalse(isNullOrEmpty("\t"));
assertFalse(isNullOrEmpty("\n"));
assertFalse(isNullOrEmpty("foo"));
assertFalse(isNullOrEmpty(NEWLINE));
} |
public static String hadoopFsFilename(String fname, Configuration conf, String user)
throws URISyntaxException, FileNotFoundException, IOException,
InterruptedException {
Path p = hadoopFsPath(fname, conf, user);
if (p == null)
return null;
else
return p.toString();
} | @Test
public void testHadoopFsFilename() {
try {
String tmpFileName1 = "/tmp/testHadoopFsListAsArray1";
String tmpFileName2 = "/tmp/testHadoopFsListAsArray2";
File tmpFile1 = new File(tmpFileName1);
File tmpFile2 = new File(tmpFileName2);
tmpFile1.createNewFile();
tmpFile2.createNewFile();
Assert.assertEquals(null, TempletonUtils.hadoopFsFilename(null, null, null));
Assert.assertEquals(null,
TempletonUtils.hadoopFsFilename(tmpFile.toURI().toString(), null, null));
Assert.assertEquals(tmpFile.toURI().toString(),
TempletonUtils.hadoopFsFilename(tmpFile.toURI().toString(),
new Configuration(),
null));
} catch (FileNotFoundException e) {
Assert.fail("Couldn't find name for /tmp");
Assert.fail("Couldn't find name for " + tmpFile.toURI().toString());
} catch (Exception e) {
// Something else is wrong
e.printStackTrace();
}
try {
TempletonUtils.hadoopFsFilename("/scoobydoo/teddybear",
new Configuration(), null);
Assert.fail("Should not have found /scoobydoo/teddybear");
} catch (FileNotFoundException e) {
// Should go here.
} catch (Exception e) {
// Something else is wrong.
e.printStackTrace();
}
} |
@Override
public void smoke() {
tobacco.smoke(this);
} | @Test
void testSmokeEveryThingThroughConstructor() {
List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(),
new RivendellTobacco(),
new SecondBreakfastTobacco()
);
// Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final GuiceWizard guiceWizard = new GuiceWizard(tobacco);
guiceWizard.smoke();
String lastMessage = appender.getLastMessage();
assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
});
// ... and nothing else is happening.
assertEquals(tobaccos.size(), appender.getLogSize());
} |
public static boolean isValidIp(String ip) {
return VALIDATOR.isValid(ip);
} | @Test
public void isValidIp() {
String ipv4 = "192.168.1.0";
String ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String invalidIp = "192.168.1.256";
String ipv4Cidr = "192.168.1.0/24";
assert IPAddressUtils.isValidIp(ipv4);
assert IPAddressUtils.isValidIp(ipv6);
assert !IPAddressUtils.isValidIp(invalidIp);
assert !IPAddressUtils.isValidIp(ipv4Cidr);
} |
protected boolean checkFeExistByIpOrFqdn(String ipOrFqdn) throws UnknownHostException {
Pair<String, String> targetIpAndFqdn = NetUtils.getIpAndFqdnByHost(ipOrFqdn);
for (Frontend fe : frontends.values()) {
Pair<String, String> curIpAndFqdn;
try {
curIpAndFqdn = NetUtils.getIpAndFqdnByHost(fe.getHost());
} catch (UnknownHostException e) {
LOG.warn("failed to get right ip by fqdn {}", fe.getHost(), e);
if (targetIpAndFqdn.second.equals(fe.getHost())
&& !Strings.isNullOrEmpty(targetIpAndFqdn.second)) {
return true;
}
continue;
}
// target, cur has same ip
if (targetIpAndFqdn.first.equals(curIpAndFqdn.first)) {
return true;
}
// target, cur has same fqdn and both of them are not equal ""
if (targetIpAndFqdn.second.equals(curIpAndFqdn.second)
&& !Strings.isNullOrEmpty(targetIpAndFqdn.second)) {
return true;
}
}
return false;
} | @Test
public void testCheckFeExistByIpOrFqdn() throws UnknownHostException {
NodeMgr nodeMgr = new NodeMgr();
nodeMgr.replayAddFrontend(new Frontend(FrontendNodeType.FOLLOWER, "node1", "localhost", 9010));
Assert.assertTrue(nodeMgr.checkFeExistByIpOrFqdn("localhost"));
Assert.assertTrue(nodeMgr.checkFeExistByIpOrFqdn("127.0.0.1"));
} |
@Override
public boolean unregister(final Application application) {
if(!ServiceManagementFunctions.library.SMLoginItemSetEnabled(application.getIdentifier(), false)) {
log.warn(String.format("Failed to remove %s as login item", application));
return false;
}
return true;
} | @Test
public void testUnregister() {
assertFalse(new ServiceManagementApplicationLoginRegistry().unregister(
new Application("bundle.helper")));
} |
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId,
@RequestParam("namespaceName") String namespaceName,
@RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) {
if (StringUtils.isBlank(namespaceId)) {
namespaceId = UUID.randomUUID().toString();
} else {
namespaceId = namespaceId.trim();
if (!namespaceIdCheckPattern.matcher(namespaceId).matches()) {
return false;
}
if (namespaceId.length() > NAMESPACE_ID_MAX_LENGTH) {
return false;
}
// check unique
if (namespacePersistService.tenantInfoCountByTenantId(namespaceId) > 0) {
return false;
}
}
// contains illegal chars
if (!namespaceNameCheckPattern.matcher(namespaceName).matches()) {
return false;
}
try {
return namespaceOperationService.createNamespace(namespaceId, namespaceName, namespaceDesc);
} catch (NacosException e) {
return false;
}
} | @Test
void testCreateNamespaceWithLongCustomId() throws Exception {
StringBuilder longId = new StringBuilder();
for (int i = 0; i < 129; i++) {
longId.append("a");
}
assertFalse(namespaceController.createNamespace(longId.toString(), "testName", "testDesc"));
verify(namespaceOperationService, never()).createNamespace(longId.toString(), "testName", "testDesc");
} |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testCaseInsensitiveNot() {
Evaluator evaluator = new Evaluator(STRUCT, not(equal("X", 7)), false);
assertThat(evaluator.eval(TestHelpers.Row.of(7))).as("not(7 == 7) => false").isFalse();
assertThat(evaluator.eval(TestHelpers.Row.of(8))).as("not(8 == 7) => false").isTrue();
Evaluator structEvaluator = new Evaluator(STRUCT, not(equal("s1.s2.s3.s4.i", 7)), false);
assertThat(
structEvaluator.eval(
TestHelpers.Row.of(
7,
null,
null,
TestHelpers.Row.of(
TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(7)))))))
.as("not(7 == 7) => false")
.isFalse();
assertThat(
structEvaluator.eval(
TestHelpers.Row.of(
8,
null,
null,
TestHelpers.Row.of(
TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(8)))))))
.as("not(8 == 7) => false")
.isTrue();
} |
@ConstantFunction(name = "bitor", argTypes = {INT, INT}, returnType = INT)
public static ConstantOperator bitorInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt(first.getInt() | second.getInt());
} | @Test
public void bitorInt() {
assertEquals(10, ScalarOperatorFunctions.bitorInt(O_INT_10, O_INT_10).getInt());
} |
RegistryEndpointProvider<URL> writer(URL location, Consumer<Long> writtenByteCountListener) {
return new Writer(location, writtenByteCountListener);
} | @Test
public void testWriter_handleResponse() throws IOException, RegistryException {
Mockito.when(mockResponse.getHeader("Location"))
.thenReturn(Collections.singletonList("https://somenewurl/location"));
GenericUrl requestUrl = new GenericUrl("https://someurl");
Mockito.when(mockResponse.getRequestUrl()).thenReturn(requestUrl);
Assert.assertEquals(
new URL("https://somenewurl/location"),
testBlobPusher.writer(mockUrl, ignored -> {}).handleResponse(mockResponse));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.