focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public String getRomOAID() {
Uri uri = Uri.parse("content://com.vivo.vms.IdProvider/IdentifierId/OAID");
String oaid = null;
Cursor cursor = null;
try {
cursor = mContext.getContentResolver().query(uri, null, null,
null, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex("value");
oaid = cursor.getString(index);
if (oaid == null || oaid.length() == 0) {
SALog.i(TAG, "OAID query failed");
}
}
} catch (Throwable th) {
SALog.i(TAG, th);
} finally {
if (cursor != null) {
cursor.close();
}
}
return oaid;
}
|
@Test
public void getRomOAID() {
VivoImpl vivo = new VivoImpl(mApplication);
// if (vivo.isSupported()) {
// Assert.assertNull(vivo.getRomOAID());
// }
}
|
public static String removeTrailingSlashes(String path) {
return TRAILING_SLASH_PATTERN.matcher(path).replaceFirst("");
}
|
@Test
public void removeTrailingSlashes_whenNoTrailingSlashes_returnsOriginal() {
assertThat(removeTrailingSlashes("/a/b/c")).isEqualTo("/a/b/c");
}
|
BeanLevelInfo getFinalPath( BeanInjectionInfo.Property property ) {
return ( !property.getPath().isEmpty() ) ? property.getPath().get( property.getPath().size() - 1 ) : null;
}
|
@Test
public void getFinalPath_Null() {
BeanInjector bi = new BeanInjector(null );
BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class );
BeanInjectionInfo.Property noPathProperty = bii. new Property("name", "groupName",
Collections.EMPTY_LIST );
assertNull(bi.getFinalPath( noPathProperty ) );
}
|
@Override
public EpoxyModel<?> remove(int index) {
notifyRemoval(index, 1);
return super.remove(index);
}
|
@Test
public void testRemoveIndex() {
EpoxyModel<?> removedModel = modelList.remove(0);
assertFalse(modelList.contains(removedModel));
assertEquals(2, modelList.size());
verify(observer).onItemRangeRemoved(0, 1);
}
|
@Override public Scope decorateScope(@Nullable TraceContext context, Scope scope) {
if (scope == Scope.NOOP) return scope; // we only scope fields constant in the context
ScopeEvent event = new ScopeEvent();
if (!event.isEnabled()) return scope;
if (context != null) {
event.traceId = context.traceIdString();
event.parentId = context.parentIdString();
event.spanId = context.spanIdString();
}
event.begin();
class JfrCurrentTraceContextScope implements Scope {
@Override public void close() {
scope.close();
event.commit();
}
}
return new JfrCurrentTraceContextScope();
}
|
@Test void doesntDecorateNoop() {
assertThat(decorator.decorateScope(context, Scope.NOOP)).isSameAs(Scope.NOOP);
assertThat(decorator.decorateScope(null, Scope.NOOP)).isSameAs(Scope.NOOP);
}
|
@Override public GrpcClientRequest request() {
return request;
}
|
@Test void request() {
assertThat(response.request()).isSameAs(request);
}
|
@Override
public void process(final Exchange exchange) throws Exception {
component.getRoutingProcessor(configuration.getChannel())
.process(exchange);
}
|
@Test
void testProcessAsynchronous() {
when(configuration.getChannel()).thenReturn("testChannel");
when(component.getRoutingProcessor(anyString())).thenReturn(processor);
boolean result = producer.process(exchange, asyncCallback);
assertFalse(result);
}
|
public synchronized String encrypt(String keyRingId, String keyId, String message) {
CryptoKeyName keyName = CryptoKeyName.of(projectId, region, keyRingId, keyId);
LOG.info("Encrypting given message using key {}.", keyName.toString());
try (KeyManagementServiceClient client = clientFactory.getKMSClient()) {
EncryptResponse response = client.encrypt(keyName, ByteString.copyFromUtf8(message));
LOG.info("Successfully encrypted message.");
return new String(
Base64.getEncoder().encode(response.getCiphertext().toByteArray()),
StandardCharsets.UTF_8);
}
}
|
@Test
public void testEncryptShouldEncodeEncryptedMessageWithBase64() {
String ciphertext = "ciphertext";
EncryptResponse encryptedResponse =
EncryptResponse.newBuilder().setCiphertext(ByteString.copyFromUtf8(ciphertext)).build();
when(kmsClientFactory.getKMSClient()).thenReturn(serviceClient);
when(serviceClient.encrypt(any(CryptoKeyName.class), any(ByteString.class)))
.thenReturn(encryptedResponse);
String encryptedMessage = testManager.encrypt(KEYRING_ID, KEY_ID, "test message");
String actual =
new String(
Base64.getDecoder().decode(encryptedMessage.getBytes(StandardCharsets.UTF_8)),
StandardCharsets.UTF_8);
assertThat(actual).isEqualTo(ciphertext);
}
|
public static Labels fromString(String stringLabels) throws IllegalArgumentException {
Map<String, String> labels = new HashMap<>();
try {
if (stringLabels != null && !stringLabels.isEmpty()) {
String[] labelsArray = stringLabels.split(",");
for (String label : labelsArray) {
String[] fields = label.split("=");
labels.put(fields[0].trim(), fields[1].trim());
}
}
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse labels from string " + stringLabels, e);
}
return new Labels(labels);
}
|
@Test
public void testParseInvalidLabels1() {
assertThrows(IllegalArgumentException.class, () -> {
String invalidLabels = ",key1=value1,key2=value2";
Labels.fromString(invalidLabels);
});
}
|
public static FieldScope none() {
return FieldScopeImpl.none();
}
|
@Test
public void testFieldScopes_none() {
Message message = parse("o_int: 3 r_string: \"foo\"");
Message diffMessage = parse("o_int: 5 r_string: \"bar\"");
expectThat(diffMessage).ignoringFieldScope(FieldScopes.none()).isNotEqualTo(message);
expectThat(diffMessage).withPartialScope(FieldScopes.none()).isEqualTo(message);
expectFailureWhenTesting()
.that(diffMessage)
.withPartialScope(FieldScopes.none())
.isNotEqualTo(message);
expectIsNotEqualToFailed();
expectThatFailure().hasMessageThat().contains("ignored: o_int");
expectThatFailure().hasMessageThat().contains("ignored: r_string");
}
|
@Override
@CacheEvict(value = RedisKeyConstants.ROLE, key = "#updateReqVO.id")
@LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_UPDATE_SUB_TYPE, bizNo = "{{#updateReqVO.id}}",
success = SYSTEM_ROLE_UPDATE_SUCCESS)
public void updateRole(RoleSaveReqVO updateReqVO) {
// 1.1 校验是否可以更新
RoleDO role = validateRoleForUpdate(updateReqVO.getId());
// 1.2 校验角色的唯一字段是否重复
validateRoleDuplicate(updateReqVO.getName(), updateReqVO.getCode(), updateReqVO.getId());
// 2. 更新到数据库
RoleDO updateObj = BeanUtils.toBean(updateReqVO, RoleDO.class);
roleMapper.updateById(updateObj);
// 3. 记录操作日志上下文
LogRecordContext.putVariable("role", role);
}
|
@Test
public void testUpdateRole() {
// mock 数据
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType()));
roleMapper.insert(roleDO);
// 准备参数
Long id = roleDO.getId();
RoleSaveReqVO reqVO = randomPojo(RoleSaveReqVO.class, o -> o.setId(id));
// 调用
roleService.updateRole(reqVO);
// 断言
RoleDO newRoleDO = roleMapper.selectById(id);
assertPojoEquals(reqVO, newRoleDO);
}
|
protected static void parse(OldExcelExtractor extractor, XHTMLContentHandler xhtml)
throws TikaException, IOException, SAXException {
// Get the whole text, as a single string
String text = extractor.getText();
// Split and output
String line;
BufferedReader reader = new BufferedReader(new StringReader(text));
while ((line = reader.readLine()) != null) {
xhtml.startElement("p");
xhtml.characters(line);
xhtml.endElement("p");
}
}
|
@Test
public void testPlainText() throws Exception {
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
try (TikaInputStream stream = getTestFile(file)) {
new OldExcelParser().parse(stream, handler, metadata, new ParseContext());
}
String text = handler.toString();
// Check we find a few words we expect in there
assertContains("Size", text);
assertContains("Returns", text);
// Check we find a few numbers we expect in there
assertContains("11", text);
assertContains("784", text);
}
|
public static boolean isDirectory(URL resourceURL) throws URISyntaxException {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final JarEntry entry = jarConnection.getJarEntry();
if (entry.isDirectory()) {
return true;
}
// WARNING! Heuristics ahead.
// It turns out that JarEntry#isDirectory() really just tests whether the filename ends in a '/'.
// If you try to open the same URL without a trailing '/', it'll succeed — but the result won't be
// what you want. We try to get around this by calling getInputStream() on the file inside the jar.
// This seems to return null for directories (though that behavior is undocumented as far as I
// can tell). If you have a better idea, please improve this.
final String relativeFilePath = entry.getName();
final JarFile jarFile = jarConnection.getJarFile();
final ZipEntry zipEntry = jarFile.getEntry(relativeFilePath);
final InputStream inputStream = jarFile.getInputStream(zipEntry);
return inputStream == null;
} catch (IOException e) {
throw new ResourceNotFoundException(e);
}
case "file":
return new File(resourceURL.toURI()).isDirectory();
default:
throw new IllegalArgumentException("Unsupported protocol " + resourceURL.getProtocol() +
" for resource " + resourceURL);
}
}
|
@Test
void isDirectoryReturnsTrueForDirectoriesWithSpacesInJars() throws Exception {
final URL url = new URL("jar:" + resourceJar.toExternalForm() + "!/dir with space/");
assertThat(url.getProtocol()).isEqualTo("jar");
assertThat(ResourceURL.isDirectory(url)).isTrue();
}
|
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
}
|
@Test
public void when_addNonexistentZipOfJarsWithPath_then_throwsException() {
// Given
String path = Paths.get("/i/do/not/exist").toString();
// Then
expectedException.expect(JetException.class);
expectedException.expectMessage("Not an existing, readable file: " + path);
// When
config.addJarsInZip(path);
}
|
public String serializeJob(Job job) {
return jsonMapper.serialize(job);
}
|
@Test
void onIllegalJobParameterCorrectExceptionIsThrown() {
TestService.IllegalWork illegalWork = new TestService.IllegalWork(5);
Job job = anEnqueuedJob()
.withJobDetails(() -> testService.doIllegalWork(illegalWork))
.build();
assertThatCode(() -> jobMapper.serializeJob(job))
.isInstanceOf(JobParameterJsonMapperException.class)
.isNotExactlyInstanceOf(JobRunrException.class);
}
|
@Override
public String toString() {
return getClass().getSimpleName() + "[period=" + getPeriod() + ", startDate="
+ getStartDate() + ", endDate=" + getEndDate() + ']';
}
|
@Test
public void testToString() {
final String string = periodRange.toString();
assertNotNull("toString not null", string);
assertFalse("toString not empty", string.isEmpty());
final String string2 = customRange.toString();
assertNotNull("toString not null", string2);
assertFalse("toString not empty", string2.isEmpty());
}
|
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (statement.getStatement() instanceof CreateSource) {
return handleCreateSource((ConfiguredStatement<CreateSource>) statement);
}
return statement;
}
|
@Test
public void shouldInjectMissingKeyAndValueFormat() {
// Given
givenConfig(ImmutableMap.of(
KsqlConfig.KSQL_DEFAULT_KEY_FORMAT_CONFIG, "KAFKA",
KsqlConfig.KSQL_DEFAULT_VALUE_FORMAT_CONFIG, "JSON"
));
givenSourceProps(ImmutableMap.of());
// When
final ConfiguredStatement<?> result = injector.inject(csStatement);
// Then
assertThat(result.getMaskedStatementText(), containsString("KEY_FORMAT='KAFKA'"));
assertThat(result.getMaskedStatementText(), containsString("VALUE_FORMAT='JSON'"));
}
|
@VisibleForTesting
public int getClusterMetricsFailedRetrieved() {
return numGetClusterMetricsFailedRetrieved.value();
}
|
@Test
public void testGetClusterMetricsFailed() {
long totalBadbefore = metrics.getClusterMetricsFailedRetrieved();
badSubCluster.getClusterMetrics();
Assert.assertEquals(totalBadbefore + 1,
metrics.getClusterMetricsFailedRetrieved());
}
|
@Override
public Host filter(final KsqlHostInfo host) {
if (host.host().equals(activeHost.host()) && host.port() == activeHost.port()) {
return Host.include(host);
}
return Host.exclude(host, "Host is not the active host for this partition.");
}
|
@Test
public void shouldFilterActive() {
// Given:
// When:
final Host filterActive = activeHostFilter.filter(activeHost);
final Host filterStandby = activeHostFilter.filter(standByHost);
// Then:
assertThat(filterActive.isSelected(), is(true));
assertThat(filterStandby.isSelected(), is(false));
assertThat(filterStandby.getReasonNotSelected(), is("Host is not the active host for this partition."));
}
|
@Override
public String getRomOAID() {
String oaid = null;
try {
Intent intent = new Intent("com.asus.msa.action.ACCESS_DID");
ComponentName componentName = new ComponentName("com.asus.msa.SupplementaryDID", "com.asus.msa.SupplementaryDID.SupplementaryDIDService");
intent.setComponent(componentName);
if (mContext.bindService(intent, mService, Context.BIND_AUTO_CREATE)) {
AsusInterface anInterface = new AsusInterface(OAIDService.BINDER_QUEUE.take());
oaid = anInterface.getOAID();
mContext.unbindService(mService);
}
} catch (Throwable th) {
SALog.i(TAG, th);
}
return oaid;
}
|
@Test
public void getRomOAID() {
AsusImpl asus = new AsusImpl(mApplication);
// if(asus.isSupported()) {
// Assert.assertNull(asus.getRomOAID());
// }
}
|
@Override
protected Result[] run(String value) {
final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly);
// the extractor instance is rebuilt every second anyway
final Match match = grok.match(value);
final Map<String, Object> matches = match.captureFlattened();
final List<Result> results = new ArrayList<>(matches.size());
for (final Map.Entry<String, Object> entry : matches.entrySet()) {
// never add null values to the results, those don't make sense for us
if (entry.getValue() != null) {
results.add(new Result(entry.getValue(), entry.getKey(), -1, -1));
}
}
return results.toArray(new Result[0]);
}
|
@Test
public void testIssue5563() {
// See: https://github.com/Graylog2/graylog2-server/issues/5563
// https://github.com/Graylog2/graylog2-server/issues/5704
final Map<String, Object> config = new HashMap<>();
config.put("named_captures_only", true);
patternSet.add(GrokPattern.create("YOLO", "(?<test_field>test)"));
// Make sure that the user can use a capture name with an "_".
final GrokExtractor extractor = makeExtractor("%{YOLO}", config);
assertThat(extractor.run("test"))
.hasSize(1)
.containsOnly(
new Extractor.Result("test", "test_field", -1, -1)
);
}
|
@Subscribe
public void inputDeleted(InputDeleted inputDeletedEvent) {
LOG.debug("Input deleted: {}", inputDeletedEvent.id());
final IOState<MessageInput> inputState = inputRegistry.getInputState(inputDeletedEvent.id());
if (inputState != null) {
inputRegistry.remove(inputState);
}
}
|
@Test
public void inputDeletedDoesNothingIfInputIsNotRunning() throws Exception {
final String inputId = "input-id";
@SuppressWarnings("unchecked")
final IOState<MessageInput> inputState = mock(IOState.class);
when(inputState.getState()).thenReturn(null);
when(inputRegistry.getInputState(inputId)).thenReturn(inputState);
listener.inputDeleted(InputDeleted.create(inputId));
verify(inputRegistry, never()).remove(any(MessageInput.class));
}
|
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
|
@Test
public void testSetArtifactId() {
String artifactId = "aaa";
String expected = "aaa";
Model instance = new Model();
instance.setArtifactId(artifactId);
assertEquals(expected, instance.getArtifactId());
}
|
@Override
public ConfigData get(String path) {
return get(path, Files::isRegularFile);
}
|
@Test
public void testGetAllKeysAtPath() {
ConfigData configData = provider.get(dir);
assertEquals(toSet(asList(foo, bar)), configData.data().keySet());
assertEquals("FOO", configData.data().get(foo));
assertEquals("BAR", configData.data().get(bar));
assertNull(configData.ttl());
}
|
@Override
public CompletableFuture<List<Long>> getSplitBoundary(BundleSplitOption bundleSplitOption) {
NamespaceBundle bundle = bundleSplitOption.getBundle();
return CompletableFuture.completedFuture(Collections.singletonList(bundle.getLowerEndpoint()
+ (bundle.getUpperEndpoint() - bundle.getLowerEndpoint()) / 2));
}
|
@Test
public void testGetSplitBoundaryMethodReturnCorrectResult() {
RangeEquallyDivideBundleSplitAlgorithm rangeEquallyDivideBundleSplitAlgorithm = new RangeEquallyDivideBundleSplitAlgorithm();
Assert.assertThrows(NullPointerException.class, () -> rangeEquallyDivideBundleSplitAlgorithm.getSplitBoundary(new BundleSplitOption()));
long lowerRange = 10L;
long upperRange = 0xffffffffL;
long correctResult = lowerRange + (upperRange - lowerRange) / 2;
NamespaceBundle namespaceBundle = new NamespaceBundle(NamespaceName.SYSTEM_NAMESPACE, Range.range(lowerRange, BoundType.CLOSED, upperRange, BoundType.CLOSED),
Mockito.mock(NamespaceBundleFactory.class));
CompletableFuture<List<Long>> splitBoundary = rangeEquallyDivideBundleSplitAlgorithm.getSplitBoundary(new BundleSplitOption(null, namespaceBundle, null));
List<Long> value = splitBoundary.join();
Assert.assertEquals((long)value.get(0), correctResult);
}
|
public static RuleViolation isStandard(Transaction tx) {
// TODO: Finish this function off.
if (tx.getVersion() > 2 || tx.getVersion() < 1) {
log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion());
return RuleViolation.VERSION;
}
final List<TransactionOutput> outputs = tx.getOutputs();
for (int i = 0; i < outputs.size(); i++) {
TransactionOutput output = outputs.get(i);
RuleViolation violation = isOutputStandard(output);
if (violation != RuleViolation.NONE) {
log.warn("TX considered non-standard due to output {} violating rule {}", i, violation);
return violation;
}
}
final List<TransactionInput> inputs = tx.getInputs();
for (int i = 0; i < inputs.size(); i++) {
TransactionInput input = inputs.get(i);
RuleViolation violation = isInputStandard(input);
if (violation != RuleViolation.NONE) {
log.warn("TX considered non-standard due to input {} violating rule {}", i, violation);
return violation;
}
}
return RuleViolation.NONE;
}
|
@Test
public void nonShortestPossiblePushData() {
ScriptChunk nonStandardChunk = new ScriptChunk(OP_PUSHDATA1, new byte[75]);
byte[] nonStandardScript = new ScriptBuilder().addChunk(nonStandardChunk).build().program();
// Test non-standard script as an input.
Transaction tx = new Transaction();
assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx));
tx.addInput(new TransactionInput(null, nonStandardScript, TransactionOutPoint.UNCONNECTED));
assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx));
// Test non-standard script as an output.
tx.clearInputs();
assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx));
tx.addOutput(new TransactionOutput(null, COIN, nonStandardScript));
assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx));
}
|
@Override
public RefreshNodesResourcesResponse refreshNodesResources(RefreshNodesResourcesRequest request)
throws YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrRefreshNodesResourcesFailedRetrieved();
RouterServerUtil.logAndThrowException("Missing RefreshNodesResources request.", null);
}
String subClusterId = request.getSubClusterId();
if (StringUtils.isBlank(subClusterId)) {
routerMetrics.incrRefreshNodesResourcesFailedRetrieved();
RouterServerUtil.logAndThrowException("Missing RefreshNodesResources SubClusterId.", null);
}
try {
long startTime = clock.getTime();
RMAdminProtocolMethod remoteMethod = new RMAdminProtocolMethod(
new Class[]{RefreshNodesResourcesRequest.class}, new Object[]{request});
Collection<RefreshNodesResourcesResponse> refreshNodesResourcesResps =
remoteMethod.invokeConcurrent(this, RefreshNodesResourcesResponse.class, subClusterId);
if (CollectionUtils.isNotEmpty(refreshNodesResourcesResps)) {
long stopTime = clock.getTime();
routerMetrics.succeededRefreshNodesResourcesRetrieved(stopTime - startTime);
return RefreshNodesResourcesResponse.newInstance();
}
} catch (YarnException e) {
routerMetrics.incrRefreshNodesResourcesFailedRetrieved();
RouterServerUtil.logAndThrowException(e,
"Unable to refreshNodesResources due to exception. " + e.getMessage());
}
routerMetrics.incrRefreshNodesResourcesFailedRetrieved();
throw new YarnException("Unable to refreshNodesResources.");
}
|
@Test
public void testRefreshNodesResourcesEmptyRequest() throws Exception {
// null request1.
LambdaTestUtils.intercept(YarnException.class, "Missing RefreshNodesResources request.",
() -> interceptor.refreshNodesResources(null));
// null request2.
RefreshNodesResourcesRequest request = RefreshNodesResourcesRequest.newInstance();
LambdaTestUtils.intercept(YarnException.class, "Missing RefreshNodesResources SubClusterId.",
() -> interceptor.refreshNodesResources(request));
}
|
@Override
public OffsetFetchResponseData data() {
return data;
}
|
@Test
public void testUseDefaultLeaderEpochV8() {
final Optional<Integer> emptyLeaderEpoch = Optional.empty();
partitionDataMap.clear();
partitionDataMap.put(new TopicPartition(topicOne, partitionOne),
new PartitionData(
offset,
emptyLeaderEpoch,
metadata,
Errors.UNKNOWN_TOPIC_OR_PARTITION)
);
OffsetFetchResponse response = new OffsetFetchResponse(
throttleTimeMs,
Collections.singletonMap(groupOne, Errors.NOT_COORDINATOR),
Collections.singletonMap(groupOne, partitionDataMap));
OffsetFetchResponseData expectedData =
new OffsetFetchResponseData()
.setGroups(Collections.singletonList(
new OffsetFetchResponseGroup()
.setGroupId(groupOne)
.setTopics(Collections.singletonList(
new OffsetFetchResponseTopics()
.setName(topicOne)
.setPartitions(Collections.singletonList(
new OffsetFetchResponsePartitions()
.setPartitionIndex(partitionOne)
.setCommittedOffset(offset)
.setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH)
.setErrorCode(Errors.UNKNOWN_TOPIC_OR_PARTITION.code())
.setMetadata(metadata)))))
.setErrorCode(Errors.NOT_COORDINATOR.code())))
.setThrottleTimeMs(throttleTimeMs);
assertEquals(expectedData, response.data());
}
|
public static <T extends Comparable<T>> Pair<Integer, T> argmax(List<T> values) {
if (values.isEmpty()) {
throw new IllegalArgumentException("argmax on an empty list");
}
//
// There is no "globally min" value like -Inf for an arbitrary type T so we just pick the first list element
T vmax = values.get(0);
int imax = 0;
for (int i = 1; i < values.size(); i++) {
T v = values.get(i);
if (v.compareTo(vmax) > 0) {
vmax = v;
imax = i;
}
}
return new Pair<>(imax, vmax);
}
|
@Test
public void testArgmax() {
assertThrows(IllegalArgumentException.class, () -> Util.argmax(new ArrayList<Double>()));
List<Integer> lst = Collections.singletonList(1);
Pair<Integer, Integer> argmax = Util.argmax(lst);
assertEquals(0, argmax.getA());
assertEquals(1, argmax.getB());
lst = Arrays.asList(3, 2, 1);
argmax = Util.argmax(lst);
assertEquals(0, argmax.getA());
assertEquals(3, argmax.getB());
}
|
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
}
|
@Test
public void testCancelAsync() throws InterruptedException {
RedissonClient r1 = createInstance();
AtomicInteger iterations = new AtomicInteger();
ExecutorService executor = Executors.newSingleThreadExecutor();
r1.getRemoteService().register(RemoteInterface.class, new RemoteImpl(iterations), 1, executor);
RedissonClient r2 = createInstance();
RemoteInterfaceAsync ri = r2.getRemoteService().get(RemoteInterfaceAsync.class);
RFuture<Void> f = ri.cancelMethod();
Thread.sleep(500);
assertThat(f.cancel(true)).isTrue();
executor.shutdown();
r1.shutdown();
r2.shutdown();
assertThat(iterations.get()).isLessThan(Integer.MAX_VALUE / 2);
assertThat(executor.awaitTermination(2, TimeUnit.SECONDS)).isTrue();
}
|
@Override
public void exists(final String path, final boolean watch, final AsyncCallback.StatCallback cb, final Object ctx)
{
if (!SymlinkUtil.containsSymlink(path))
{
_zk.exists(path, watch, cb, ctx);
}
else
{
SymlinkStatCallback compositeCallback = new SymlinkStatCallback(path, _defaultWatcher, cb);
exists0(path, watch ? compositeCallback : null, compositeCallback, ctx);
}
}
|
@Test
public void testSymlinkWithExistWatch2() throws InterruptedException, ExecutionException
{
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AsyncCallback.StatCallback existCallback = new AsyncCallback.StatCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, Stat stat)
{
KeeperException.Code result = KeeperException.Code.get(rc);
Assert.assertEquals(result, KeeperException.Code.OK);
latch.countDown();
}
};
Watcher existWatch = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
Assert.assertEquals(event.getType(), Event.EventType.NodeDataChanged);
_zkClient.getZooKeeper().exists(event.getPath(), null, existCallback, null);
}
};
AsyncCallback.StatCallback existCallback2 = new AsyncCallback.StatCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, Stat stat)
{
KeeperException.Code result = KeeperException.Code.get(rc);
Assert.assertEquals(result, KeeperException.Code.NONODE);
latch2.countDown();
}
};
// symlink: /foo/$link/foo -> /foo/bar/foo, which doesn't exist
_zkClient.getZooKeeper().exists("/foo/$link/foo", existWatch, existCallback2, null);
latch2.await(30, TimeUnit.SECONDS);
// update symlink. now it points to /bar/foo, which does exist.
_zkClient.setSymlinkData("/foo/$link", "/bar", new FutureCallback<>());
latch.await(30, TimeUnit.SECONDS);
// restore symlink
_zkClient.setSymlinkData("/foo/$link", "/foo/bar", new FutureCallback<>());
}
|
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
}
|
@Test(expectedExceptions = SemanticException.class, expectedExceptionsMessageRegExp = "line 1:37: Scalar subqueries in UNNEST are not supported")
public void testUnnestInnerScalar()
{
analyze("SELECT * FROM (SELECT 1) CROSS JOIN UNNEST((SELECT array[1])) AS T(x)");
}
|
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0), variables);
} catch (ParseFailedException e) {
throw new MigrationException(String.format(
"Failed to parse the statement. Statement: %s. Reason: %s",
sql, e.getMessage()));
}
final SqlBaseParser.SingleStatementContext statementContext = KSQL_PARSER.parse(substituted)
.get(0).getStatement();
final boolean isStatement = StatementType.get(statementContext.statement().getClass())
== StatementType.STATEMENT;
return new ParsedCommand(substituted,
isStatement ? Optional.empty() : Optional.of(new AstBuilder(TypeRegistry.EMPTY)
.buildStatement(statementContext)));
}
|
@Test
public void shouldParseDropConnectorStatement() {
// Given:
final String dropConnector = "DRoP CONNEcTOR `jdbc-connector` ;"; // The space at the end is intentional
// When:
List<CommandParser.ParsedCommand> commands = parse(dropConnector);
// Then:
assertThat(commands.size(), is(1));
assertThat(commands.get(0).getCommand(), is(dropConnector));
assertThat(commands.get(0).getStatement().isPresent(), is (true));
assertThat(commands.get(0).getStatement().get(), instanceOf(DropConnector.class));
assertThat(((DropConnector) commands.get(0).getStatement().get()).getConnectorName(), is("jdbc-connector"));
assertThat(((DropConnector) commands.get(0).getStatement().get()).getIfExists(), is(false));
}
|
void fail(Throwable throwable) {
checkArgument(throwable != null, "Must be not null.");
releaseInternal(throwable);
// notify the netty thread which will propagate the error to the consumer task
notifyDataAvailable();
}
|
@Test
void testFail() throws Exception {
int numSegments = 5;
Queue<MemorySegment> segments = createsMemorySegments(numSegments);
try {
CountingAvailabilityListener listener = new CountingAvailabilityListener();
SortMergeSubpartitionReader subpartitionReader =
createSortMergeSubpartitionReader(listener);
subpartitionReader.readBuffers(segments, segments::add);
assertThat(listener.numNotifications).isEqualTo(1);
assertThat(subpartitionReader.unsynchronizedGetNumberOfQueuedBuffers()).isEqualTo(4);
subpartitionReader.fail(new RuntimeException("Test exception."));
assertThat(subpartitionReader.getReleaseFuture()).isDone();
assertThat(subpartitionReader.unsynchronizedGetNumberOfQueuedBuffers()).isZero();
assertThat(subpartitionReader.getAvailabilityAndBacklog(false).isAvailable()).isTrue();
assertThat(subpartitionReader.isReleased()).isTrue();
assertThat(listener.numNotifications).isEqualTo(2);
assertThat(subpartitionReader.getFailureCause()).isNotNull();
} finally {
assertThat(segments).hasSize(numSegments);
}
}
|
public static TableSchema toTableSchema(Schema schema) {
return new TableSchema().setFields(toTableFieldSchema(schema));
}
|
@Test
public void testToTableSchema_row() {
TableSchema schema = toTableSchema(ROW_TYPE);
assertThat(schema.getFields().size(), equalTo(1));
TableFieldSchema field = schema.getFields().get(0);
assertThat(field.getName(), equalTo("row"));
assertThat(field.getType(), equalTo(StandardSQLTypeName.STRUCT.toString()));
assertThat(field.getMode(), nullValue());
assertThat(
field.getFields(),
containsInAnyOrder(
ID,
VALUE,
NAME,
TIMESTAMP_VARIANT1,
TIMESTAMP_VARIANT2,
TIMESTAMP_VARIANT3,
TIMESTAMP_VARIANT4,
TIMESTAMP_VARIANT5,
TIMESTAMP_VARIANT6,
TIMESTAMP_VARIANT7,
TIMESTAMP_VARIANT8,
DATETIME,
DATETIME_0MS,
DATETIME_0S_NS,
DATETIME_0S_0NS,
DATE,
TIME,
TIME_0MS,
TIME_0S_NS,
TIME_0S_0NS,
VALID,
BINARY,
RAW_BYTES,
NUMERIC,
BOOLEAN,
LONG,
DOUBLE));
}
|
public static boolean isValidAndroidId(String androidId) {
if (TextUtils.isEmpty(androidId)) {
return false;
}
return !mInvalidAndroidId.contains(androidId.toLowerCase(Locale.getDefault()));
}
|
@Test
public void isValidAndroidId() {
}
|
@Override
public boolean register(final Application application) {
try {
if(finder.isInstalled(application)) {
service.add(new FinderLocal(workspace.absolutePathForAppBundleWithIdentifier(application.getIdentifier())));
return true;
}
return false;
}
catch(LocalAccessDeniedException e) {
return false;
}
}
|
@Test
public void testRegisterNotInstalled() {
final SharedFileListApplicationLoginRegistry registry = new SharedFileListApplicationLoginRegistry(new DisabledApplicationFinder());
assertFalse(registry.register(new Application("ch.sudo.cyberduck")));
}
|
public RewriteGroupedCode rewrite(String context) {
BlockStatementGrouperVisitor visitor =
new BlockStatementGrouperVisitor(maxMethodLength, parameters);
visitor.visitStatement(topStatement, context);
final Map<String, List<String>> groupStrings = visitor.rewrite(rewriter);
return new RewriteGroupedCode(rewriter.getText(), groupStrings);
}
|
@Test
public void testExtractWhileInIfGroups() {
String parameters = "a, b";
String givenBlock = readResource("groups/code/WhileInIf.txt");
String expectedBlock = readResource("groups/expected/WhileInIf.txt");
BlockStatementGrouper grouper = new BlockStatementGrouper(givenBlock, 10, parameters);
RewriteGroupedCode rewriteGroupedCode = grouper.rewrite("myFun");
String rewriteCode = rewriteGroupedCode.getRewriteCode();
Map<String, List<String>> groups = rewriteGroupedCode.getGroups();
// Trying to mitigate any indentation issues between all sort of platforms by simply
// trim every line of the "class". Before this change, code-splitter test could fail on
// Windows machines while passing on Unix.
assertThat(trimLines(rewriteCode)).isEqualTo(trimLines(expectedBlock));
assertThat(groups).hasSize(5);
List<String> group1 = groups.get("myFun_rewriteGroup0_1_rewriteGroup2_3_rewriteGroup5");
assertThat(group1).hasSize(2);
assertThat(group1.get(0)).isEqualTo("myFun_whileBody0_0(a, b);");
assertThat(trimLines(group1.get(1)))
.isEqualTo(
trimLines(
""
+ " if (a[0] > 0) {\n"
+ " myFun_whileBody0_0_ifBody0(a, b);\n"
+ " } else {\n"
+ " myFun_whileBody0_0_ifBody1(a, b);\n"
+ " }"));
List<String> group2 = groups.get("myFun_rewriteGroup0_1_rewriteGroup6");
assertThat(group2).hasSize(1);
assertThat(trimLines(group2.get(0)))
.isEqualTo(
trimLines(
""
+ "while (counter > 0) {\n"
+ " myFun_rewriteGroup0_1_rewriteGroup2_3_rewriteGroup5(a, b);\n"
+ " counter--;\n"
+ "}"));
List<String> group3 = groups.get("myFun_rewriteGroup0_1_rewriteGroup7");
assertThat(group3).containsExactly("a[2] += b[2];", "b[3] += a[3];");
List<String> group4 = groups.get("myFun_rewriteGroup8");
assertThat(group4).hasSize(3);
assertThat(group4.get(0)).isEqualTo("a[0] += b[1];");
assertThat(group4.get(1)).isEqualTo("b[1] += a[1];");
assertThat(trimLines(group4.get(2)))
.isEqualTo(
trimLines(
"if (a.length < 100) {\n"
+ " myFun_rewriteGroup0_1_rewriteGroup6(a, b);\n"
+ " \n"
+ " myFun_rewriteGroup0_1_rewriteGroup7(a, b);\n"
+ " } else {\n"
+ " while (counter < 100) {\n"
+ " b[4] = b[4]++;\n"
+ " counter++;\n"
+ " }\n"
+ "}"));
List<String> group5 = groups.get("myFun_rewriteGroup9");
assertThat(group5).containsExactly("a[5] += b[5];", "b[6] += a[6];");
}
|
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
|
@Test
void testIsBlank() throws Exception {
assertTrue(StringUtils.isBlank(null));
assertTrue(StringUtils.isBlank(""));
assertFalse(StringUtils.isBlank("abc"));
}
|
public static String truncateUtf8(String str, int maxBytes) {
Charset charset = StandardCharsets.UTF_8;
//UTF-8编码单个字符最大长度4
return truncateByByteLength(str, charset, maxBytes, 4, true);
}
|
@Test
public void truncateUtf8Test2() {
final String str = "这是This一";
final String ret = StrUtil.truncateUtf8(str, 13);
assertEquals("这是This一", ret);
}
|
@Override
public Optional<ConfigTable> readConfig(Set<String> keys) {
removeUninterestedKeys(keys);
registerKeyListeners(keys);
final ConfigTable table = new ConfigTable();
configItemKeyedByName.forEach((key, value) -> {
if (value.isPresent()) {
table.add(new ConfigTable.ConfigItem(key, value.get()));
} else {
table.add(new ConfigTable.ConfigItem(key, null));
}
});
return Optional.of(table);
}
|
@Test
public void shouldUnsubscribeWhenKeyRemoved() {
cacheByKey = new ConcurrentHashMap<>();
KVCache existedCache = mock(KVCache.class);
cacheByKey.put("existedKey", existedCache);
configItemKeyedByName = new ConcurrentHashMap<>();
Whitebox.setInternalState(register, "cachesByKey", cacheByKey);
Whitebox.setInternalState(register, "configItemKeyedByName", configItemKeyedByName);
KVCache cache1 = mock(KVCache.class);
KVCache cache2 = mock(KVCache.class);
ArgumentCaptor<ConsulCache.Listener> listener1 = ArgumentCaptor.forClass(ConsulCache.Listener.class);
ArgumentCaptor<ConsulCache.Listener> listener2 = ArgumentCaptor.forClass(ConsulCache.Listener.class);
try (MockedStatic<KVCache> kvCacheMockedStatic = mockStatic(KVCache.class)) {
kvCacheMockedStatic.when(() -> KVCache.newCache(any(), eq("key1"))).thenReturn(cache1);
kvCacheMockedStatic.when(() -> KVCache.newCache(any(), eq("key2"))).thenReturn(cache2);
when(register.readConfig(any(Set.class))).thenCallRealMethod();
register.readConfig(Sets.newHashSet("key1", "key2"));
verify(cache1).addListener(listener1.capture());
verify(cache2).addListener(listener2.capture());
verify(existedCache).stop();
}
}
|
@Override
public void removeSensor(final Sensor sensor) {
Objects.requireNonNull(sensor, "Sensor is null");
metrics.removeSensor(sensor.name());
final Sensor parent = parentSensors.remove(sensor);
if (parent != null) {
metrics.removeSensor(parent.name());
}
}
|
@Test
public void testRemoveSensor() {
final String sensorName = "sensor1";
final String scope = "scope";
final String entity = "entity";
final String operation = "put";
final Sensor sensor1 = streamsMetrics.addSensor(sensorName, RecordingLevel.DEBUG);
streamsMetrics.removeSensor(sensor1);
final Sensor sensor1a = streamsMetrics.addSensor(sensorName, RecordingLevel.DEBUG, sensor1);
streamsMetrics.removeSensor(sensor1a);
final Sensor sensor2 = streamsMetrics.addLatencyRateTotalSensor(scope, entity, operation, RecordingLevel.DEBUG);
streamsMetrics.removeSensor(sensor2);
final Sensor sensor3 = streamsMetrics.addRateTotalSensor(scope, entity, operation, RecordingLevel.DEBUG);
streamsMetrics.removeSensor(sensor3);
assertEquals(Collections.emptyMap(), streamsMetrics.parentSensors());
}
|
@VisibleForTesting
static String truncateLongClasspath(ImmutableList<String> imageEntrypoint) {
List<String> truncated = new ArrayList<>();
UnmodifiableIterator<String> iterator = imageEntrypoint.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
truncated.add(element);
if (element.equals("-cp") || element.equals("-classpath")) {
String classpath = iterator.next();
if (classpath.length() > 200) {
truncated.add(classpath.substring(0, 200) + "<... classpath truncated ...>");
} else {
truncated.add(classpath);
}
}
}
return truncated.toString();
}
|
@Test
public void testTruncateLongClasspath_longClasspath() {
String classpath =
"/app/resources:/app/classes:/app/libs/spring-boot-starter-web-2.0.3.RELEASE.jar:/app/libs/"
+ "shared-library-0.1.0.jar:/app/libs/spring-boot-starter-json-2.0.3.RELEASE.jar:/app/"
+ "libs/spring-boot-starter-2.0.3.RELEASE.jar:/app/libs/spring-boot-starter-tomcat-2.0."
+ "3.RELEASE.jar";
ImmutableList<String> entrypoint =
ImmutableList.of("java", "-Dmy-property=value", "-cp", classpath, "com.example.Main");
Assert.assertEquals(
"[java, -Dmy-property=value, -cp, /app/resources:/app/classes:/app/libs/spring-boot-starter"
+ "-web-2.0.3.RELEASE.jar:/app/libs/shared-library-0.1.0.jar:/app/libs/spring-boot-"
+ "starter-json-2.0.3.RELEASE.jar:/app/libs/spring-boot-starter-2.<... classpath "
+ "truncated ...>, com.example.Main]",
BuildImageStep.truncateLongClasspath(entrypoint));
}
|
private CompletableFuture<Void> seekAsyncInternal(long requestId, ByteBuf seek, MessageId seekId,
Long seekTimestamp, String seekBy) {
AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs());
Backoff backoff = new BackoffBuilder()
.setInitialTime(100, TimeUnit.MILLISECONDS)
.setMax(opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS)
.setMandatoryStop(0, TimeUnit.MILLISECONDS)
.create();
if (!seekStatus.compareAndSet(SeekStatus.NOT_STARTED, SeekStatus.IN_PROGRESS)) {
final String message = String.format(
"[%s][%s] attempting to seek operation that is already in progress (seek by %s)",
topic, subscription, seekBy);
log.warn("[{}][{}] Attempting to seek operation that is already in progress, cancelling {}",
topic, subscription, seekBy);
return FutureUtil.failedFuture(new IllegalStateException(message));
}
seekFuture = new CompletableFuture<>();
seekAsyncInternal(requestId, seek, seekId, seekTimestamp, seekBy, backoff, opTimeoutMs);
return seekFuture;
}
|
@Test
public void testSeekAsyncInternal() {
// given
ClientCnx cnx = mock(ClientCnx.class);
CompletableFuture<ProducerResponse> clientReq = new CompletableFuture<>();
when(cnx.sendRequestWithId(any(ByteBuf.class), anyLong())).thenReturn(clientReq);
ScheduledExecutorProvider provider = mock(ScheduledExecutorProvider.class);
ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
when(provider.getExecutor()).thenReturn(scheduledExecutorService);
when(consumer.getClient().getScheduledExecutorProvider()).thenReturn(provider);
CompletableFuture<Void> result = consumer.seekAsync(1L);
verify(scheduledExecutorService, atLeast(1)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
consumer.setClientCnx(cnx);
consumer.setState(HandlerState.State.Ready);
consumer.seekStatus.set(ConsumerImpl.SeekStatus.NOT_STARTED);
// when
CompletableFuture<Void> firstResult = consumer.seekAsync(1L);
CompletableFuture<Void> secondResult = consumer.seekAsync(1L);
clientReq.complete(null);
assertTrue(firstResult.isDone());
assertTrue(secondResult.isCompletedExceptionally());
verify(cnx, times(1)).sendRequestWithId(any(ByteBuf.class), anyLong());
}
|
@Override
public Object getValue() {
try {
return mBeanServerConn.getAttribute(getObjectName(), attributeName);
} catch (IOException | JMException e) {
return null;
}
}
|
@Test
public void returnsNullIfMBeanNotFound() throws Exception {
ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean");
JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount");
assertThat(gauge.getValue()).isNull();
}
|
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
getExecuteClientProxy(instance).deregisterService(serviceName, groupName, instance);
}
|
@Test
void testDeregisterEphemeralServiceGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setServiceName(serviceName);
instance.setClusterName(groupName);
instance.setIp("1.1.1.1");
instance.setPort(1);
// use grpc
instance.setEphemeral(true);
delegate.deregisterService(serviceName, groupName, instance);
verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance);
}
|
@Override
public Map<String, Map<String, String>> getAdditionalInformation() {
Map<String, Map<String, String>> result = Maps.newHashMap();
result.put("values", values);
return result;
}
|
@Test
public void testGetValues() throws Exception {
Map<String,String> values = Maps.newHashMap();
values.put("foo", "bar");
values.put("zomg", "baz");
DropdownField f = new DropdownField("test", "Name", "fooval", values, ConfigurationField.Optional.NOT_OPTIONAL);
assertEquals(values, f.getAdditionalInformation().get("values"));
}
|
@VisibleForTesting
static boolean isRichConsole(ConsoleOutput consoleOutput, HttpTraceLevel httpTraceLevel) {
if (httpTraceLevel != HttpTraceLevel.off) {
return false;
}
switch (consoleOutput) {
case plain:
return false;
case auto:
// Enables progress footer when ANSI is supported (Windows or TERM not 'dumb').
return System.getProperty("os.name").startsWith("windows")
|| (System.console() != null && !"dumb".equals(System.getenv("TERM")));
case rich:
default:
return true;
}
}
|
@Test
public void testIsRichConsole_true() {
assertThat(CliLogger.isRichConsole(ConsoleOutput.rich, HttpTraceLevel.off)).isTrue();
}
|
String deleteAll(int n) {
return deleteAllQueries.computeIfAbsent(n, deleteAllFactory);
}
|
@Test
public void testDeleteAllIsQuoted() {
Queries queries = new Queries(mapping, idColumn, columnMetadata);
String result = queries.deleteAll(2);
assertEquals("DELETE FROM \"mymapping\" WHERE \"id\" IN (?, ?)", result);
}
|
@VisibleForTesting
public void validateDictDataValueUnique(Long id, String dictType, String value) {
DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value);
if (dictData == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典数据
if (id == null) {
throw exception(DICT_DATA_VALUE_DUPLICATE);
}
if (!dictData.getId().equals(id)) {
throw exception(DICT_DATA_VALUE_DUPLICATE);
}
}
|
@Test
public void testValidateDictDataValueUnique_valueDuplicateForUpdate() {
// 准备参数
Long id = randomLongId();
String dictType = randomString();
String value = randomString();
// mock 数据
dictDataMapper.insert(randomDictDataDO(o -> {
o.setDictType(dictType);
o.setValue(value);
}));
// 调用,校验异常
assertServiceException(() -> dictDataService.validateDictDataValueUnique(id, dictType, value),
DICT_DATA_VALUE_DUPLICATE);
}
|
public void logOnCommitPosition(
final int memberId,
final long leadershipTermId,
final long logPosition,
final int leaderId)
{
final int length = 2 * SIZE_OF_LONG + 2 * SIZE_OF_INT;
final int encodedLength = encodedLength(length);
final ManyToOneRingBuffer ringBuffer = this.ringBuffer;
final int index = ringBuffer.tryClaim(COMMIT_POSITION.toEventCodeId(), encodedLength);
if (index > 0)
{
try
{
ClusterEventEncoder.encodeOnCommitPosition(
(UnsafeBuffer)ringBuffer.buffer(),
index,
length,
length,
memberId,
leadershipTermId,
logPosition,
leaderId);
}
finally
{
ringBuffer.commit(index);
}
}
}
|
@Test
void logOnCommitPosition()
{
final int offset = ALIGNMENT * 4;
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
final long leadershipTermId = 1233L;
final long logPosition = 988723465L;
final int leaderId = 982374;
final int memberId = 2;
logger.logOnCommitPosition(memberId, leadershipTermId, logPosition, leaderId);
final int length = 2 * SIZE_OF_LONG + 2 * SIZE_OF_INT;
verifyLogHeader(logBuffer, offset, COMMIT_POSITION.toEventCodeId(), length, length);
int index = encodedMsgOffset(offset) + LOG_HEADER_LENGTH;
assertEquals(leadershipTermId, logBuffer.getLong(index, LITTLE_ENDIAN));
index += SIZE_OF_LONG;
assertEquals(logPosition, logBuffer.getLong(index, LITTLE_ENDIAN));
index += SIZE_OF_LONG;
assertEquals(leaderId, logBuffer.getInt(index, LITTLE_ENDIAN));
index += SIZE_OF_INT;
assertEquals(memberId, logBuffer.getInt(index, LITTLE_ENDIAN));
final StringBuilder sb = new StringBuilder();
ClusterEventDissector.dissectCommitPosition(COMMIT_POSITION, logBuffer, encodedMsgOffset(offset), sb);
final String expectedMessagePattern = "\\[[0-9]+\\.[0-9]+] CLUSTER: COMMIT_POSITION " +
"\\[24/24]: memberId=2 leadershipTermId=1233 logPosition=988723465 leaderId=982374";
assertThat(sb.toString(), Matchers.matchesPattern(expectedMessagePattern));
}
|
public Mono<CosmosDatabaseResponse> createDatabase(
final String databaseName, final ThroughputProperties throughputProperties) {
CosmosDbUtils.validateIfParameterIsNotEmpty(databaseName, PARAM_DATABASE_NAME);
return client.createDatabaseIfNotExists(databaseName, throughputProperties);
}
|
@Test
void testCreateDatabase() {
final CosmosAsyncClientWrapper client = mock(CosmosAsyncClientWrapper.class);
when(client.createDatabaseIfNotExists(any(), any())).thenReturn(Mono.just(mock(CosmosDatabaseResponse.class)));
final CosmosDbClientOperations operations = CosmosDbClientOperations.withClient(client);
CosmosDbTestUtils.assertIllegalArgumentException(() -> operations.createDatabase(null, null));
CosmosDbTestUtils.assertIllegalArgumentException(() -> operations.createDatabase("", null));
assertNotNull(operations.createDatabase("test", null).block());
}
|
public TopicRouteData pickupTopicRouteData(final String topic) {
TopicRouteData topicRouteData = new TopicRouteData();
boolean foundQueueData = false;
boolean foundBrokerData = false;
List<BrokerData> brokerDataList = new LinkedList<>();
topicRouteData.setBrokerDatas(brokerDataList);
HashMap<String, List<String>> filterServerMap = new HashMap<>();
topicRouteData.setFilterServerTable(filterServerMap);
try {
this.lock.readLock().lockInterruptibly();
Map<String, QueueData> queueDataMap = this.topicQueueTable.get(topic);
if (queueDataMap != null) {
topicRouteData.setQueueDatas(new ArrayList<>(queueDataMap.values()));
foundQueueData = true;
Set<String> brokerNameSet = new HashSet<>(queueDataMap.keySet());
for (String brokerName : brokerNameSet) {
BrokerData brokerData = this.brokerAddrTable.get(brokerName);
if (null == brokerData) {
continue;
}
BrokerData brokerDataClone = new BrokerData(brokerData);
brokerDataList.add(brokerDataClone);
foundBrokerData = true;
if (filterServerTable.isEmpty()) {
continue;
}
for (final String brokerAddr : brokerDataClone.getBrokerAddrs().values()) {
BrokerAddrInfo brokerAddrInfo = new BrokerAddrInfo(brokerDataClone.getCluster(), brokerAddr);
List<String> filterServerList = this.filterServerTable.get(brokerAddrInfo);
filterServerMap.put(brokerAddr, filterServerList);
}
}
}
} catch (Exception e) {
log.error("pickupTopicRouteData Exception", e);
} finally {
this.lock.readLock().unlock();
}
log.debug("pickupTopicRouteData {} {}", topic, topicRouteData);
if (foundBrokerData && foundQueueData) {
topicRouteData.setTopicQueueMappingByBroker(this.topicQueueMappingInfoTable.get(topic));
if (!namesrvConfig.isSupportActingMaster()) {
return topicRouteData;
}
if (topic.startsWith(TopicValidator.SYNC_BROKER_MEMBER_GROUP_PREFIX)) {
return topicRouteData;
}
if (topicRouteData.getBrokerDatas().size() == 0 || topicRouteData.getQueueDatas().size() == 0) {
return topicRouteData;
}
boolean needActingMaster = false;
for (final BrokerData brokerData : topicRouteData.getBrokerDatas()) {
if (brokerData.getBrokerAddrs().size() != 0
&& !brokerData.getBrokerAddrs().containsKey(MixAll.MASTER_ID)) {
needActingMaster = true;
break;
}
}
if (!needActingMaster) {
return topicRouteData;
}
for (final BrokerData brokerData : topicRouteData.getBrokerDatas()) {
final HashMap<Long, String> brokerAddrs = brokerData.getBrokerAddrs();
if (brokerAddrs.size() == 0 || brokerAddrs.containsKey(MixAll.MASTER_ID) || !brokerData.isEnableActingMaster()) {
continue;
}
// No master
for (final QueueData queueData : topicRouteData.getQueueDatas()) {
if (queueData.getBrokerName().equals(brokerData.getBrokerName())) {
if (!PermName.isWriteable(queueData.getPerm())) {
final Long minBrokerId = Collections.min(brokerAddrs.keySet());
final String actingMasterAddr = brokerAddrs.remove(minBrokerId);
brokerAddrs.put(MixAll.MASTER_ID, actingMasterAddr);
}
break;
}
}
}
return topicRouteData;
}
return null;
}
|
@Test
public void testPickupTopicRouteData() {
TopicRouteData result = routeInfoManager.pickupTopicRouteData("unit_test");
assertThat(result).isNull();
}
|
@Override public Span start() {
return start(clock.currentTimeMicroseconds());
}
|
@Test void start() {
span.start();
span.flush();
assertThat(spans.get(0).startTimestamp())
.isPositive();
}
|
public void add() {
add(1L, defaultPosition);
}
|
@Test
final void testAddLong() {
final String metricName = "unitTestCounter";
Counter c = receiver.declareCounter(metricName);
final long twoToThePowerOfFourtyeight = 65536L * 65536L * 65536L;
c.add(twoToThePowerOfFourtyeight);
Bucket b = receiver.getSnapshot();
final Map<String, List<Entry<Point, UntypedMetric>>> valuesByMetricName = b.getValuesByMetricName();
assertEquals(1, valuesByMetricName.size());
List<Entry<Point, UntypedMetric>> x = valuesByMetricName.get(metricName);
assertEquals(1, x.size());
assertEquals(Point.emptyPoint(), x.get(0).getKey());
assertEquals(twoToThePowerOfFourtyeight, x.get(0).getValue().getCount());
}
|
@HighFrequencyInvocation
public EncryptColumn getEncryptColumn(final String logicColumnName) {
ShardingSpherePreconditions.checkState(isEncryptColumn(logicColumnName), () -> new EncryptColumnNotFoundException(table, logicColumnName));
return columns.get(logicColumnName);
}
|
@Test
void assertGetEncryptColumn() {
assertNotNull(encryptTable.getEncryptColumn("logicColumn"));
}
|
@Override
public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) {
return internal.query(query, positionBound, config);
}
|
@Test
public void shouldTrackOpenIteratorsMetric() {
final MultiVersionedKeyQuery<String, String> query = MultiVersionedKeyQuery.withKey(KEY);
final PositionBound bound = PositionBound.unbounded();
final QueryConfig config = new QueryConfig(false);
when(inner.query(any(), any(), any())).thenReturn(
QueryResult.forResult(new LogicalSegmentIterator(Collections.emptyListIterator(), RAW_KEY, 0L, 0L, ResultOrder.ANY)));
final KafkaMetric openIteratorsMetric = getMetric("num-open-iterators");
assertThat(openIteratorsMetric, not(nullValue()));
assertThat((Long) openIteratorsMetric.metricValue(), equalTo(0L));
final QueryResult<VersionedRecordIterator<String>> result = store.query(query, bound, config);
try (final VersionedRecordIterator<String> iterator = result.getResult()) {
assertThat((Long) openIteratorsMetric.metricValue(), equalTo(1L));
}
assertThat((Long) openIteratorsMetric.metricValue(), equalTo(0L));
}
|
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
}
|
@Test
public void testProcessElementExceptionWithReturn() throws Exception {
thrown.expect(UserCodeException.class);
thrown.expectMessage("bogus");
DoFnInvokers.invokerFor(
new DoFn<Integer, Integer>() {
@ProcessElement
public ProcessContinuation processElement(
@SuppressWarnings("unused") ProcessContext c,
RestrictionTracker<SomeRestriction, Void> tracker) {
throw new IllegalArgumentException("bogus");
}
@GetInitialRestriction
public SomeRestriction getInitialRestriction(@Element Integer element) {
return null;
}
@NewTracker
public SomeRestrictionTracker newTracker(@Restriction SomeRestriction restriction) {
return null;
}
})
.invokeProcessElement(
new FakeArgumentProvider<Integer, Integer>() {
@Override
public DoFn.ProcessContext processContext(DoFn<Integer, Integer> doFn) {
return null; // will not be touched
}
@Override
public RestrictionTracker<?, ?> restrictionTracker() {
return null; // will not be touched
}
});
}
|
public void selectInputStreams(Collection<EditLogInputStream> streams,
long fromTxnId, boolean inProgressOk) throws IOException {
selectInputStreams(streams, fromTxnId, inProgressOk, false);
}
|
@Test
public void testSelectInputStreamsMajorityDown() throws Exception {
// Shut down all of the JNs.
cluster.shutdown();
List<EditLogInputStream> streams = Lists.newArrayList();
try {
qjm.selectInputStreams(streams, 0, false);
fail("Did not throw IOE");
} catch (QuorumException ioe) {
GenericTestUtils.assertExceptionContains(
"Got too many exceptions", ioe);
assertTrue(streams.isEmpty());
}
}
|
public static Charset getCharset(HttpMessage message) {
return getCharset(message, CharsetUtil.ISO_8859_1);
}
|
@Test
public void testGetCharset() {
testGetCharsetUtf8("text/html; charset=utf-8");
}
|
@Override
protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
final NSDictionary serialized = NSDictionary.dictionaryWithContentsOfFile(file.getAbsolute());
if(null == serialized) {
throw new LocalAccessDeniedException(String.format("Invalid bookmark file %s", file));
}
final List<NSDictionary> array = new PlistDeserializer(serialized).listForKey("CustomPluginSettings");
if(null == array) {
log.warn("Missing key CustomPluginSettings");
return;
}
for(NSDictionary dict : array) {
final PlistDeserializer bookmark = new PlistDeserializer(dict);
final String identifier = bookmark.stringForKey("MountFSClassName");
if(StringUtils.isBlank(identifier)) {
log.warn("Missing key MountFSClassName");
continue;
}
final Protocol protocol;
switch(identifier) {
case "FtpConnection":
protocol = protocols.forType(Protocol.Type.ftp);
break;
case "WebDAVConnection":
protocol = protocols.forType(Protocol.Type.dav);
break;
case "OpenStackConnection":
protocol = protocols.forType(Protocol.Type.swift);
break;
case "BBConnection":
protocol = protocols.forType(Protocol.Type.b2);
break;
case "S3Connection":
protocol = protocols.forType(Protocol.Type.s3);
break;
case "DropboxConnection":
protocol = protocols.forType(Protocol.Type.dropbox);
break;
case "GDriveConnection":
protocol = protocols.forType(Protocol.Type.googledrive);
break;
default:
protocol = null;
break;
}
if(null == protocol) {
log.warn(String.format("Unable to determine protocol for %s", identifier));
continue;
}
final NSDictionary details = bookmark.objectForKey("MountFSOptions");
if(null == details) {
continue;
}
final PlistDeserializer options = new PlistDeserializer(details);
final String hostname = options.stringForKey("host");
if(StringUtils.isBlank(hostname)) {
continue;
}
final Host host = new Host(protocol, hostname, new Credentials(options.stringForKey("login")));
host.setNickname(bookmark.stringForKey("MountFSLabel"));
host.setDefaultPath(options.stringForKey("remotePath"));
this.add(host);
}
}
|
@Test
public void testParse() throws Exception {
CloudMounterBookmarkCollection c = new CloudMounterBookmarkCollection();
assertEquals(0, c.size());
c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(
new TestProtocol(Scheme.ftp),
new TestProtocol(Scheme.ftps),
new TestProtocol(Scheme.sftp)
))), new Local("src/test/resources/com.eltima.cloudmounter.plist"));
assertEquals(2, c.size());
}
|
public static ClusterHealthStatus isHealth(List<RemoteInstance> remoteInstances) {
if (CollectionUtils.isEmpty(remoteInstances)) {
return ClusterHealthStatus.unHealth("can't get the instance list");
}
if (!CoreModuleConfig.Role.Receiver.equals(ROLE)) {
List<RemoteInstance> selfInstances = remoteInstances.stream().
filter(remoteInstance -> remoteInstance.getAddress().isSelf()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(selfInstances)) {
return ClusterHealthStatus.unHealth("can't get itself");
}
}
if (remoteInstances.size() > 1 && hasIllegalNodeAddress(remoteInstances)) {
return ClusterHealthStatus.unHealth("find illegal node in cluster mode such as 127.0.0.1, localhost");
}
return ClusterHealthStatus.HEALTH;
}
|
@Test
public void unHealthWithNullInstance() {
ClusterHealthStatus clusterHealthStatus = OAPNodeChecker.isHealth(null);
Assertions.assertFalse(clusterHealthStatus.isHealth());
}
|
public static void main(String[] args) {
final var inventory = new Inventory(1000);
var executorService = Executors.newFixedThreadPool(3);
IntStream.range(0, 3).<Runnable>mapToObj(i -> () -> {
while (inventory.addItem(new Item())) {
LOGGER.info("Adding another item");
}
}).forEach(executorService::execute);
executorService.shutdown();
try {
executorService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error("Error waiting for ExecutorService shutdown");
Thread.currentThread().interrupt();
}
}
|
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
|
@Override
public boolean touch(URI uri)
throws IOException {
try {
HeadObjectResponse s3ObjectMetadata = getS3ObjectMetadata(uri);
String encodedUrl = URLEncoder.encode(uri.getHost() + uri.getPath(), StandardCharsets.UTF_8);
String path = sanitizePath(uri.getPath());
CopyObjectRequest request = generateCopyObjectRequest(encodedUrl, uri, path,
ImmutableMap.of("lastModified", String.valueOf(System.currentTimeMillis())));
_s3Client.copyObject(request);
long newUpdateTime = getS3ObjectMetadata(uri).lastModified().toEpochMilli();
return newUpdateTime > s3ObjectMetadata.lastModified().toEpochMilli();
} catch (NoSuchKeyException e) {
String path = sanitizePath(uri.getPath());
PutObjectRequest putObjectRequest = generatePutObjectRequest(uri, path);
_s3Client.putObject(putObjectRequest, RequestBody.fromBytes(new byte[0]));
return true;
} catch (S3Exception e) {
throw new IOException(e);
}
}
|
@Test
public void testTouchFilesInFolder()
throws Exception {
String folder = "my-files";
String[] originalFiles = new String[]{"a-touch.txt", "b-touch.txt", "c-touch.txt"};
for (String fileName : originalFiles) {
String fileNameWithFolder = folder + DELIMITER + fileName;
_s3PinotFS.touch(URI.create(String.format(FILE_FORMAT, SCHEME, BUCKET, fileNameWithFolder)));
}
ListObjectsV2Response listObjectsV2Response =
_s3Client.listObjectsV2(S3TestUtils.getListObjectRequest(BUCKET, folder, false));
String[] response = listObjectsV2Response.contents().stream().map(S3Object::key).filter(x -> x.contains("touch"))
.toArray(String[]::new);
Assert.assertEquals(response.length, originalFiles.length);
Assert.assertTrue(Arrays.equals(response, Arrays.stream(originalFiles).map(x -> folder + DELIMITER + x).toArray()));
}
|
public static <T> Window<T> into(WindowFn<? super T, ?> fn) {
try {
fn.windowCoder().verifyDeterministic();
} catch (NonDeterministicException e) {
throw new IllegalArgumentException("Window coders must be deterministic.", e);
}
return Window.<T>configure().withWindowFn(fn);
}
|
@Test
@Category({ValidatesRunner.class, UsesCustomWindowMerging.class})
public void testMergingCustomWindowsKeyedCollection() {
Instant startInstant = new Instant(0L);
PCollection<KV<Integer, String>> inputCollection =
pipeline.apply(
Create.timestamped(
TimestampedValue.of(
KV.of(0, "big"), startInstant.plus(Duration.standardSeconds(10))),
TimestampedValue.of(
KV.of(1, "small1"), startInstant.plus(Duration.standardSeconds(20))),
// This element is not contained within the bigWindow and not merged
TimestampedValue.of(
KV.of(2, "small2"), startInstant.plus(Duration.standardSeconds(39)))));
PCollection<KV<Integer, String>> windowedCollection =
inputCollection.apply(Window.into(new CustomWindowFn<>()));
PCollection<Long> count =
windowedCollection.apply(
Combine.globally(Count.<KV<Integer, String>>combineFn()).withoutDefaults());
// "small1" and "big" elements merged into bigWindow "small2" not merged
// because it is not contained in bigWindow
PAssert.that("Wrong number of elements in output collection", count).containsInAnyOrder(2L, 1L);
pipeline.run();
}
|
@Override
public Optional<ShardingConditionValue> generate(final BetweenExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) {
ConditionValue betweenConditionValue = new ConditionValue(predicate.getBetweenExpr(), params);
ConditionValue andConditionValue = new ConditionValue(predicate.getAndExpr(), params);
Optional<Comparable<?>> betweenValue = betweenConditionValue.getValue();
Optional<Comparable<?>> andValue = andConditionValue.getValue();
List<Integer> parameterMarkerIndexes = new ArrayList<>(2);
betweenConditionValue.getParameterMarkerIndex().ifPresent(parameterMarkerIndexes::add);
andConditionValue.getParameterMarkerIndex().ifPresent(parameterMarkerIndexes::add);
if (betweenValue.isPresent() && andValue.isPresent()) {
return Optional.of(new RangeShardingConditionValue<>(column.getName(), column.getTableName(), SafeNumberOperationUtils.safeClosed(betweenValue.get(), andValue.get()),
parameterMarkerIndexes));
}
Timestamp timestamp = timestampServiceRule.getTimestamp();
if (!betweenValue.isPresent() && ExpressionConditionUtils.isNowExpression(predicate.getBetweenExpr())) {
betweenValue = Optional.of(timestamp);
}
if (!andValue.isPresent() && ExpressionConditionUtils.isNowExpression(predicate.getAndExpr())) {
andValue = Optional.of(timestamp);
}
if (!betweenValue.isPresent() || !andValue.isPresent()) {
return Optional.empty();
}
return Optional.of(new RangeShardingConditionValue<>(column.getName(), column.getTableName(), Range.closed(betweenValue.get(), andValue.get()), parameterMarkerIndexes));
}
|
@SuppressWarnings("unchecked")
@Test
void assertGenerateOneNowConditionValue() {
Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now());
ExpressionSegment betweenSegment = new LiteralExpressionSegment(0, 0, timestamp);
ExpressionSegment andSegment = new CommonExpressionSegment(0, 0, "now()");
BetweenExpression value = new BetweenExpression(0, 0, null, betweenSegment, andSegment, false);
Optional<ShardingConditionValue> shardingConditionValue = generator.generate(value, column, new LinkedList<>(), timestampServiceRule);
assertTrue(shardingConditionValue.isPresent());
RangeShardingConditionValue<Date> rangeShardingConditionValue = (RangeShardingConditionValue<Date>) shardingConditionValue.get();
assertThat(rangeShardingConditionValue.getColumnName(), is(column.getName()));
assertThat(rangeShardingConditionValue.getTableName(), is(column.getTableName()));
assertThat(rangeShardingConditionValue.getValueRange().lowerEndpoint(), is(timestamp));
assertTrue(rangeShardingConditionValue.getParameterMarkerIndexes().isEmpty());
}
|
public static File getPluginFile(final String path) {
String pluginPath = getPluginPath(path);
return new File(pluginPath);
}
|
@Test
public void testGetPluginPathByPluginExt() {
System.setProperty("plugin-ext", "/testUrl");
File jarFile = ShenyuPluginPathBuilder.getPluginFile("");
assertNotNull(jarFile);
}
|
@Override
public Boolean run(final Session<?> session) throws BackgroundException {
final UnixPermission feature = session.getFeature(UnixPermission.class);
if(log.isDebugEnabled()) {
log.debug(String.format("Run with feature %s", feature));
}
for(Path file : files) {
if(this.isCanceled()) {
throw new ConnectionCanceledException();
}
final Permission merged = permissions.get(file);
this.write(session, feature, file, merged);
}
return true;
}
|
@Test
public void testRun() throws Exception {
final PermissionOverwrite permission = new PermissionOverwrite(
new PermissionOverwrite.Action(true, true, true),
new PermissionOverwrite.Action(null, false, false),
new PermissionOverwrite.Action(true, false, false)
);
// Tests all actions set to read
final Path path = new Path("a", EnumSet.of(Path.Type.directory), new TestPermissionAttributes(Permission.Action.read));
final WritePermissionWorker worker = new WritePermissionWorker(Collections.singletonList(path), permission, new BooleanRecursiveCallback<>(true), new DisabledProgressListener());
worker.run(new NullSession(new Host(new TestProtocol())) {
@Override
public AttributedList<Path> list(final Path file, final ListProgressListener listener) {
final AttributedList<Path> children = new AttributedList<>();
// test just group set to read
children.add(new Path("b", EnumSet.of(Path.Type.file), new TestPermissionAttributes(Permission.Action.none, Permission.Action.read, Permission.Action.none)));
return children;
}
@Override
@SuppressWarnings("unchecked")
public <T> T _getFeature(final Class<T> type) {
if(type == UnixPermission.class) {
return (T) new UnixPermission() {
@Override
public void setUnixOwner(final Path file, final String owner) {
throw new UnsupportedOperationException();
}
@Override
public void setUnixGroup(final Path file, final String group) {
throw new UnsupportedOperationException();
}
@Override
public Permission getUnixPermission(final Path file) {
throw new UnsupportedOperationException();
}
@Override
public void setUnixPermission(final Path file, final TransferStatus status) throws BackgroundException {
assertEquals(new Permission(744), status.getPermission());
}
};
}
return super._getFeature(type);
}
});
}
|
public ProtocolBuilder register(Boolean register) {
this.register = register;
return getThis();
}
|
@Test
void register() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.register(true);
Assertions.assertTrue(builder.build().isRegister());
}
|
public String getUUID() {
if (CatalogMgr.isExternalCatalog(catalogName)) {
return catalogName + "." + fullQualifiedName;
}
return Long.toString(id);
}
|
@Test
public void testGetUUID() {
// Internal database
Database db1 = new Database();
Assert.assertEquals("0", db1.getUUID());
Database db2 = new Database(101, "db2");
Assert.assertEquals("101", db2.getUUID());
// External database
Database db3 = new Database(101, "db3");
db3.setCatalogName("hive");
Assert.assertEquals("hive.db3", db3.getUUID());
}
|
public static List<String> resolveCompsDependency(Service service) {
List<String> components = new ArrayList<String>();
for (Component component : service.getComponents()) {
int depSize = component.getDependencies().size();
if (!components.contains(component.getName())) {
components.add(component.getName());
}
if (depSize != 0) {
for (String depComp : component.getDependencies()) {
if (!components.contains(depComp)) {
components.add(0, depComp);
}
}
}
}
return components;
}
|
@Test
public void testResolveNoCompsDependency() {
Service service = createExampleApplication();
Component compa = createComponent("compa");
Component compb = createComponent("compb");
service.addComponent(compa);
service.addComponent(compb);
List<String> order = ServiceApiUtil.resolveCompsDependency(service);
List<String> expected = new ArrayList<String>();
expected.add("compa");
expected.add("compb");
for (int i = 0; i < expected.size(); i++) {
Assert.assertEquals("Components are not equal.", expected.get(i),
order.get(i));
}
}
|
public static String getPrefix(URI uri, ClassLoader classLoader) {
if (uri == null && classLoader == null) {
return null;
} else {
StringBuilder sb = new StringBuilder();
if (uri != null) {
sb.append(uri.toASCIIString()).append('/');
}
if (classLoader != null) {
sb.append(classLoader).append('/');
}
return sb.toString();
}
}
|
@Test
public void testGetPrefix() {
String prefix = getPrefix(uri, classLoader);
assertEquals(expectedPrefix, prefix);
}
|
public void log(QueryLogParams params) {
_logger.debug("Broker Response: {}", params._response);
if (!(_logRateLimiter.tryAcquire() || shouldForceLog(params))) {
_numDroppedLogs.incrementAndGet();
return;
}
final StringBuilder queryLogBuilder = new StringBuilder();
for (QueryLogEntry value : QUERY_LOG_ENTRY_VALUES) {
value.format(queryLogBuilder, this, params);
queryLogBuilder.append(',');
}
// always log the query last - don't add this to the QueryLogEntry enum
queryLogBuilder.append("query=")
.append(StringUtils.substring(params._requestContext.getQuery(), 0, _maxQueryLengthToLog));
_logger.info(queryLogBuilder.toString());
if (_droppedLogRateLimiter.tryAcquire()) {
// use getAndSet to 0 so that there will be no race condition between
// loggers that increment this counter and this thread
long numDroppedLogsSinceLastLog = _numDroppedLogs.getAndSet(0);
if (numDroppedLogsSinceLastLog > 0) {
_logger.warn("{} logs were dropped. (log max rate per second: {})", numDroppedLogsSinceLastLog,
_logRateLimiter.getRate());
}
}
}
|
@Test
public void shouldForceLogWhenExceptionsExist() {
// Given:
Mockito.when(_logRateLimiter.tryAcquire()).thenReturn(false);
QueryLogger.QueryLogParams params = generateParams(false, 1, 456);
QueryLogger queryLogger = new QueryLogger(_logRateLimiter, 100, true, _logger, _droppedRateLimiter);
// When:
queryLogger.log(params);
// Then:
Assert.assertEquals(_infoLog.size(), 1);
}
|
@Override
public COSDictionary getCOSObject()
{
return dictionary;
}
|
@Test
void createWidgetAnnotationFromField()
{
PDDocument document = new PDDocument();
PDAcroForm acroForm = new PDAcroForm(document);
PDTextField textField = new PDTextField(acroForm);
PDAnnotation annotation = textField.getWidgets().get(0);
assertEquals(COSName.ANNOT, annotation.getCOSObject().getItem(COSName.TYPE));
assertEquals(PDAnnotationWidget.SUB_TYPE, annotation.getCOSObject().getNameAsString(COSName.SUBTYPE));
}
|
@Bean
public ShenyuPlugin signPlugin(final SignService signService, final ServerCodecConfigurer configurer) {
return new SignPlugin(configurer.getReaders(), signService);
}
|
@Test
public void testSignPlugin() {
applicationContextRunner.run(context -> {
ShenyuPlugin plugin = context.getBean("signPlugin", ShenyuPlugin.class);
assertNotNull(plugin);
assertThat(plugin.named()).isEqualTo(PluginEnum.SIGN.getName());
}
);
}
|
@Udf(description = "Splits a string into an array of substrings based on a delimiter.")
public List<String> split(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The delimiter to split a string by. If NULL, then function returns NULL.")
final String delimiter) {
if (string == null || delimiter == null) {
return null;
}
// Java split() accepts regular expressions as a delimiter, but the behavior of this UDF split()
// is to accept only literal strings. This method uses Guava Splitter instead, which does not
// accept any regex pattern. This is to avoid a confusion to users when splitting by regex
// special characters, such as '.' and '|'.
try {
// Guava Splitter does not accept empty delimiters. Use the Java split() method instead.
if (delimiter.isEmpty()) {
return Arrays.asList(EMPTY_DELIMITER.split(string));
} else {
return Splitter.on(delimiter).splitToList(string);
}
} catch (final Exception e) {
throw new KsqlFunctionException(
String.format("Invalid delimiter '%s' in the split() function.", delimiter), e);
}
}
|
@Test
public void shouldReturnNullOnAnyNullParametersOnSplitBytes() {
assertThat(splitUdf.split(null, EMPTY_BYTES), is(nullValue()));
assertThat(splitUdf.split(EMPTY_BYTES, null), is(nullValue()));
assertThat(splitUdf.split((ByteBuffer) null, null), is(nullValue()));
}
|
@Override
public StageBundleFactory forStage(ExecutableStage executableStage) {
return new SimpleStageBundleFactory(executableStage);
}
|
@Test
public void createsCorrectEnvironment() throws Exception {
try (DefaultJobBundleFactory bundleFactory =
createDefaultJobBundleFactory(envFactoryProviderMap)) {
bundleFactory.forStage(getExecutableStage(environment));
verify(envFactory).createEnvironment(eq(environment), any());
}
}
|
@Override
public int hashCode()
{
return Objects.hash(numBits, numHashFunctions, Arrays.hashCode(bitSet.getData()));
}
|
@Test
public void testHashCode()
{
List<Long> bitset1 = ImmutableList.of(2L);
List<Long> bitset2 = ImmutableList.of(2L);
HiveBloomFilter filter1 = new HiveBloomFilter(bitset1, 1, 1);
HiveBloomFilter filter2 = new HiveBloomFilter(bitset2, 1, 1);
assertEquals(filter1, filter2);
assertEquals(filter1.hashCode(), filter2.hashCode());
}
|
@Override
public Path copy(final Path source, final Path copy, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final CloudBlob target = session.getClient().getContainerReference(containerService.getContainer(copy).getName())
.getAppendBlobReference(containerService.getKey(copy));
final CloudBlob blob = session.getClient().getContainerReference(containerService.getContainer(source).getName())
.getBlobReferenceFromServer(containerService.getKey(source));
final BlobRequestOptions options = new BlobRequestOptions();
options.setStoreBlobContentMD5(new HostPreferences(session.getHost()).getBoolean("azure.upload.md5"));
final URI s = session.getHost().getCredentials().isTokenAuthentication() ?
URI.create(blob.getUri().toString() + session.getHost().getCredentials().getToken()) : blob.getUri();
final String id = target.startCopy(s,
AccessCondition.generateEmptyCondition(), AccessCondition.generateEmptyCondition(), options, context);
if(log.isDebugEnabled()) {
log.debug(String.format("Started copy for %s with copy operation ID %s", copy, id));
}
listener.sent(status.getLength());
return copy;
}
catch(StorageException e) {
throw new AzureExceptionMappingService().map("Cannot copy {0}", e, source);
}
catch(URISyntaxException e) {
throw new NotfoundException(e.getMessage(), e);
}
}
|
@Test
public void testCopy() throws Exception {
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new AzureTouchFeature(session, null).touch(
new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
Thread.sleep(1000L);
final AzureCopyFeature feature = new AzureCopyFeature(session, null);
assertThrows(UnsupportedException.class, () -> feature.preflight(container, test));
try {
feature.preflight(container, test);
}
catch(UnsupportedException e) {
assertEquals("Unsupported", e.getMessage());
assertEquals("Cannot copy cyberduck.", e.getDetail(false));
}
final Path copy = feature.copy(test,
new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus(), new DisabledConnectionCallback(), new DisabledStreamListener());
assertEquals(test.attributes().getChecksum(), copy.attributes().getChecksum());
assertNotEquals(new AzureAttributesFinderFeature(session, null).find(test).getModificationDate(), new AzureAttributesFinderFeature(session, null).find(copy).getModificationDate());
assertTrue(new AzureFindFeature(session, null).find(test));
assertTrue(new AzureFindFeature(session, null).find(copy));
new AzureDeleteFeature(session, null).delete(Arrays.asList(test, copy), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
|
private ContentType getContentType(Exchange exchange) throws ParseException {
String contentTypeStr = ExchangeHelper.getContentType(exchange);
if (contentTypeStr == null) {
contentTypeStr = DEFAULT_CONTENT_TYPE;
}
ContentType contentType = new ContentType(contentTypeStr);
String contentEncoding = ExchangeHelper.getContentEncoding(exchange);
// add a charset parameter for text subtypes
if (contentEncoding != null && contentType.match("text/*")) {
contentType.setParameter("charset", MimeUtility.mimeCharset(contentEncoding));
}
return contentType;
}
|
@Test
public void roundtripWithBinaryAttachmentsAndBinaryContent() throws IOException {
String attContentType = "application/binary";
byte[] attText = { 0, 1, 2, 3, 4, 5, 6, 7 };
String attFileName = "Attachment File Name";
in.setBody("Body text");
DataSource ds = new ByteArrayDataSource(attText, attContentType);
in.addAttachment(attFileName, new DataHandler(ds));
Exchange result = template.send("direct:roundtripbinarycontent", exchange);
AttachmentMessage out = result.getMessage(AttachmentMessage.class);
assertEquals("Body text", out.getBody(String.class));
assertTrue(out.hasAttachments());
assertEquals(1, out.getAttachmentNames().size());
assertTrue(out.getAttachmentNames().contains(attFileName));
DataHandler dh = out.getAttachment(attFileName);
assertNotNull(dh);
assertEquals(attContentType, dh.getContentType());
InputStream is = dh.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOHelper.copyAndCloseInput(is, os);
assertArrayEquals(attText, os.toByteArray());
}
|
public static BigDecimal ensureFit(final BigDecimal value, final Schema schema) {
return ensureFit(value, precision(schema), scale(schema));
}
|
@Test
public void shouldEnsureFitIfExactMatch() {
// No Exception When:
DecimalUtil.ensureFit(new BigDecimal("1.2"), DECIMAL_SCHEMA);
}
|
public AtomicLong getNextIndex(String virtualHostname, boolean secure) {
Map<String, VipIndexSupport> index = (secure) ? secureVirtualHostNameAppMap : virtualHostNameAppMap;
return Optional.ofNullable(index.get(virtualHostname.toUpperCase(Locale.ROOT)))
.map(VipIndexSupport::getRoundRobinIndex)
.orElse(null);
}
|
@Test
public void testGetNextIndex() {
DataCenterInfo myDCI = new DataCenterInfo() {
public DataCenterInfo.Name getName() {
return DataCenterInfo.Name.MyOwn;
}
};
InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
.setAppName("test")
.setVIPAddress("test.testname:1")
.setSecureVIPAddress("securetest.testname:7102")
.setDataCenterInfo(myDCI)
.setHostName("test.hostname")
.setStatus(InstanceStatus.UP)
.build();
Application application = new Application("TestApp");
application.addInstance(instanceInfo);
Applications applications = new Applications();
applications.addApplication(application);
assertNotNull(applications.getNextIndex("test.testname:1", false));
assertEquals(0L, applications.getNextIndex("test.testname:1", false).get());
assertNotNull(applications.getNextIndex("securetest.testname:7102", true));
assertEquals(0L, applications.getNextIndex("securetest.testname:7102", true).get());
assertNotSame(applications.getNextIndex("test.testname:1", false), applications.getNextIndex("securetest.testname:7102", true));
}
|
public TaskIOMetricGroup(TaskMetricGroup parent) {
this(parent, SystemClock.getInstance());
}
|
@Test
void testTaskIOMetricGroup() throws InterruptedException {
TaskMetricGroup task = UnregisteredMetricGroups.createUnregisteredTaskMetricGroup();
ManualClock clock = new ManualClock(System.currentTimeMillis());
TaskIOMetricGroup taskIO = new TaskIOMetricGroup(task, clock);
// test initializing time
final long initializationTime = 100L;
assertThat(taskIO.getTaskInitializationDuration()).isEqualTo(0L);
taskIO.markTaskInitializationStarted();
clock.advanceTime(Duration.ofMillis(initializationTime));
assertThat(taskIO.getTaskInitializationDuration()).isGreaterThan(0L);
long initializationDuration = taskIO.getTaskInitializationDuration();
taskIO.markTaskStart();
assertThat(taskIO.getTaskInitializationDuration()).isEqualTo(initializationDuration);
taskIO.setEnableBusyTime(true);
taskIO.markTaskStart();
final long startTime = clock.absoluteTimeMillis();
// test initializing time remains unchanged after running
final long runningTime = 200L;
clock.advanceTime(Duration.ofMillis(runningTime));
assertThat(taskIO.getTaskInitializationDuration()).isEqualTo(initializationDuration);
// test counter forwarding
assertThat(taskIO.getNumRecordsInCounter()).isNotNull();
assertThat(taskIO.getNumRecordsOutCounter()).isNotNull();
Counter c1 = new SimpleCounter();
c1.inc(32L);
Counter c2 = new SimpleCounter();
c2.inc(64L);
taskIO.reuseRecordsInputCounter(c1);
taskIO.reuseRecordsOutputCounter(c2);
assertThat(taskIO.getNumRecordsInCounter().getCount()).isEqualTo(32L);
assertThat(taskIO.getNumRecordsOutCounter().getCount()).isEqualTo(64L);
// test IOMetrics instantiation
taskIO.getNumBytesInCounter().inc(100L);
taskIO.getNumBytesOutCounter().inc(250L);
taskIO.getNumBuffersOutCounter().inc(3L);
taskIO.getIdleTimeMsPerSecond().markStart();
taskIO.getSoftBackPressuredTimePerSecond().markStart();
long softSleepTime = 2L;
clock.advanceTime(Duration.ofMillis(softSleepTime));
taskIO.getIdleTimeMsPerSecond().markEnd();
taskIO.getSoftBackPressuredTimePerSecond().markEnd();
long hardSleepTime = 4L;
taskIO.getHardBackPressuredTimePerSecond().markStart();
clock.advanceTime(Duration.ofMillis(hardSleepTime));
taskIO.getHardBackPressuredTimePerSecond().markEnd();
long ioSleepTime = 3L;
taskIO.getChangelogBusyTimeMsPerSecond().markStart();
clock.advanceTime(Duration.ofMillis(ioSleepTime));
taskIO.getChangelogBusyTimeMsPerSecond().markEnd();
IOMetrics io = taskIO.createSnapshot();
assertThat(io.getNumRecordsIn()).isEqualTo(32L);
assertThat(io.getNumRecordsOut()).isEqualTo(64L);
assertThat(io.getNumBytesIn()).isEqualTo(100L);
assertThat(io.getNumBytesOut()).isEqualTo(250L);
assertThat(taskIO.getNumBuffersOutCounter().getCount()).isEqualTo(3L);
assertThat(taskIO.getIdleTimeMsPerSecond().getAccumulatedCount())
.isEqualTo(io.getAccumulateIdleTime());
assertThat(
taskIO.getHardBackPressuredTimePerSecond().getAccumulatedCount()
+ taskIO.getSoftBackPressuredTimePerSecond().getAccumulatedCount())
.isEqualTo(io.getAccumulateBackPressuredTime());
assertThat(io.getAccumulateBusyTime())
.isEqualTo(
clock.absoluteTimeMillis()
- startTime
- io.getAccumulateIdleTime()
- io.getAccumulateBackPressuredTime());
assertThat(taskIO.getIdleTimeMsPerSecond().getCount())
.isGreaterThanOrEqualTo(softSleepTime);
assertThat(taskIO.getSoftBackPressuredTimePerSecond().getCount())
.isGreaterThanOrEqualTo(softSleepTime);
assertThat(taskIO.getHardBackPressuredTimePerSecond().getCount())
.isGreaterThanOrEqualTo(hardSleepTime);
assertThat(taskIO.getChangelogBusyTimeMsPerSecond().getCount())
.isGreaterThanOrEqualTo(ioSleepTime);
}
|
static int parseMajorJavaVersion(String javaVersion) {
int version = parseDotted(javaVersion);
if (version == -1) {
version = extractBeginningInt(javaVersion);
}
if (version == -1) {
return 6; // Choose minimum supported JDK version as default
}
return version;
}
|
@Test
public void testJava7() {
// http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html
assertThat(JavaVersion.parseMajorJavaVersion("1.7.0")).isEqualTo(7);
}
|
public Serde<GenericKey> buildKeySerde(
final FormatInfo format, final PhysicalSchema schema, final QueryContext queryContext
) {
final String loggerNamePrefix = QueryLoggerUtil.queryLoggerName(queryId, queryContext);
schemas.trackKeySerdeCreation(
loggerNamePrefix,
schema.logicalSchema(),
KeyFormat.nonWindowed(format, schema.keySchema().features())
);
return keySerdeFactory.create(
format,
schema.keySchema(),
ksqlConfig,
serviceContext.getSchemaRegistryClientFactory(),
loggerNamePrefix,
processingLogContext,
getSerdeTracker(loggerNamePrefix)
);
}
|
@Test
public void shouldBuildWindowedKeySerde() {
// Then:
runtimeBuildContext.buildKeySerde(
FORMAT_INFO,
WINDOW_INFO,
PHYSICAL_SCHEMA,
queryContext
);
// Then:
verify(keySerdeFactory).create(
FORMAT_INFO,
WINDOW_INFO,
PHYSICAL_SCHEMA.keySchema(),
ksqlConfig,
srClientFactory,
QueryLoggerUtil.queryLoggerName(QUERY_ID, queryContext),
processingLogContext,
Optional.empty()
);
}
|
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
}
|
@Test
public void testMapViaMultimapEntriesAndKeysMergeLocalAddRemoveClear() {
final String tag = "map";
StateTag<MapState<byte[], Integer>> addr =
StateTags.map(tag, ByteArrayCoder.of(), VarIntCoder.of());
MapState<byte[], Integer> mapState = underTestMapViaMultimap.state(NAMESPACE, addr);
final byte[] key1 = "key1".getBytes(StandardCharsets.UTF_8);
final byte[] key2 = "key2".getBytes(StandardCharsets.UTF_8);
final byte[] key3 = "key3".getBytes(StandardCharsets.UTF_8);
final byte[] key4 = "key4".getBytes(StandardCharsets.UTF_8);
SettableFuture<Iterable<Map.Entry<ByteString, Iterable<Integer>>>> entriesFuture =
SettableFuture.create();
when(mockReader.multimapFetchAllFuture(
false, key(NAMESPACE, tag), STATE_FAMILY, VarIntCoder.of()))
.thenReturn(entriesFuture);
SettableFuture<Iterable<Map.Entry<ByteString, Iterable<Integer>>>> keysFuture =
SettableFuture.create();
when(mockReader.multimapFetchAllFuture(
true, key(NAMESPACE, tag), STATE_FAMILY, VarIntCoder.of()))
.thenReturn(keysFuture);
ReadableState<Iterable<Map.Entry<byte[], Integer>>> entriesResult =
mapState.entries().readLater();
ReadableState<Iterable<byte[]>> keysResult = mapState.keys().readLater();
waitAndSet(entriesFuture, Arrays.asList(multimapEntry(key1, 3), multimapEntry(key2, 4)), 30);
waitAndSet(keysFuture, Arrays.asList(multimapEntry(key1), multimapEntry(key2)), 30);
mapState.put(key1, 7);
mapState.put(dup(key3), 8);
mapState.put(key4, 1);
mapState.remove(key4);
Iterable<Map.Entry<byte[], Integer>> entries = entriesResult.read();
assertEquals(3, Iterables.size(entries));
assertThat(
entries,
Matchers.containsInAnyOrder(
multimapEntryMatcher(key1, 7),
multimapEntryMatcher(key2, 4),
multimapEntryMatcher(key3, 8)));
Iterable<byte[]> keys = keysResult.read();
assertEquals(3, Iterables.size(keys));
assertThat(keys, Matchers.containsInAnyOrder(key1, key2, key3));
assertFalse(mapState.isEmpty().read());
mapState.clear();
assertTrue(mapState.isEmpty().read());
assertTrue(Iterables.isEmpty(mapState.keys().read()));
assertTrue(Iterables.isEmpty(mapState.entries().read()));
// Previously read iterable should still have the same result.
assertEquals(3, Iterables.size(keys));
assertThat(keys, Matchers.containsInAnyOrder(key1, key2, key3));
}
|
@Deprecated
public CompletableFuture<Void> disableOwnership(NamespaceBundle bundle) {
return updateBundleState(bundle, false)
.thenCompose(__ -> {
ResourceLock<NamespaceEphemeralData> lock = locallyAcquiredLocks.get(bundle);
if (lock == null) {
return CompletableFuture.completedFuture(null);
} else {
return lock.updateValue(selfOwnerInfoDisabled);
}
});
}
|
@Test
public void testDisableOwnership() throws Exception {
OwnershipCache cache = new OwnershipCache(this.pulsar, nsService);
NamespaceBundle testBundle = new NamespaceBundle(NamespaceName.get("pulsar/test/ns-1"),
Range.closedOpen(0L, (long) Integer.MAX_VALUE),
bundleFactory);
assertFalse(cache.getOwnerAsync(testBundle).get().isPresent());
NamespaceEphemeralData data1 = cache.tryAcquiringOwnership(testBundle).get();
assertFalse(data1.isDisabled());
cache.disableOwnership(testBundle).get();
// force the next read to get directly from ZK
// localCache.ownerInfoCache().invalidate(ServiceUnitZkUtils.path(testNs));
data1 = cache.getOwnerAsync(testBundle).get().get();
assertTrue(data1.isDisabled());
}
|
public CompletableFuture<Result> getTerminationFuture() {
return terminationFuture;
}
|
@Test
void testUnexpectedTaskManagerTerminationFailsRunnerFatally() throws Exception {
final CompletableFuture<Void> terminationFuture = new CompletableFuture<>();
final TestingTaskExecutorService taskExecutorService =
TestingTaskExecutorService.newBuilder()
.setTerminationFuture(terminationFuture)
.build();
final TaskManagerRunner taskManagerRunner =
createTaskManagerRunner(
createConfiguration(),
createTaskExecutorServiceFactory(taskExecutorService));
terminationFuture.complete(null);
assertThatFuture(taskManagerRunner.getTerminationFuture())
.eventuallySucceeds()
.isEqualTo(TaskManagerRunner.Result.FAILURE);
}
|
@Override
public Object evaluateLiteralExpression(String rawExpression, String className, List<String> genericClasses) {
Object expressionResult = compileAndExecute(rawExpression, new HashMap<>());
Class<Object> requiredClass = loadClass(className, classLoader);
if (expressionResult != null && !requiredClass.isAssignableFrom(expressionResult.getClass())) {
throw new IllegalArgumentException("Cannot assign a '" + expressionResult.getClass().getCanonicalName() +
"' to '" + requiredClass.getCanonicalName() + "'");
}
return expressionResult;
}
|
@Ignore("https://issues.redhat.com/browse/DROOLS-4649")
@Test
public void evaluateLiteralExpression_Array() {
assertThat(evaluateLiteralExpression("{\"Jim\", \"Michael\"}", Object[].class)).isEqualTo(new String[]{"Jim", "Michael"});
assertThat(evaluateLiteralExpression("{ }", Object[].class)).isEqualTo(new String[]{});
}
|
protected void mergeAndRevive(ConsumeReviveObj consumeReviveObj) throws Throwable {
ArrayList<PopCheckPoint> sortList = consumeReviveObj.genSortList();
POP_LOGGER.info("reviveQueueId={}, ck listSize={}", queueId, sortList.size());
if (sortList.size() != 0) {
POP_LOGGER.info("reviveQueueId={}, 1st ck, startOffset={}, reviveOffset={}; last ck, startOffset={}, reviveOffset={}", queueId, sortList.get(0).getStartOffset(),
sortList.get(0).getReviveOffset(), sortList.get(sortList.size() - 1).getStartOffset(), sortList.get(sortList.size() - 1).getReviveOffset());
}
long newOffset = consumeReviveObj.oldOffset;
for (PopCheckPoint popCheckPoint : sortList) {
if (!shouldRunPopRevive) {
POP_LOGGER.info("slave skip ck process, revive topic={}, reviveQueueId={}", reviveTopic, queueId);
break;
}
if (consumeReviveObj.endTime - popCheckPoint.getReviveTime() <= (PopAckConstants.ackTimeInterval + PopAckConstants.SECOND)) {
break;
}
// check normal topic, skip ck , if normal topic is not exist
String normalTopic = KeyBuilder.parseNormalTopic(popCheckPoint.getTopic(), popCheckPoint.getCId());
if (brokerController.getTopicConfigManager().selectTopicConfig(normalTopic) == null) {
POP_LOGGER.warn("reviveQueueId={}, can not get normal topic {}, then continue", queueId, popCheckPoint.getTopic());
newOffset = popCheckPoint.getReviveOffset();
continue;
}
if (null == brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(popCheckPoint.getCId())) {
POP_LOGGER.warn("reviveQueueId={}, can not get cid {}, then continue", queueId, popCheckPoint.getCId());
newOffset = popCheckPoint.getReviveOffset();
continue;
}
while (inflightReviveRequestMap.size() > 3) {
waitForRunning(100);
Pair<Long, Boolean> pair = inflightReviveRequestMap.firstEntry().getValue();
if (!pair.getObject2() && System.currentTimeMillis() - pair.getObject1() > 1000 * 30) {
PopCheckPoint oldCK = inflightReviveRequestMap.firstKey();
rePutCK(oldCK, pair);
inflightReviveRequestMap.remove(oldCK);
POP_LOGGER.warn("stay too long, remove from reviveRequestMap, {}, {}, {}, {}", popCheckPoint.getTopic(),
popCheckPoint.getBrokerName(), popCheckPoint.getQueueId(), popCheckPoint.getStartOffset());
}
}
reviveMsgFromCk(popCheckPoint);
newOffset = popCheckPoint.getReviveOffset();
}
if (newOffset > consumeReviveObj.oldOffset) {
if (!shouldRunPopRevive) {
POP_LOGGER.info("slave skip commit, revive topic={}, reviveQueueId={}", reviveTopic, queueId);
return;
}
this.brokerController.getConsumerOffsetManager().commitOffset(PopAckConstants.LOCAL_HOST, PopAckConstants.REVIVE_GROUP, reviveTopic, queueId, newOffset);
}
reviveOffset = newOffset;
consumeReviveObj.newOffset = newOffset;
}
|
@Test
public void testReviveMsgFromCk_messageNotFound_needRetry_noEnd() throws Throwable {
brokerConfig.setSkipWhenCKRePutReachMaxTimes(false);
PopCheckPoint ck = buildPopCheckPoint(0, 0, 0);
ck.setRePutTimes(Byte.MAX_VALUE + "");
PopReviveService.ConsumeReviveObj reviveObj = new PopReviveService.ConsumeReviveObj();
reviveObj.map.put("", ck);
reviveObj.endTime = System.currentTimeMillis();
when(escapeBridge.getMessageAsync(anyString(), anyLong(), anyInt(), anyString(), anyBoolean()))
.thenReturn(CompletableFuture.completedFuture(Triple.of(null, "", true)));
popReviveService.mergeAndRevive(reviveObj);
verify(escapeBridge, times(0)).putMessageToSpecificQueue(any(MessageExtBrokerInner.class)); // write retry
verify(messageStore, times(1)).putMessage(any(MessageExtBrokerInner.class)); // rewrite CK
}
|
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
}
|
@Test
void resolveRequestWithClassSelectorShouldLogWarnIfNoFeaturesFound(LogRecordListener logRecordListener) {
DiscoverySelector resource = selectClass(NoFeatures.class);
EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource);
resolver.resolveSelectors(discoveryRequest, testDescriptor);
assertEquals(0, testDescriptor.getChildren().size());
assertEquals(1, logRecordListener.getLogRecords().size());
LogRecord logRecord = logRecordListener.getLogRecords().get(0);
assertEquals(Level.WARNING, logRecord.getLevel());
assertEquals("No features found in package 'io.cucumber.junit.platform.engine.nofeatures'",
logRecord.getMessage());
}
|
static Object parseCell(String cell, Schema.Field field) {
Schema.FieldType fieldType = field.getType();
try {
switch (fieldType.getTypeName()) {
case STRING:
return cell;
case INT16:
return Short.parseShort(cell);
case INT32:
return Integer.parseInt(cell);
case INT64:
return Long.parseLong(cell);
case BOOLEAN:
return Boolean.parseBoolean(cell);
case BYTE:
return Byte.parseByte(cell);
case DECIMAL:
return new BigDecimal(cell);
case DOUBLE:
return Double.parseDouble(cell);
case FLOAT:
return Float.parseFloat(cell);
case DATETIME:
return Instant.parse(cell);
default:
throw new UnsupportedOperationException(
"Unsupported type: " + fieldType + ", consider using withCustomRecordParsing");
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
e.getMessage() + " field " + field.getName() + " was received -- type mismatch");
}
}
|
@Test
public void givenValidStringCell_parses() {
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("lithium", "lithium");
Schema schema =
Schema.builder().addStringField("a_string").addDateTimeField("a_datetime").build();
assertEquals(
cellToExpectedValue.getValue(),
CsvIOParseHelpers.parseCell(
cellToExpectedValue.getKey().toString(), schema.getField("a_string")));
}
|
public SelectorService getSelectorService() {
return selectorService;
}
|
@Test
public void testGetSelectorService() {
assertEquals(selectorService, abstractShenyuClientRegisterService.getSelectorService());
}
|
@Udf
public List<String> keys(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final List<String> ret = new ArrayList<>();
node.fieldNames().forEachRemaining(ret::add);
return ret;
}
|
@Test(expected = KsqlFunctionException.class)
public void shouldReturnNullForInvalidJson() {
udf.keys("abc");
}
|
public void register(OpChain operatorChain) {
Future<?> scheduledFuture = _executorService.submit(new TraceRunnable() {
@Override
public void runJob() {
boolean isFinished = false;
TransferableBlock returnedErrorBlock = null;
Throwable thrown = null;
try {
LOGGER.trace("({}): Executing", operatorChain);
TransferableBlock result = operatorChain.getRoot().nextBlock();
while (!result.isEndOfStreamBlock()) {
result = operatorChain.getRoot().nextBlock();
}
isFinished = true;
if (result.isErrorBlock()) {
returnedErrorBlock = result;
LOGGER.error("({}): Completed erroneously {} {}", operatorChain, result.getQueryStats(),
result.getExceptions());
} else {
LOGGER.debug("({}): Completed {}", operatorChain, result.getQueryStats());
}
} catch (Exception e) {
LOGGER.error("({}): Failed to execute operator chain!", operatorChain, e);
thrown = e;
} finally {
_submittedOpChainMap.remove(operatorChain.getId());
if (returnedErrorBlock != null || thrown != null) {
if (thrown == null) {
thrown = new RuntimeException("Error block " + returnedErrorBlock.getExceptions());
}
operatorChain.cancel(thrown);
} else if (isFinished) {
operatorChain.close();
}
}
}
});
_submittedOpChainMap.put(operatorChain.getId(), scheduledFuture);
}
|
@Test
public void shouldScheduleSingleOpChainRegisteredAfterStart()
throws InterruptedException {
OpChain opChain = getChain(_operatorA);
OpChainSchedulerService schedulerService = new OpChainSchedulerService(_executor);
CountDownLatch latch = new CountDownLatch(1);
Mockito.when(_operatorA.nextBlock()).thenAnswer(inv -> {
latch.countDown();
return TransferableBlockTestUtils.getEndOfStreamTransferableBlock(0);
});
schedulerService.register(opChain);
Assert.assertTrue(latch.await(10, TimeUnit.SECONDS), "expected await to be called in less than 10 seconds");
}
|
@Override
public Map<String, String> generationCodes(Long tableId) {
// 校验是否已经存在
CodegenTableDO table = codegenTableMapper.selectById(tableId);
if (table == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
List<CodegenColumnDO> columns = codegenColumnMapper.selectListByTableId(tableId);
if (CollUtil.isEmpty(columns)) {
throw exception(CODEGEN_COLUMN_NOT_EXISTS);
}
// 如果是主子表,则加载对应的子表信息
List<CodegenTableDO> subTables = null;
List<List<CodegenColumnDO>> subColumnsList = null;
if (CodegenTemplateTypeEnum.isMaster(table.getTemplateType())) {
// 校验子表存在
subTables = codegenTableMapper.selectListByTemplateTypeAndMasterTableId(
CodegenTemplateTypeEnum.SUB.getType(), tableId);
if (CollUtil.isEmpty(subTables)) {
throw exception(CODEGEN_MASTER_GENERATION_FAIL_NO_SUB_TABLE);
}
// 校验子表的关联字段存在
subColumnsList = new ArrayList<>();
for (CodegenTableDO subTable : subTables) {
List<CodegenColumnDO> subColumns = codegenColumnMapper.selectListByTableId(subTable.getId());
if (CollUtil.findOne(subColumns, column -> column.getId().equals(subTable.getSubJoinColumnId())) == null) {
throw exception(CODEGEN_SUB_COLUMN_NOT_EXISTS, subTable.getId());
}
subColumnsList.add(subColumns);
}
}
// 执行生成
return codegenEngine.execute(table, columns, subTables, subColumnsList);
}
|
@Test
public void testGenerationCodes_sub_tableNotExists() {
// mock 数据(CodegenTableDO)
CodegenTableDO table = randomPojo(CodegenTableDO.class,
o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())
.setTemplateType(CodegenTemplateTypeEnum.MASTER_NORMAL.getType()));
codegenTableMapper.insert(table);
// mock 数据(CodegenColumnDO)
CodegenColumnDO column01 = randomPojo(CodegenColumnDO.class, o -> o.setTableId(table.getId()));
codegenColumnMapper.insert(column01);
// 准备参数
Long tableId = table.getId();
// 调用,并断言
assertServiceException(() -> codegenService.generationCodes(tableId),
CODEGEN_MASTER_GENERATION_FAIL_NO_SUB_TABLE);
}
|
@Deprecated
public Collection<MessageQueue> queuesWithNamespace(Collection<MessageQueue> queues) {
if (StringUtils.isEmpty(this.getNamespace())) {
return queues;
}
Iterator<MessageQueue> iter = queues.iterator();
while (iter.hasNext()) {
MessageQueue queue = iter.next();
queue.setTopic(withNamespace(queue.getTopic()));
}
return queues;
}
|
@Test
public void testQueuesWithNamespace() {
MessageQueue messageQueue = new MessageQueue();
messageQueue.setTopic("defaultTopic");
Collection<MessageQueue> messageQueues = clientConfig.queuesWithNamespace(Collections.singleton(messageQueue));
assertTrue(messageQueues.contains(messageQueue));
assertEquals("lmq%defaultTopic", messageQueues.iterator().next().getTopic());
}
|
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
if (transactionManager.hasFatalError()) {
if (lastError != null)
maybeAbortBatches(lastError);
client.poll(retryBackoffMs, time.milliseconds());
return;
}
if (transactionManager.hasAbortableError() && shouldHandleAuthorizationError(lastError)) {
return;
}
// Check whether we need a new producerId. If so, we will enqueue an InitProducerId
// request which will be sent below
transactionManager.bumpIdempotentEpochAndResetIdIfNeeded();
if (maybeSendAndPollTransactionalRequest()) {
return;
}
} catch (AuthenticationException e) {
// This is already logged as error, but propagated here to perform any clean ups.
log.trace("Authentication exception while processing transactional request", e);
transactionManager.authenticationFailed(e);
}
}
long currentTimeMs = time.milliseconds();
long pollTimeout = sendProducerData(currentTimeMs);
client.poll(pollTimeout, currentTimeMs);
}
|
@Test
public void testShouldRaiseOutOfOrderSequenceExceptionToUserIfLogWasNotTruncated() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId(producerId, Errors.NONE);
assertTrue(transactionManager.hasProducerId());
assertEquals(0, transactionManager.sequenceNumber(tp0));
// Send first ProduceRequest
Future<RecordMetadata> request1 = appendToAccumulator(tp0);
sender.runOnce();
assertEquals(1, client.inFlightRequestCount());
assertEquals(1, transactionManager.sequenceNumber(tp0));
assertEquals(OptionalInt.empty(), transactionManager.lastAckedSequence(tp0));
sendIdempotentProducerResponse(0, tp0, Errors.NONE, 1000L, 10L);
sender.runOnce(); // receive the response.
assertTrue(request1.isDone());
assertEquals(1000L, request1.get().offset());
assertEquals(OptionalInt.of(0), transactionManager.lastAckedSequence(tp0));
assertEquals(OptionalLong.of(1000L), transactionManager.lastAckedOffset(tp0));
// Send second ProduceRequest,
Future<RecordMetadata> request2 = appendToAccumulator(tp0);
sender.runOnce();
assertEquals(2, transactionManager.sequenceNumber(tp0));
assertEquals(OptionalInt.of(0), transactionManager.lastAckedSequence(tp0));
assertFalse(request2.isDone());
sendIdempotentProducerResponse(1, tp0, Errors.UNKNOWN_PRODUCER_ID, -1L, 10L);
sender.runOnce(); // receive response 0, should request an epoch bump
sender.runOnce(); // bump epoch
assertEquals(1, transactionManager.producerIdAndEpoch().epoch);
assertEquals(OptionalInt.empty(), transactionManager.lastAckedSequence(tp0));
assertFalse(request2.isDone());
}
|
@VisibleForTesting
void updateBackoffMetrics(int retryCount, int statusCode) {
if (abfsBackoffMetrics != null) {
if (statusCode < HttpURLConnection.HTTP_OK
|| statusCode >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
synchronized (this) {
if (retryCount >= maxIoRetries) {
abfsBackoffMetrics.incrementNumberOfRequestsFailed();
}
}
} else {
synchronized (this) {
if (retryCount > ZERO && retryCount <= maxIoRetries) {
maxRetryCount = Math.max(abfsBackoffMetrics.getMaxRetryCount(), retryCount);
abfsBackoffMetrics.setMaxRetryCount(maxRetryCount);
updateCount(retryCount);
} else {
abfsBackoffMetrics.incrementNumberOfRequestsSucceededWithoutRetrying();
}
}
}
}
}
|
@Test
public void testBackoffRetryMetrics() throws Exception {
// Create an AzureBlobFileSystem instance.
final Configuration configuration = getRawConfiguration();
configuration.set(FS_AZURE_METRIC_FORMAT, String.valueOf(MetricFormat.INTERNAL_BACKOFF_METRIC_FORMAT));
final AzureBlobFileSystem fs = (AzureBlobFileSystem) FileSystem.newInstance(configuration);
AbfsConfiguration abfsConfiguration = fs.getAbfsStore().getAbfsConfiguration();
// Get an instance of AbfsClient and AbfsRestOperation.
AbfsClient testClient = super.getAbfsClient(super.getAbfsStore(fs));
AbfsRestOperation op = ITestAbfsClient.getRestOp(
DeletePath, testClient, HTTP_METHOD_DELETE,
ITestAbfsClient.getTestUrl(testClient, "/NonExistingPath"),
ITestAbfsClient.getTestRequestHeaders(testClient), getConfiguration());
// Mock retry counts and status code.
ArrayList<String> retryCounts = new ArrayList<>(Arrays.asList("35", "28", "31", "45", "10", "2", "9"));
int statusCode = HttpURLConnection.HTTP_UNAVAILABLE;
// Update backoff metrics.
for (String retryCount : retryCounts) {
op.updateBackoffMetrics(Integer.parseInt(retryCount), statusCode);
}
// For retry count greater than the max configured value, the request should fail.
Assert.assertEquals("Number of failed requests does not match expected value.",
"3", String.valueOf(testClient.getAbfsCounters().getAbfsBackoffMetrics().getNumberOfRequestsFailed()));
// Close the AzureBlobFileSystem.
fs.close();
}
|
public Response listDumpFiles(String topologyId, String hostPort, String user) throws IOException {
String portStr = hostPort.split(":")[1];
Path rawDir = logRoot.resolve(topologyId).resolve(portStr);
Path absDir = rawDir.toAbsolutePath().normalize();
if (!absDir.startsWith(logRoot) || !rawDir.normalize().toString().equals(rawDir.toString())) {
//Ensure filename doesn't contain ../ parts
return LogviewerResponseBuilder.buildResponsePageNotFound();
}
if (absDir.toFile().exists()) {
String workerFileRelativePath = String.join(File.separator, topologyId, portStr, WORKER_LOG_FILENAME);
if (resourceAuthorizer.isUserAllowedToAccessFile(user, workerFileRelativePath)) {
String content = buildDumpFileListPage(topologyId, hostPort, absDir.toFile());
return LogviewerResponseBuilder.buildSuccessHtmlResponse(content);
} else {
return LogviewerResponseBuilder.buildResponseUnauthorizedUser(user);
}
} else {
return LogviewerResponseBuilder.buildResponsePageNotFound();
}
}
|
@Test
public void testListDumpFilesTraversalInTopoId() throws Exception {
try (TmpPath rootPath = new TmpPath()) {
LogviewerProfileHandler handler = createHandlerTraversalTests(rootPath.getFile().toPath());
Response response = handler.listDumpFiles("../../", "localhost:logs", "user");
Utils.forceDelete(rootPath.toString());
assertThat(response.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.