focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public CompletionStage<V> getAsync(K key) {
return cache.getAsync(key);
}
|
@Test
public void testGetAsync() throws Exception {
cache.put(42, "foobar");
Future<String> future = adapter.getAsync(42).toCompletableFuture();
String result = future.get();
assertEquals("foobar", result);
}
|
private static boolean canSatisfyConstraints(ApplicationId appId,
PlacementConstraint constraint, SchedulerNode node,
AllocationTagsManager atm,
Optional<DiagnosticsCollector> dcOpt)
throws InvalidAllocationTagsQueryException {
if (constraint == null) {
LOG.debug("Constraint is found empty during constraint validation for"
+ " app:{}", appId);
return true;
}
// If this is a single constraint, transform to SingleConstraint
SingleConstraintTransformer singleTransformer =
new SingleConstraintTransformer(constraint);
constraint = singleTransformer.transform();
AbstractConstraint sConstraintExpr = constraint.getConstraintExpr();
// TODO handle other type of constraints, e.g CompositeConstraint
if (sConstraintExpr instanceof SingleConstraint) {
SingleConstraint single = (SingleConstraint) sConstraintExpr;
return canSatisfySingleConstraint(appId, single, node, atm, dcOpt);
} else if (sConstraintExpr instanceof And) {
And and = (And) sConstraintExpr;
return canSatisfyAndConstraint(appId, and, node, atm, dcOpt);
} else if (sConstraintExpr instanceof Or) {
Or or = (Or) sConstraintExpr;
return canSatisfyOrConstraint(appId, or, node, atm, dcOpt);
} else {
throw new InvalidAllocationTagsQueryException(
"Unsupported type of constraint: "
+ sConstraintExpr.getClass().getSimpleName());
}
}
|
@Test
public void testInvalidAllocationTagNamespace() {
AllocationTagsManager tm = new AllocationTagsManager(rmContext);
PlacementConstraintManagerService pcm =
new MemoryPlacementConstraintManager();
rmContext.setAllocationTagsManager(tm);
rmContext.setPlacementConstraintManager(pcm);
long ts = System.currentTimeMillis();
ApplicationId application1 = BuilderUtils.newApplicationId(ts, 123);
RMNode n0r1 = rmNodes.get(0);
SchedulerNode schedulerNode0 = newSchedulerNode(n0r1.getHostName(),
n0r1.getRackName(), n0r1.getNodeID());
PlacementConstraint constraint1 = PlacementConstraints
.targetNotIn(NODE, allocationTagWithNamespace("unknown_namespace",
"hbase-m"))
.build();
Set<String> srcTags1 = new HashSet<>();
srcTags1.add("app1");
try {
PlacementConstraintsUtil.canSatisfyConstraints(application1,
createSchedulingRequest(srcTags1, constraint1), schedulerNode0,
pcm, tm);
Assert.fail("This should fail because we gave an invalid namespace");
} catch (Exception e) {
Assert.assertTrue(e instanceof InvalidAllocationTagsQueryException);
Assert.assertTrue(e.getMessage()
.contains("Invalid namespace prefix: unknown_namespace"));
}
}
|
public String getShare() {
return share;
}
|
@Test
void shareForDoubleSlashURIPathShouldBeExtracted() {
// relaxed handling, it could be rejected if we wanted to be strict
var remoteConf = context.getEndpoint("azure-files://account//share/", FilesEndpoint.class).getConfiguration();
assertEquals("share", remoteConf.getShare());
}
|
@Override
public Long sendSingleNotifyToAdmin(Long userId, String templateCode, Map<String, Object> templateParams) {
return sendSingleNotify(userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams);
}
|
@Test
public void testSendSingleNotifyToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// mock NotifyTemplateService 的方法
NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class, o -> {
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setContent("验证码为{code}, 操作为{op}");
o.setParams(Lists.newArrayList("code", "op"));
});
when(notifyTemplateService.getNotifyTemplateByCodeFromCache(eq(templateCode))).thenReturn(template);
String content = randomString();
when(notifyTemplateService.formatNotifyTemplateContent(eq(template.getContent()), eq(templateParams)))
.thenReturn(content);
// mock NotifyMessageService 的方法
Long messageId = randomLongId();
when(notifyMessageService.createNotifyMessage(eq(userId), eq(UserTypeEnum.ADMIN.getValue()),
eq(template), eq(content), eq(templateParams))).thenReturn(messageId);
// 调用
Long resultMessageId = notifySendService.sendSingleNotifyToAdmin(userId, templateCode, templateParams);
// 断言
assertEquals(messageId, resultMessageId);
}
|
public Long getAvgMergeTime() {
return avgMergeTime;
}
|
@Test(timeout = 10000)
public void testAverageMergeTime() throws IOException {
String historyFileName =
"job_1329348432655_0001-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist";
String confFileName =
"job_1329348432655_0001_conf.xml";
Configuration conf = new Configuration();
JobACLsManager jobAclsMgr = new JobACLsManager(conf);
Path fulleHistoryPath =
new Path(TestJobHistoryEntities.class.getClassLoader()
.getResource(historyFileName)
.getFile());
Path fullConfPath =
new Path(TestJobHistoryEntities.class.getClassLoader()
.getResource(confFileName)
.getFile());
HistoryFileInfo info = mock(HistoryFileInfo.class);
when(info.getConfFile()).thenReturn(fullConfPath);
when(info.getHistoryFile()).thenReturn(fulleHistoryPath);
JobId jobId = MRBuilderUtils.newJobId(1329348432655l, 1, 1);
CompletedJob completedJob =
new CompletedJob(conf, jobId, fulleHistoryPath, true, "user",
info, jobAclsMgr);
JobInfo jobInfo = new JobInfo(completedJob);
// There are 2 tasks with merge time of 45 and 55 respectively. So average
// merge time should be 50.
Assert.assertEquals(50L, jobInfo.getAvgMergeTime().longValue());
}
|
public static AccessTokenValidator create(Map<String, ?> configs) {
return create(configs, (String) null);
}
|
@Test
public void testConfigureThrowsExceptionOnAccessTokenValidatorInit() {
OAuthBearerLoginCallbackHandler handler = new OAuthBearerLoginCallbackHandler();
AccessTokenRetriever accessTokenRetriever = new AccessTokenRetriever() {
@Override
public void init() throws IOException {
throw new IOException("My init had an error!");
}
@Override
public String retrieve() {
return "dummy";
}
};
Map<String, ?> configs = getSaslConfigs();
AccessTokenValidator accessTokenValidator = AccessTokenValidatorFactory.create(configs);
assertThrowsWithMessage(
KafkaException.class, () -> handler.init(accessTokenRetriever, accessTokenValidator), "encountered an error when initializing");
}
|
public static void add(String group, List<String> users) {
for (String user : users) {
Set<String> userGroups = userToNetgroupsMap.get(user);
// ConcurrentHashMap does not allow null values;
// So null value check can be used to check if the key exists
if (userGroups == null) {
//Generate a ConcurrentHashSet (backed by the keyset of the ConcurrentHashMap)
userGroups =
Collections.newSetFromMap(new ConcurrentHashMap<String,Boolean>());
Set<String> currentSet = userToNetgroupsMap.putIfAbsent(user, userGroups);
if (currentSet != null) {
userGroups = currentSet;
}
}
userGroups.add(group);
}
}
|
@Test
public void testMembership() {
List<String> users = new ArrayList<String>();
users.add(USER1);
users.add(USER2);
NetgroupCache.add(GROUP1, users);
users = new ArrayList<String>();
users.add(USER1);
users.add(USER3);
NetgroupCache.add(GROUP2, users);
verifyGroupMembership(USER1, 2, GROUP1);
verifyGroupMembership(USER1, 2, GROUP2);
verifyGroupMembership(USER2, 1, GROUP1);
verifyGroupMembership(USER3, 1, GROUP2);
}
|
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = models.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = 0;
for (int i = 0; i < ntrees; i++) {
base = base + models[i].tree.predict(xj);
prediction[i][j] = base / (i+1);
}
}
return prediction;
}
|
@Test
public void testKin8nm() {
test("kin8nm", Kin8nm.formula, Kin8nm.data, 0.1704);
}
|
public String getName() {
String path = uri.getPath();
int slash = path.lastIndexOf(SEPARATOR);
return path.substring(slash+1);
}
|
@Test (timeout = 30000)
public void testGetName() {
assertEquals("", new Path("/").getName());
assertEquals("foo", new Path("foo").getName());
assertEquals("foo", new Path("/foo").getName());
assertEquals("foo", new Path("/foo/").getName());
assertEquals("bar", new Path("/foo/bar").getName());
assertEquals("bar", new Path("hdfs://host/foo/bar").getName());
}
|
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
super.pluginLoaded(pluginDescriptor);
if(extension.canHandlePlugin(pluginDescriptor.id())) {
for (PluginMetadataChangeListener listener: listeners) {
listener.onPluginMetadataCreate(pluginDescriptor.id());
}
}
}
|
@Test
public void onPluginLoaded_shouldIgnoreNonAnalyticsPlugins() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
AnalyticsMetadataLoader metadataLoader = new AnalyticsMetadataLoader(pluginManager, metadataStore, infoBuilder, extension);
when(extension.canHandlePlugin(descriptor.id())).thenReturn(false);
metadataLoader.pluginLoaded(descriptor);
verifyNoMoreInteractions(infoBuilder);
verifyNoMoreInteractions(metadataStore);
}
|
static KiePMMLClusteringField getKiePMMLClusteringField(ClusteringField clusteringField) {
double fieldWeight = clusteringField.getFieldWeight() == null ? 1.0 :
clusteringField.getFieldWeight().doubleValue();
boolean isCenterField =
clusteringField.getCenterField() == null || clusteringField.getCenterField() == ClusteringField.CenterField.TRUE;
KiePMMLCompareFunction kiePMMLCompareFunction = clusteringField.getCompareFunction() != null ? compareFunctionFrom(clusteringField.getCompareFunction()) : null;
return new KiePMMLClusteringField(clusteringField.getField(), fieldWeight, isCenterField,
kiePMMLCompareFunction, null);
}
|
@Test
void getKiePMMLClusteringField() {
ClusteringField clusteringField = new ClusteringField();
final Random random = new Random();
clusteringField.setField("TEXT");
clusteringField.setFieldWeight(random.nextDouble());
clusteringField.setCenterField(getRandomEnum(ClusteringField.CenterField.values()));
clusteringField.setCompareFunction(getRandomEnum(CompareFunction.values()));
KiePMMLClusteringField retrieved = KiePMMLClusteringModelFactory.getKiePMMLClusteringField(clusteringField);
commonEvaluateKiePMMLClusteringField(retrieved, clusteringField);
}
|
public static final void loadAttributesMap( DataNode dataNode, AttributesInterface attributesInterface )
throws KettleException {
loadAttributesMap( dataNode, attributesInterface, NODE_ATTRIBUTE_GROUPS );
}
|
@Test
public void testLoadAttributesMap_DefaultTag() throws Exception {
try ( MockedStatic<AttributesMapUtil> mockedAttributesMapUtil = mockStatic( AttributesMapUtil.class ) ) {
mockedAttributesMapUtil.when( () -> AttributesMapUtil.loadAttributesMap( any( DataNode.class ),
any( AttributesInterface.class ) ) ).thenCallRealMethod();
mockedAttributesMapUtil.when( () -> AttributesMapUtil.loadAttributesMap( any( DataNode.class ),
any( AttributesInterface.class ), anyString() ) ).thenCallRealMethod();
DataNode dataNode = new DataNode( CNST_DUMMY );
DataNode groupsDataNode = dataNode.addNode( AttributesMapUtil.NODE_ATTRIBUTE_GROUPS );
DataNode aGroupDataNode = groupsDataNode.addNode( A_GROUP );
aGroupDataNode.setProperty( A_KEY, A_VALUE );
JobEntryCopy jobEntryCopy = new JobEntryCopy();
AttributesMapUtil.loadAttributesMap( dataNode, jobEntryCopy );
assertNotNull( jobEntryCopy.getAttributesMap() );
assertNotNull( jobEntryCopy.getAttributes( A_GROUP ) );
assertEquals( A_VALUE, jobEntryCopy.getAttribute( A_GROUP, A_KEY ) );
}
}
|
Map<ProjectionProducer<PTransform<?, ?>>, Map<PCollection<?>, FieldAccessDescriptor>>
getPushdownOpportunities() {
return pushdownOpportunities.build();
}
|
@Test
public void testPushdownProducersWithMultipleOutputs_returnsMultiplePushdowns() {
Pipeline p = Pipeline.create();
PTransform<PBegin, PCollectionTuple> source = new MultipleOutputSourceWithPushdown();
PCollectionTuple outputs = p.apply(source);
Map<PCollection<?>, FieldAccessDescriptor> pCollectionFieldAccess =
ImmutableMap.of(
outputs.get("output1"),
FieldAccessDescriptor.withFieldNames("field1", "field2"),
outputs.get("output2"),
FieldAccessDescriptor.withFieldNames("field3", "field4"));
ProjectionProducerVisitor visitor = new ProjectionProducerVisitor(pCollectionFieldAccess);
p.traverseTopologically(visitor);
Map<ProjectionProducer<PTransform<?, ?>>, Map<PCollection<?>, FieldAccessDescriptor>>
pushdownOpportunities = visitor.getPushdownOpportunities();
Assert.assertEquals(1, pushdownOpportunities.size());
Map<PCollection<?>, FieldAccessDescriptor> opportunitiesForSource =
pushdownOpportunities.get(source);
Assert.assertNotNull(opportunitiesForSource);
Assert.assertEquals(2, opportunitiesForSource.size());
FieldAccessDescriptor fieldAccessDescriptor1 =
opportunitiesForSource.get(outputs.get("output1"));
Assert.assertNotNull(fieldAccessDescriptor1);
Assert.assertFalse(fieldAccessDescriptor1.getAllFields());
assertThat(fieldAccessDescriptor1.fieldNamesAccessed(), containsInAnyOrder("field1", "field2"));
FieldAccessDescriptor fieldAccessDescriptor2 =
opportunitiesForSource.get(outputs.get("output2"));
Assert.assertNotNull(fieldAccessDescriptor2);
Assert.assertFalse(fieldAccessDescriptor2.getAllFields());
assertThat(fieldAccessDescriptor2.fieldNamesAccessed(), containsInAnyOrder("field3", "field4"));
}
|
public static void createTrustedCertificatesVolumes(List<Volume> volumeList, List<CertSecretSource> trustedCertificates, boolean isOpenShift) {
createTrustedCertificatesVolumes(volumeList, trustedCertificates, isOpenShift, null);
}
|
@Test
public void testTrustedCertificatesVolumes() {
CertSecretSource cert1 = new CertSecretSourceBuilder()
.withSecretName("first-certificate")
.withCertificate("ca.crt")
.build();
CertSecretSource cert2 = new CertSecretSourceBuilder()
.withSecretName("second-certificate")
.withCertificate("tls.crt")
.build();
CertSecretSource cert3 = new CertSecretSourceBuilder()
.withSecretName("first-certificate")
.withCertificate("ca2.crt")
.build();
List<Volume> volumes = new ArrayList<>();
CertUtils.createTrustedCertificatesVolumes(volumes, List.of(cert1, cert2, cert3), false);
assertThat(volumes.size(), is(2));
assertThat(volumes.get(0).getName(), is("first-certificate"));
assertThat(volumes.get(0).getSecret().getSecretName(), is("first-certificate"));
assertThat(volumes.get(1).getName(), is("second-certificate"));
assertThat(volumes.get(1).getSecret().getSecretName(), is("second-certificate"));
}
|
@Override
public PageResult<FileConfigDO> getFileConfigPage(FileConfigPageReqVO pageReqVO) {
return fileConfigMapper.selectPage(pageReqVO);
}
|
@Test
public void testGetFileConfigPage() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setName("芋道源码")
.setStorage(FileStorageEnum.LOCAL.getStorage());
dbFileConfig.setCreateTime(LocalDateTimeUtil.parse("2020-01-23", DatePattern.NORM_DATE_PATTERN));// 等会查询到
fileConfigMapper.insert(dbFileConfig);
// 测试 name 不匹配
fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setName("源码")));
// 测试 storage 不匹配
fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setStorage(FileStorageEnum.DB.getStorage())));
// 测试 createTime 不匹配
fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setCreateTime(LocalDateTimeUtil.parse("2020-11-23", DatePattern.NORM_DATE_PATTERN))));
// 准备参数
FileConfigPageReqVO reqVO = new FileConfigPageReqVO();
reqVO.setName("芋道");
reqVO.setStorage(FileStorageEnum.LOCAL.getStorage());
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 1, 1),
buildTime(2020, 1, 24)}));
// 调用
PageResult<FileConfigDO> pageResult = fileConfigService.getFileConfigPage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbFileConfig, pageResult.getList().get(0));
}
|
@Override
public void finish()
throws IOException
{
writer.flush();
}
|
@Test
public void testJsonPrintingNoRows()
throws Exception
{
StringWriter writer = new StringWriter();
List<String> fieldNames = ImmutableList.of("first", "last");
OutputPrinter printer = new JsonPrinter(fieldNames, writer);
printer.finish();
assertEquals(writer.getBuffer().toString(), "");
}
|
public void incrementCount() {
incrementCount(headSlot, 1);
}
|
@Test
public void testIncrementCount() {
assertEquals(0, counter.get(1));
assertEquals(0, counter.get(2));
counter.incrementCount();
assertEquals(1, counter.get(1));
assertEquals(1, counter.get(2));
counter.incrementCount(2);
assertEquals(3, counter.get(2));
}
|
public static LineageGraph convertToLineageGraph(List<Transformation<?>> transformations) {
DefaultLineageGraph.LineageGraphBuilder builder = DefaultLineageGraph.builder();
for (Transformation<?> transformation : transformations) {
List<LineageEdge> edges = processSink(transformation);
for (LineageEdge lineageEdge : edges) {
builder.addLineageEdge(lineageEdge);
}
}
return builder.build();
}
|
@Test
void testExtractLineageGraphFromLegacyTransformations() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Long> source = env.addSource(new LineageSourceFunction());
DataStreamSink<Long> sink = source.addSink(new LineageSinkFunction());
LineageGraph lineageGraph =
LineageGraphUtils.convertToLineageGraph(Arrays.asList(sink.getTransformation()));
assertThat(lineageGraph.sources().size()).isEqualTo(1);
assertThat(lineageGraph.sources().get(0).boundedness())
.isEqualTo(Boundedness.CONTINUOUS_UNBOUNDED);
assertThat(lineageGraph.sources().get(0).datasets().size()).isEqualTo(1);
assertThat(lineageGraph.sources().get(0).datasets().get(0).name())
.isEqualTo(LEGACY_SOURCE_DATASET_NAME);
assertThat(lineageGraph.sources().get(0).datasets().get(0).namespace())
.isEqualTo(LEGACY_SOURCE_DATASET_NAMESPACE);
assertThat(lineageGraph.sinks().size()).isEqualTo(1);
assertThat(lineageGraph.sinks().get(0).datasets().size()).isEqualTo(1);
assertThat(lineageGraph.sinks().get(0).datasets().get(0).name())
.isEqualTo(LEGACY_SINK_DATASET_NAME);
assertThat(lineageGraph.sinks().get(0).datasets().get(0).namespace())
.isEqualTo(LEGACY_SINK_DATASET_NAMESPACE);
assertThat(lineageGraph.relations().size()).isEqualTo(1);
}
|
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String targetObjectId = reader.readLine();
String methodName = reader.readLine();
List<Object> arguments = getArguments(reader);
ReturnObject returnObject = invokeMethod(methodName, targetObjectId, arguments);
String returnCommand = Protocol.getOutputCommand(returnObject);
logger.finest("Returning command: " + returnCommand);
writer.write(returnCommand);
writer.flush();
}
|
@Test
public void testReflectionException2() {
String inputCommand = target + "\nmethod1aa\ne\n";
try {
command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer);
assertTrue(sWriter.toString().startsWith("!xspy4j.Py4JException: "));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
|
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
EntityType originatorEntityType = msg.getOriginator().getEntityType();
if (!EntityType.DEVICE.equals(originatorEntityType)) {
ctx.tellFailure(msg, new IllegalArgumentException(
"Unsupported originator entity type: [" + originatorEntityType + "]. Only DEVICE entity type is supported."
));
return;
}
DeviceId originator = new DeviceId(msg.getOriginator().getId());
rateLimits.compute(originator, (__, rateLimit) -> {
if (rateLimit == null) {
rateLimit = new TbRateLimits(rateLimitConfig);
}
boolean isNotRateLimited = rateLimit.tryConsume();
if (isNotRateLimited) {
sendEventAndTell(ctx, originator, msg);
} else {
ctx.tellNext(msg, "Rate limited");
}
return rateLimit;
});
}
|
@Test
public void givenMsgArrivedTooFast_whenOnMsg_thenRateLimitsThisMsg() {
// GIVEN
ConcurrentReferenceHashMap<DeviceId, TbRateLimits> rateLimits = new ConcurrentReferenceHashMap<>();
ReflectionTestUtils.setField(node, "rateLimits", rateLimits);
var rateLimitMock = mock(TbRateLimits.class);
rateLimits.put(DEVICE_ID, rateLimitMock);
given(rateLimitMock.tryConsume()).willReturn(false);
// WHEN
node.onMsg(ctxMock, msg);
// THEN
then(ctxMock).should().tellNext(msg, "Rate limited");
then(ctxMock).should(never()).tellSuccess(any());
then(ctxMock).should(never()).tellFailure(any(), any());
then(ctxMock).shouldHaveNoMoreInteractions();
then(deviceStateManagerMock).shouldHaveNoInteractions();
}
|
@Override
public void reset() {
set(INIT);
}
|
@Test
public void testReset() {
SnapshotRegistry registry = new SnapshotRegistry(new LogContext());
TimelineLong value = new TimelineLong(registry);
registry.getOrCreateSnapshot(2);
value.set(1L);
registry.getOrCreateSnapshot(3);
value.set(2L);
registry.reset();
assertEquals(Collections.emptyList(), registry.epochsList());
assertEquals(TimelineLong.INIT, value.get());
}
|
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(itemType, "itemType may not be null");
if (dataTable.isEmpty()) {
return emptyList();
}
ListOrProblems<T> result = toListOrProblems(dataTable, itemType);
if (result.hasList()) {
return unmodifiableList(result.getList());
}
throw listNoConverterDefined(
itemType,
result.getProblems());
}
|
@Test
void convert_to_list__double_column__throws_exception() {
DataTable table = parse("",
"| 3 | 5 |",
"| 6 | 7 |");
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> converter.toList(table, Integer.class));
assertThat(exception.getMessage(), is("" +
"Can't convert DataTable to List<java.lang.Integer>.\n" +
"Please review these problems:\n" +
"\n" +
" - There was a table cell transformer for java.lang.Integer but the table was too wide to use it.\n" +
" Please reduce the table width to use this converter.\n" +
"\n" +
" - There was no table entry or table row transformer registered for java.lang.Integer.\n" +
" Please consider registering a table entry or row transformer.\n" +
"\n" +
" - There was no default table entry transformer registered to transform java.lang.Integer.\n" +
" Please consider registering a default table entry transformer.\n" +
"\n" +
"Note: Usually solving one is enough"));
}
|
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.importPolicy().classReference(inliner, getTopLevelClass(), getName());
}
|
@Test
public void inline() {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
context.put(PackageSymbol.class, Symtab.instance(context).rootPackage);
assertInlines("List", UClassIdent.create("java.util.List"));
assertInlines("Map.Entry", UClassIdent.create("java.util.Map.Entry"));
}
|
public Set<String> usedStreamIds() {
final Set<String> queryStreamIds = queries().stream()
.map(Query::usedStreamIds)
.reduce(Collections.emptySet(), Sets::union);
final Set<String> searchTypeStreamIds = queries().stream()
.flatMap(q -> q.searchTypes().stream())
.map(SearchType::effectiveStreams)
.reduce(Collections.emptySet(), Sets::union);
return Sets.union(queryStreamIds, searchTypeStreamIds);
}
|
@Test
void usedStreamIdsReturnsQueryStreamsWhenSearchTypesAreMissing() {
final Search search = searchWithQueriesWithStreams("c,d,e");
assertThat(search.usedStreamIds()).containsExactlyInAnyOrder("c", "d", "e");
}
|
public boolean isDisabled() {
return _disabled;
}
|
@Test
public void withDisabledFalse()
throws JsonProcessingException {
String confStr = "{\"disabled\": false}";
IndexConfig config = JsonUtils.stringToObject(confStr, IndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
}
|
@Override
public void run() {
SecurityManager sm = System.getSecurityManager();
if (!(sm instanceof SelSecurityManager)) {
throw new IllegalStateException("Invalid security manager: " + sm);
}
Thread.currentThread().setContextClassLoader(this.classLoader);
((SelSecurityManager) sm).setAccessControl(this.acc);
super.run();
}
|
@Test
public void testRun() throws Exception {
assertEquals(0, i);
System.setSecurityManager(new SelSecurityManager());
t2.start();
t2.join();
assertEquals(10, i);
assertNull(ex);
}
|
@Override
public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria)
{
Map<String, String> variables = new HashMap<>();
if (userRegex.isPresent()) {
Matcher userMatcher = userRegex.get().matcher(criteria.getUser());
if (!userMatcher.matches()) {
return Optional.empty();
}
addVariableValues(userRegex.get(), criteria.getUser(), variables);
}
if (sourceRegex.isPresent()) {
String source = criteria.getSource().orElse("");
if (!sourceRegex.get().matcher(source).matches()) {
return Optional.empty();
}
addVariableValues(sourceRegex.get(), source, variables);
}
if (principalRegex.isPresent()) {
String principal = criteria.getPrincipal().orElse("");
if (!principalRegex.get().matcher(principal).matches()) {
return Optional.empty();
}
addVariableValues(principalRegex.get(), principal, variables);
}
if (!clientTags.isEmpty() && !criteria.getTags().containsAll(clientTags)) {
return Optional.empty();
}
if (clientInfoRegex.isPresent() && !clientInfoRegex.get().matcher(criteria.getClientInfo().orElse(EMPTY_CRITERIA_STRING)).matches()) {
return Optional.empty();
}
if (selectorResourceEstimate.isPresent() && !selectorResourceEstimate.get().match(criteria.getResourceEstimates())) {
return Optional.empty();
}
if (queryType.isPresent()) {
String contextQueryType = criteria.getQueryType().orElse(EMPTY_CRITERIA_STRING);
if (!queryType.get().equalsIgnoreCase(contextQueryType)) {
return Optional.empty();
}
}
if (schema.isPresent() && criteria.getSchema().isPresent()) {
if (criteria.getSchema().get().compareToIgnoreCase(schema.get()) != 0) {
return Optional.empty();
}
}
variables.putIfAbsent(USER_VARIABLE, criteria.getUser());
// Special handling for source, which is an optional field that is part of the standard variables
variables.putIfAbsent(SOURCE_VARIABLE, criteria.getSource().orElse(""));
variables.putIfAbsent(SCHEMA_VARIABLE, criteria.getSchema().orElse(""));
VariableMap map = new VariableMap(variables);
ResourceGroupId id = group.expandTemplate(map);
OptionalInt firstDynamicSegment = group.getFirstDynamicSegment();
return Optional.of(new SelectionContext<>(id, map, firstDynamicSegment));
}
|
@Test
public void testUserRegex()
{
ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "foo");
StaticSelector selector = new StaticSelector(
Optional.of(Pattern.compile("user.*")),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
new ResourceGroupIdTemplate("global.foo"));
assertEquals(selector.match(newSelectionCriteria("userA", null, ImmutableSet.of("tag1"), EMPTY_RESOURCE_ESTIMATES)).map(SelectionContext::getResourceGroupId), Optional.of(resourceGroupId));
assertEquals(selector.match(newSelectionCriteria("userB", "source", ImmutableSet.of(), EMPTY_RESOURCE_ESTIMATES)).map(SelectionContext::getResourceGroupId), Optional.of(resourceGroupId));
assertEquals(selector.match(newSelectionCriteria("A.user", null, ImmutableSet.of("tag1"), EMPTY_RESOURCE_ESTIMATES)), Optional.empty());
}
|
@Override
public Map<String, Object> newMap() {
return new CaseInsensitiveMap<>();
}
|
@Test
public void testConstructFromOther() {
Map<String, Object> other = new FastHeadersMapFactory().newMap();
other.put("Foo", "cheese");
other.put("bar", 123);
Map<String, Object> map = new FastHeadersMapFactory().newMap(other);
assertEquals("cheese", map.get("FOO"));
assertEquals("cheese", map.get("foo"));
assertEquals("cheese", map.get("Foo"));
assertEquals(123, map.get("BAR"));
assertEquals(123, map.get("bar"));
assertEquals(123, map.get("BaR"));
}
|
@Override
public boolean delete(URI segmentUri, boolean forceDelete)
throws IOException {
LOGGER.info("Deleting uri {} force {}", segmentUri, forceDelete);
try {
if (isDirectory(segmentUri)) {
if (!forceDelete) {
Preconditions.checkState(isEmptyDirectory(segmentUri),
"ForceDelete flag is not set and directory '%s' is not empty", segmentUri);
}
String prefix = normalizeToDirectoryPrefix(segmentUri);
ListObjectsV2Response listObjectsV2Response;
ListObjectsV2Request.Builder listObjectsV2RequestBuilder =
ListObjectsV2Request.builder().bucket(segmentUri.getHost());
if (prefix.equals(DELIMITER)) {
ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.build();
listObjectsV2Response = _s3Client.listObjectsV2(listObjectsV2Request);
} else {
ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.prefix(prefix).build();
listObjectsV2Response = _s3Client.listObjectsV2(listObjectsV2Request);
}
boolean deleteSucceeded = true;
for (S3Object s3Object : listObjectsV2Response.contents()) {
DeleteObjectRequest deleteObjectRequest =
DeleteObjectRequest.builder().bucket(segmentUri.getHost()).key(s3Object.key()).build();
DeleteObjectResponse deleteObjectResponse = _s3Client.deleteObject(deleteObjectRequest);
deleteSucceeded &= deleteObjectResponse.sdkHttpResponse().isSuccessful();
}
return deleteSucceeded;
} else {
String prefix = sanitizePath(segmentUri.getPath());
DeleteObjectRequest deleteObjectRequest =
DeleteObjectRequest.builder().bucket(segmentUri.getHost()).key(prefix).build();
DeleteObjectResponse deleteObjectResponse = _s3Client.deleteObject(deleteObjectRequest);
return deleteObjectResponse.sdkHttpResponse().isSuccessful();
}
} catch (NoSuchKeyException e) {
return false;
} catch (S3Exception e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
|
@Test
public void testDeleteFile()
throws Exception {
String[] originalFiles = new String[]{"a-delete.txt", "b-delete.txt", "c-delete.txt"};
String fileToDelete = "a-delete.txt";
List<String> expectedResultList = new ArrayList<>();
for (String fileName : originalFiles) {
createEmptyFile("", fileName);
if (!fileName.equals(fileToDelete)) {
expectedResultList.add(fileName);
}
}
boolean deleteResult = _s3PinotFS.delete(
URI.create(String.format(FILE_FORMAT, SCHEME, BUCKET, fileToDelete)), false);
Assert.assertTrue(deleteResult);
ListObjectsV2Response listObjectsV2Response =
_s3Client.listObjectsV2(S3TestUtils.getListObjectRequest(BUCKET, "", true));
String[] actualResponse =
listObjectsV2Response.contents().stream().map(S3Object::key).filter(x -> x.contains("delete"))
.toArray(String[]::new);
Assert.assertEquals(actualResponse.length, 2);
Assert.assertTrue(Arrays.equals(actualResponse, expectedResultList.toArray()));
}
|
public static Method setter(Class<?> o, String propertiesName) {
if (o == null) {
return null;
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o);
return descriptor.getWriteMethod();
} catch (IntrospectionException e) {
throw new RuntimeException("not find setter for" + propertiesName + "in" + o.getName(), e);
}
}
|
@Test
public void testSetter() {
Method name = BeanUtil.setter(Customer.class, "name");
Assert.assertEquals("setName", name.getName());
}
|
@Override
public Object construct(String componentName) {
ClusteringConfiguration clusteringConfiguration = configuration.clustering();
boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer();
int level = configuration.locking().concurrencyLevel();
MemoryConfiguration memoryConfiguration = configuration.memory();
boolean offHeap = memoryConfiguration.isOffHeap();
EvictionStrategy strategy = memoryConfiguration.whenFull();
//handle case when < 0 value signifies unbounded container or when we are not removal based
if (strategy.isExceptionBased() || !strategy.isEnabled()) {
if (offHeap) {
if (shouldSegment) {
int segments = clusteringConfiguration.hash().numSegments();
Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier =
this::createAndStartOffHeapConcurrentMap;
if (clusteringConfiguration.l1().enabled()) {
return new L1SegmentedDataContainer<>(mapSupplier, segments);
}
return new DefaultSegmentedDataContainer<>(mapSupplier, segments);
} else {
return new OffHeapDataContainer();
}
} else if (shouldSegment) {
Supplier<PeekableTouchableMap<Object, Object>> mapSupplier =
PeekableTouchableContainerMap::new;
int segments = clusteringConfiguration.hash().numSegments();
if (clusteringConfiguration.l1().enabled()) {
return new L1SegmentedDataContainer<>(mapSupplier, segments);
}
return new DefaultSegmentedDataContainer<>(mapSupplier, segments);
} else {
return DefaultDataContainer.unBoundedDataContainer(level);
}
}
boolean sizeInBytes = memoryConfiguration.maxSize() != null;
long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount();
DataContainer<?, ?> dataContainer;
if (offHeap) {
if (shouldSegment) {
int segments = clusteringConfiguration.hash().numSegments();
dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize,
memoryConfiguration.evictionType());
} else {
dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType());
}
} else if (shouldSegment) {
int segments = clusteringConfiguration.hash().numSegments();
dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize,
memoryConfiguration.evictionType());
} else {
dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize,
memoryConfiguration.evictionType());
}
if (sizeInBytes) {
memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE)
.addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes()));
} else {
memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT)
.addListener((newSize, old) -> dataContainer.resize(newSize.get()));
}
return dataContainer;
}
|
@Test
public void testDefaultSegmented() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.cacheMode(CacheMode.DIST_ASYNC).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(DefaultSegmentedDataContainer.class, component.getClass());
}
|
@Override
public int run(String[] argv) {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-safemode".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-allowSnapshot".equalsIgnoreCase(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-disallowSnapshot".equalsIgnoreCase(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-provisionSnapshotTrash".equalsIgnoreCase(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-report".equals(cmd)) {
if (argv.length > DFS_REPORT_ARGS.length + 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-saveNamespace".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-rollEdits".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-restoreFailedStorage".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-refreshNodes".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-finalizeUpgrade".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if (RollingUpgradeCommand.matches(cmd)) {
if (argv.length > 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-upgrade".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-metasave".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-refreshServiceAcl".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-refresh".equals(cmd)) {
if (argv.length < 3) {
printUsage(cmd);
return exitCode;
}
} else if ("-refreshUserToGroupsMappings".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-printTopology".equals(cmd)) {
if(argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-refreshNamenodes".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-getVolumeReport".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-reconfig".equals(cmd)) {
if (argv.length != 4) {
printUsage(cmd);
return exitCode;
}
} else if ("-deleteBlockPool".equals(cmd)) {
if ((argv.length != 3) && (argv.length != 4)) {
printUsage(cmd);
return exitCode;
}
} else if ("-setBalancerBandwidth".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-getBalancerBandwidth".equalsIgnoreCase(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-fetchImage".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-shutdownDatanode".equals(cmd)) {
if ((argv.length != 2) && (argv.length != 3)) {
printUsage(cmd);
return exitCode;
}
} else if ("-getDatanodeInfo".equals(cmd)) {
if (argv.length != 2) {
printUsage(cmd);
return exitCode;
}
} else if ("-triggerBlockReport".equals(cmd)) {
if ((argv.length < 2) || (argv.length > 5)) {
printUsage(cmd);
return exitCode;
}
} else if ("-listOpenFiles".equals(cmd)) {
if ((argv.length > 4)) {
printUsage(cmd);
return exitCode;
}
}
// initialize DFSAdmin
init();
Exception debugException = null;
exitCode = 0;
try {
if ("-report".equals(cmd)) {
report(argv, i);
} else if ("-safemode".equals(cmd)) {
setSafeMode(argv, i);
} else if ("-allowSnapshot".equalsIgnoreCase(cmd)) {
allowSnapshot(argv);
} else if ("-disallowSnapshot".equalsIgnoreCase(cmd)) {
disallowSnapshot(argv);
} else if ("-provisionSnapshotTrash".equalsIgnoreCase(cmd)) {
provisionSnapshotTrash(argv);
} else if ("-saveNamespace".equals(cmd)) {
exitCode = saveNamespace(argv);
} else if ("-rollEdits".equals(cmd)) {
exitCode = rollEdits();
} else if ("-restoreFailedStorage".equals(cmd)) {
exitCode = restoreFailedStorage(argv[i]);
} else if ("-refreshNodes".equals(cmd)) {
exitCode = refreshNodes();
} else if ("-finalizeUpgrade".equals(cmd)) {
exitCode = finalizeUpgrade();
} else if (RollingUpgradeCommand.matches(cmd)) {
exitCode = RollingUpgradeCommand.run(getDFS(), argv, i);
} else if ("-upgrade".equals(cmd)) {
exitCode = upgrade(argv[i]);
} else if ("-metasave".equals(cmd)) {
exitCode = metaSave(argv, i);
} else if (ClearQuotaCommand.matches(cmd)) {
exitCode = new ClearQuotaCommand(argv, i, getConf()).runAll();
} else if (SetQuotaCommand.matches(cmd)) {
exitCode = new SetQuotaCommand(argv, i, getConf()).runAll();
} else if (ClearSpaceQuotaCommand.matches(cmd)) {
exitCode = new ClearSpaceQuotaCommand(argv, i, getConf()).runAll();
} else if (SetSpaceQuotaCommand.matches(cmd)) {
exitCode = new SetSpaceQuotaCommand(argv, i, getConf()).runAll();
} else if ("-refreshServiceAcl".equals(cmd)) {
exitCode = refreshServiceAcl();
} else if ("-refreshUserToGroupsMappings".equals(cmd)) {
exitCode = refreshUserToGroupsMappings();
} else if ("-refreshSuperUserGroupsConfiguration".equals(cmd)) {
exitCode = refreshSuperUserGroupsConfiguration();
} else if ("-refreshCallQueue".equals(cmd)) {
exitCode = refreshCallQueue();
} else if ("-refresh".equals(cmd)) {
exitCode = genericRefresh(argv, i);
} else if ("-printTopology".equals(cmd)) {
exitCode = printTopology();
} else if ("-refreshNamenodes".equals(cmd)) {
exitCode = refreshNamenodes(argv, i);
} else if ("-getVolumeReport".equals(cmd)) {
exitCode = getVolumeReport(argv, i);
} else if ("-deleteBlockPool".equals(cmd)) {
exitCode = deleteBlockPool(argv, i);
} else if ("-setBalancerBandwidth".equals(cmd)) {
exitCode = setBalancerBandwidth(argv, i);
} else if ("-getBalancerBandwidth".equals(cmd)) {
exitCode = getBalancerBandwidth(argv, i);
} else if ("-fetchImage".equals(cmd)) {
exitCode = fetchImage(argv, i);
} else if ("-shutdownDatanode".equals(cmd)) {
exitCode = shutdownDatanode(argv, i);
} else if ("-evictWriters".equals(cmd)) {
exitCode = evictWriters(argv, i);
} else if ("-getDatanodeInfo".equals(cmd)) {
exitCode = getDatanodeInfo(argv, i);
} else if ("-reconfig".equals(cmd)) {
exitCode = reconfig(argv, i);
} else if ("-triggerBlockReport".equals(cmd)) {
exitCode = triggerBlockReport(argv);
} else if ("-listOpenFiles".equals(cmd)) {
exitCode = listOpenFiles(argv);
} else if ("-help".equals(cmd)) {
if (i < argv.length) {
printHelp(argv[i]);
} else {
printHelp("");
}
} else {
exitCode = -1;
System.err.println(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (IllegalArgumentException arge) {
debugException = arge;
exitCode = -1;
System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage());
printUsage(cmd);
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error message, ignore the stack trace.
exitCode = -1;
debugException = e;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
System.err.println(cmd.substring(1) + ": "
+ content[0]);
} catch (Exception ex) {
System.err.println(cmd.substring(1) + ": "
+ ex.getLocalizedMessage());
debugException = ex;
}
} catch (Exception e) {
exitCode = -1;
debugException = e;
System.err.println(cmd.substring(1) + ": "
+ e.getLocalizedMessage());
}
if (LOG.isDebugEnabled() && debugException != null) {
LOG.debug("Exception encountered:", debugException);
}
return exitCode;
}
|
@Test(timeout = 30000)
public void testPrintTopologyWithStatus() throws Exception {
redirectStream();
final Configuration dfsConf = new HdfsConfiguration();
final File baseDir = new File(
PathUtils.getTestDir(getClass()),
GenericTestUtils.getMethodName());
dfsConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
final int numDn = 4;
final String[] racks = {
"/d1/r1", "/d1/r2",
"/d2/r1", "/d2/r2"};
try (MiniDFSCluster miniCluster = new MiniDFSCluster.Builder(dfsConf)
.numDataNodes(numDn).racks(racks).build()) {
miniCluster.waitActive();
assertEquals(numDn, miniCluster.getDataNodes().size());
DatanodeManager dm = miniCluster.getNameNode().getNamesystem().
getBlockManager().getDatanodeManager();
DatanodeDescriptor maintenanceNode = dm.getDatanode(
miniCluster.getDataNodes().get(1).getDatanodeId());
maintenanceNode.setInMaintenance();
DatanodeDescriptor demissionNode = dm.getDatanode(
miniCluster.getDataNodes().get(2).getDatanodeId());
demissionNode.setDecommissioned();
final DFSAdmin dfsAdmin = new DFSAdmin(dfsConf);
resetStream();
final int ret = ToolRunner.run(dfsAdmin, new String[] {"-printTopology"});
/* collect outputs */
final List<String> outs = Lists.newArrayList();
scanIntoList(out, outs);
/* verify results */
assertEquals(0, ret);
assertTrue(outs.get(1).contains(DatanodeInfo.AdminStates.NORMAL.toString()));
assertTrue(outs.get(4).contains(DatanodeInfo.AdminStates.IN_MAINTENANCE.toString()));
assertTrue(outs.get(7).contains(DatanodeInfo.AdminStates.DECOMMISSIONED.toString()));
assertTrue(outs.get(10).contains(DatanodeInfo.AdminStates.NORMAL.toString()));
}
}
|
@Override
public final int readInt() throws EOFException {
final int i = readInt(pos);
pos += INT_SIZE_IN_BYTES;
return i;
}
|
@Test
public void testReadIntPosition() throws Exception {
int readInt = in.readInt(2);
int theInt = Bits.readInt(INIT_DATA, 2, byteOrder == BIG_ENDIAN);
assertEquals(theInt, readInt);
}
|
@Override
public Mono<Void> withoutFallback(final ServerWebExchange exchange, final Throwable throwable) {
Object error;
if (throwable instanceof DegradeException) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.SERVICE_RESULT_ERROR);
} else if (throwable instanceof FlowException) {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.TOO_MANY_REQUESTS);
} else if (throwable instanceof BlockException) {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.SENTINEL_BLOCK_ERROR);
} else if (throwable instanceof SentinelPlugin.SentinelFallbackException) {
return exchange.getAttribute(Constants.RESPONSE_MONO);
} else {
return Mono.error(throwable);
}
return WebFluxResultUtils.result(exchange, error);
}
|
@Test
public void testDegradeException() {
StepVerifier.create(fallbackHandler.withoutFallback(exchange, new DegradeException("Sentinel"))).expectSubscription().verifyComplete();
}
|
public static String format(String json) {
final StringBuilder result = new StringBuilder();
Character wrapChar = null;
boolean isEscapeMode = false;
int length = json.length();
int number = 0;
char key;
for (int i = 0; i < length; i++) {
key = json.charAt(i);
if (CharUtil.DOUBLE_QUOTES == key || CharUtil.SINGLE_QUOTE == key) {
if (null == wrapChar) {
//字符串模式开始
wrapChar = key;
} else if (wrapChar.equals(key)) {
if (isEscapeMode) {
//字符串模式下,遇到结束符号,也同时结束转义
isEscapeMode = false;
}
//字符串包装结束
wrapChar = null;
}
if ((i > 1) && (json.charAt(i - 1) == CharUtil.COLON)) {
result.append(CharUtil.SPACE);
}
result.append(key);
continue;
}
if (CharUtil.BACKSLASH == key) {
if (null != wrapChar) {
//字符串模式下转义有效
isEscapeMode = !isEscapeMode;
result.append(key);
continue;
} else {
result.append(key);
}
}
if (null != wrapChar) {
//字符串模式
result.append(key);
continue;
}
//如果当前字符是前方括号、前花括号做如下处理:
if ((key == CharUtil.BRACKET_START) || (key == CharUtil.DELIM_START)) {
//如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
if ((i > 1) && (json.charAt(i - 1) == CharUtil.COLON)) {
result.append(NEW_LINE);
result.append(indent(number));
}
result.append(key);
//前方括号、前花括号,的后面必须换行。打印:换行。
result.append(NEW_LINE);
//每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
number++;
result.append(indent(number));
continue;
}
// 3、如果当前字符是后方括号、后花括号做如下处理:
if ((key == CharUtil.BRACKET_END) || (key == CharUtil.DELIM_END)) {
// (1)后方括号、后花括号,的前面必须换行。打印:换行。
result.append(NEW_LINE);
// (2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
number--;
result.append(indent(number));
// (3)打印:当前字符。
result.append(key);
// (4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
// if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
// result.append(NEW_LINE);
// }
// (5)继续下一次循环。
continue;
}
// 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
if ((key == ',')) {
result.append(key);
result.append(NEW_LINE);
result.append(indent(number));
continue;
}
if ((i > 1) && (json.charAt(i - 1) == CharUtil.COLON)) {
result.append(CharUtil.SPACE);
}
// 5、打印:当前字符。
result.append(key);
}
return result.toString();
}
|
@Test
public void formatTest() {
String json = "{'age':23,'aihao':['pashan','movies'],'name':{'firstName':'zhang','lastName':'san','aihao':['pashan','movies','name':{'firstName':'zhang','lastName':'san','aihao':['pashan','movies']}]}}";
String result = JSONStrFormatter.format(json);
assertNotNull(result);
}
|
@Override
public double entropy() {
return entropy;
}
|
@Test
public void testEntropy() {
System.out.println("entropy");
BinomialDistribution instance = new BinomialDistribution(100, 0.3);
instance.rand();
assertEquals( 2.9412, instance.entropy(), 1E-4);
}
|
public static PTransformMatcher classEqualTo(Class<? extends PTransform> clazz) {
return new EqualClassPTransformMatcher(clazz);
}
|
@Test
public void classEqualToDoesNotMatchSubclass() {
class MyPTransform extends PTransform<PCollection<KV<String, Integer>>, PCollection<Integer>> {
@Override
public PCollection<Integer> expand(PCollection<KV<String, Integer>> input) {
return PCollection.createPrimitiveOutputInternal(
input.getPipeline(), input.getWindowingStrategy(), input.isBounded(), VarIntCoder.of());
}
}
PTransformMatcher matcher = PTransformMatchers.classEqualTo(MyPTransform.class);
MyPTransform subclass = new MyPTransform() {};
assertThat(subclass.getClass(), not(Matchers.<Class<?>>equalTo(MyPTransform.class)));
assertThat(subclass, instanceOf(MyPTransform.class));
AppliedPTransform<?, ?, ?> application = getAppliedTransform(subclass);
assertThat(matcher.matches(application), is(false));
}
|
public boolean hasRequiredCoordinatorSidecars()
{
if (currentCoordinatorSidecarCount > 1) {
throw new PrestoException(TOO_MANY_SIDECARS,
format("Expected a single active coordinator sidecar. Found %s active coordinator sidecars", currentCoordinatorSidecarCount));
}
return currentCoordinatorSidecarCount == 1;
}
|
@Test
public void testHasRequiredCoordinatorSidecars()
throws InterruptedException
{
assertFalse(monitor.hasRequiredCoordinatorSidecars());
for (int i = numCoordinatorSidecars.get(); i < DESIRED_COORDINATOR_SIDECAR_COUNT; i++) {
addCoordinatorSidecar(nodeManager);
}
assertTrue(monitor.hasRequiredCoordinatorSidecars());
}
|
@Override
public double getStdDev() {
// two-pass algorithm for variance, avoids numeric overflow
if (values.length <= 1) {
return 0;
}
final double mean = getMean();
double sum = 0;
for (long value : values) {
final double diff = value - mean;
sum += diff * diff;
}
final double variance = sum / (values.length - 1);
return Math.sqrt(variance);
}
|
@Test
public void calculatesTheStdDev() {
assertThat(snapshot.getStdDev())
.isEqualTo(1.5811, offset(0.0001));
}
|
@Override
public double read() {
return gaugeSource.read();
}
|
@Test
public void whenCreatedForDynamicDoubleMetricWithExtractedValue() {
SomeObject someObject = new SomeObject();
someObject.doubleField = 41.65D;
metricsRegistry.registerDynamicMetricsProvider(someObject);
DoubleGauge doubleGauge = metricsRegistry.newDoubleGauge("foo.doubleField");
// needed to collect dynamic metrics and update the gauge created from them
metricsRegistry.collect(mock(MetricsCollector.class));
assertEquals(41.65D, doubleGauge.read(), 10E-6);
someObject.doubleField = 42.65D;
assertEquals(42.65D, doubleGauge.read(), 10E-6);
}
|
static Set<Integer> getIndicesOfUpNodes(ClusterState clusterState, NodeType type) {
int nodeCount = clusterState.getNodeCount(type);
Set<Integer> nodesBeingUp = new HashSet<>();
for (int i = 0; i < nodeCount; ++i) {
Node node = new Node(type, i);
NodeState nodeState = clusterState.getNodeState(node);
State state = nodeState.getState();
if (state == State.UP || state == State.INITIALIZING ||
state == State.RETIRED || state == State.MAINTENANCE) {
nodesBeingUp.add(i);
}
}
return nodesBeingUp;
}
|
@Test
void testIndicesOfUpNodes() {
when(clusterState.getNodeCount(NodeType.DISTRIBUTOR)).thenReturn(7);
NodeState nodeState = mock(NodeState.class);
when(nodeState.getState()).
thenReturn(State.MAINTENANCE). // 0
thenReturn(State.RETIRED). // 1
thenReturn(State.INITIALIZING). // 2
thenReturn(State.DOWN).
thenReturn(State.STOPPING).
thenReturn(State.UNKNOWN).
thenReturn(State.UP); // 6
when(clusterState.getNodeState(any())).thenReturn(nodeState);
Set<Integer> indices = ClusterStateView.getIndicesOfUpNodes(clusterState, NodeType.DISTRIBUTOR);
assertEquals(4, indices.size());
assert(indices.contains(0));
assert(indices.contains(1));
assert(indices.contains(2));
assert(indices.contains(6));
}
|
@Override
public ListenableFuture<?> execute(Rollback statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.getTransactionId().isPresent()) {
throw new PrestoException(NOT_IN_TRANSACTION, "No transaction in progress");
}
TransactionId transactionId = session.getTransactionId().get();
stateMachine.clearTransactionId();
transactionManager.asyncAbort(transactionId);
return immediateFuture(null);
}
|
@Test
public void testUnknownTransactionRollback()
{
TransactionManager transactionManager = createTestTransactionManager();
Session session = sessionBuilder()
.setTransactionId(TransactionId.create()) // Use a random transaction ID that is unknown to the system
.build();
QueryStateMachine stateMachine = createQueryStateMachine("ROLLBACK", session, true, transactionManager, executor, metadata);
RollbackTask rollbackTask = new RollbackTask();
getFutureValue(rollbackTask.execute(new Rollback(), transactionManager, metadata, new AllowAllAccessControl(), stateMachine, emptyList()));
assertTrue(stateMachine.getQueryInfo(Optional.empty()).isClearTransactionId()); // Still issue clear signal
assertFalse(stateMachine.getQueryInfo(Optional.empty()).getStartedTransactionId().isPresent());
assertTrue(transactionManager.getAllTransactionInfos().isEmpty());
}
|
public Mono<Table<String, TopicPartition, Long>> listConsumerGroupOffsets(List<String> consumerGroups,
// all partitions if null passed
@Nullable List<TopicPartition> partitions) {
Function<Collection<String>, Mono<Map<String, Map<TopicPartition, OffsetAndMetadata>>>> call =
groups -> toMono(
client.listConsumerGroupOffsets(
groups.stream()
.collect(Collectors.toMap(
g -> g,
g -> new ListConsumerGroupOffsetsSpec().topicPartitions(partitions)
))).all()
);
Mono<Map<String, Map<TopicPartition, OffsetAndMetadata>>> merged = partitionCalls(
consumerGroups,
25,
4,
call,
mapMerger()
);
return merged.map(map -> {
var table = ImmutableTable.<String, TopicPartition, Long>builder();
map.forEach((g, tpOffsets) -> tpOffsets.forEach((tp, offset) -> {
if (offset != null) {
// offset will be null for partitions that don't have committed offset for this group
table.put(g, tp, offset.offset());
}
}));
return table.build();
});
}
|
@Test
void testListConsumerGroupOffsets() throws Exception {
String topic = UUID.randomUUID().toString();
String anotherTopic = UUID.randomUUID().toString();
createTopics(new NewTopic(topic, 2, (short) 1), new NewTopic(anotherTopic, 1, (short) 1));
fillTopic(topic, 10);
Function<String, KafkaConsumer<String, String>> consumerSupplier = groupName -> {
Properties p = new Properties();
p.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
p.setProperty(ConsumerConfig.GROUP_ID_CONFIG, groupName);
p.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
p.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
p.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
p.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
return new KafkaConsumer<String, String>(p);
};
String fullyPolledConsumer = UUID.randomUUID().toString();
try (KafkaConsumer<String, String> c = consumerSupplier.apply(fullyPolledConsumer)) {
c.subscribe(List.of(topic));
int polled = 0;
while (polled < 10) {
polled += c.poll(Duration.ofMillis(50)).count();
}
c.commitSync();
}
String polled1MsgConsumer = UUID.randomUUID().toString();
try (KafkaConsumer<String, String> c = consumerSupplier.apply(polled1MsgConsumer)) {
c.subscribe(List.of(topic));
c.poll(Duration.ofMillis(100));
c.commitSync(Map.of(tp(topic, 0), new OffsetAndMetadata(1)));
}
String noCommitConsumer = UUID.randomUUID().toString();
try (KafkaConsumer<String, String> c = consumerSupplier.apply(noCommitConsumer)) {
c.subscribe(List.of(topic));
c.poll(Duration.ofMillis(100));
}
Map<TopicPartition, ListOffsetsResultInfo> endOffsets = adminClient.listOffsets(Map.of(
tp(topic, 0), OffsetSpec.latest(),
tp(topic, 1), OffsetSpec.latest())).all().get();
StepVerifier.create(
reactiveAdminClient.listConsumerGroupOffsets(
List.of(fullyPolledConsumer, polled1MsgConsumer, noCommitConsumer),
List.of(
tp(topic, 0),
tp(topic, 1),
tp(anotherTopic, 0))
)
).assertNext(table -> {
assertThat(table.row(polled1MsgConsumer))
.containsEntry(tp(topic, 0), 1L)
.hasSize(1);
assertThat(table.row(noCommitConsumer))
.isEmpty();
assertThat(table.row(fullyPolledConsumer))
.containsEntry(tp(topic, 0), endOffsets.get(tp(topic, 0)).offset())
.containsEntry(tp(topic, 1), endOffsets.get(tp(topic, 1)).offset())
.hasSize(2);
})
.verifyComplete();
}
|
@Operation(summary = "delete", description = "DELETE_WORKFLOWS_INSTANCE_NOTES")
@Parameters({
@Parameter(name = "workflowInstanceId", description = "WORKFLOW_INSTANCE_ID", schema = @Schema(implementation = Integer.class, example = "123456", required = true))
})
@DeleteMapping(value = "/{workflowInstanceId}")
@ResponseStatus(HttpStatus.OK)
@ApiException(Status.DELETE_PROCESS_DEFINE_BY_CODE_ERROR)
public Result<Void> deleteWorkflowInstance(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@PathVariable("workflowInstanceId") Integer workflowInstanceId) {
processInstanceService.deleteProcessInstanceById(loginUser, workflowInstanceId);
return Result.success();
}
|
@Test
public void testDeleteWorkflowInstanceById() {
User loginUser = getLoginUser();
Mockito.doNothing().when(processInstanceService).deleteProcessInstanceById(any(), eq(1));
Result result = workflowInstanceV2Controller.deleteWorkflowInstance(loginUser, 1);
Assertions.assertTrue(result.isSuccess());
}
|
public static String convertToLowerUnderscore(String identifierName) {
return splitToLowercaseTerms(identifierName).stream().collect(Collectors.joining("_"));
}
|
@Test
public void convertToLowerUnderscore_separatesTerms_fromCamelCase() {
String identifierName = "camelCase";
String lowerUnderscore = NamingConventions.convertToLowerUnderscore(identifierName);
assertThat(lowerUnderscore).isEqualTo("camel_case");
}
|
Map<Class, Object> getSerializers() {
return serializers;
}
|
@Test
public void testLoad_withDefaultConstructor() {
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setClassName("com.hazelcast.internal.serialization.impl.TestSerializerHook$TestSerializer");
serializerConfig.setTypeClassName("com.hazelcast.internal.serialization.impl.SampleIdentifiedDataSerializable");
SerializationConfig serializationConfig = getConfig().getSerializationConfig();
serializationConfig.addSerializerConfig(serializerConfig);
SerializerHookLoader hook = new SerializerHookLoader(serializationConfig, classLoader);
Map<Class, Object> serializers = hook.getSerializers();
assertNotNull(serializers);
}
|
@Override
public List<TransferItem> list(final Session<?> session, final Path directory, final Local local,
final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Children for %s", directory));
}
final Set<TransferItem> children = new HashSet<>();
final Find finder = new CachingFindFeature(session, cache, session.getFeature(Find.class, new DefaultFindFeature(session)));
if(finder.find(directory)) {
children.addAll(download.list(session, directory, local, listener));
}
if(local.exists()) {
children.addAll(upload.list(session, directory, local, listener));
}
return new ArrayList<>(children);
}
|
@Test
public void testChildrenRemoteAndLocalExist() throws Exception {
final NullLocal directory = new NullLocal(System.getProperty("java.io.tmpdir"), "t") {
@Override
public AttributedList<Local> list() {
final AttributedList<Local> list = new AttributedList<>();
list.add(new NullLocal(this, "a"));
return list;
}
};
final Path root = new Path("t", EnumSet.of(Path.Type.directory));
final Path remote = new Path(root, "a", EnumSet.of(Path.Type.file));
final NullSession session = new NullSession(new Host(new TestProtocol())) {
@Override
public AttributedList<Path> list(final Path file, final ListProgressListener listener) {
final AttributedList<Path> list = new AttributedList<>();
if(file.equals(root.getParent())) {
list.add(root);
}
else {
list.add(remote);
}
return list;
}
};
new DefaultLocalDirectoryFeature().mkdir(directory);
Transfer t = new SyncTransfer(new Host(new TestProtocol()), new TransferItem(root, directory));
final List<TransferItem> list = t.list(session, root, directory, new DisabledListProgressListener());
assertEquals(1, list.size());
}
|
@Override
public void add(Double value) {
this.min = Math.min(this.min, value);
}
|
@Test
void testAdd() {
DoubleMinimum min = new DoubleMinimum();
min.add(1234.5768);
min.add(9876.5432);
min.add(-987.6543);
min.add(-123.4567);
assertThat(min.getLocalValue()).isCloseTo(-987.6543, within(0.0));
}
|
DecodedJWT verifyJWT(PublicKey publicKey,
String publicKeyAlg,
DecodedJWT jwt) throws AuthenticationException {
if (publicKeyAlg == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new AuthenticationException("PublicKey algorithm cannot be null");
}
Algorithm alg;
try {
switch (publicKeyAlg) {
case ALG_RS256:
alg = Algorithm.RSA256((RSAPublicKey) publicKey, null);
break;
case ALG_RS384:
alg = Algorithm.RSA384((RSAPublicKey) publicKey, null);
break;
case ALG_RS512:
alg = Algorithm.RSA512((RSAPublicKey) publicKey, null);
break;
case ALG_ES256:
alg = Algorithm.ECDSA256((ECPublicKey) publicKey, null);
break;
case ALG_ES384:
alg = Algorithm.ECDSA384((ECPublicKey) publicKey, null);
break;
case ALG_ES512:
alg = Algorithm.ECDSA512((ECPublicKey) publicKey, null);
break;
default:
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new AuthenticationException("Unsupported algorithm: " + publicKeyAlg);
}
} catch (ClassCastException e) {
incrementFailureMetric(AuthenticationExceptionCode.ALGORITHM_MISMATCH);
throw new AuthenticationException("Expected PublicKey alg [" + publicKeyAlg + "] does match actual alg.");
}
// We verify issuer when retrieving the PublicKey, so it is not verified here.
// The claim presence requirements are based on https://openid.net/specs/openid-connect-basic-1_0.html#IDToken
Verification verifierBuilder = JWT.require(alg)
.acceptLeeway(acceptedTimeLeewaySeconds)
.withAnyOfAudience(allowedAudiences)
.withClaimPresence(RegisteredClaims.ISSUED_AT)
.withClaimPresence(RegisteredClaims.EXPIRES_AT)
.withClaimPresence(RegisteredClaims.NOT_BEFORE)
.withClaimPresence(RegisteredClaims.SUBJECT);
if (isRoleClaimNotSubject) {
verifierBuilder = verifierBuilder.withClaimPresence(roleClaim);
}
JWTVerifier verifier = verifierBuilder.build();
try {
return verifier.verify(jwt);
} catch (TokenExpiredException e) {
incrementFailureMetric(AuthenticationExceptionCode.EXPIRED_JWT);
throw new AuthenticationException("JWT expired: " + e.getMessage());
} catch (SignatureVerificationException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_VERIFYING_JWT_SIGNATURE);
throw new AuthenticationException("JWT signature verification exception: " + e.getMessage());
} catch (InvalidClaimException e) {
incrementFailureMetric(AuthenticationExceptionCode.INVALID_JWT_CLAIM);
throw new AuthenticationException("JWT contains invalid claim: " + e.getMessage());
} catch (AlgorithmMismatchException e) {
incrementFailureMetric(AuthenticationExceptionCode.ALGORITHM_MISMATCH);
throw new AuthenticationException("JWT algorithm does not match Public Key algorithm: " + e.getMessage());
} catch (JWTDecodeException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
throw new AuthenticationException("Error while decoding JWT: " + e.getMessage());
} catch (JWTVerificationException | IllegalArgumentException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_VERIFYING_JWT);
throw new AuthenticationException("JWT verification failed: " + e.getMessage());
}
}
|
@Test
public void ensureFutureIATFails() throws Exception {
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
DefaultJwtBuilder defaultJwtBuilder = new DefaultJwtBuilder();
addValidMandatoryClaims(defaultJwtBuilder, basicProviderAudience);
// Override the exp set in the above method
defaultJwtBuilder.setIssuedAt(Date.from(Instant.now().plusSeconds(60)));
defaultJwtBuilder.signWith(keyPair.getPrivate());
DecodedJWT jwt = JWT.decode(defaultJwtBuilder.compact());
Assert.assertThrows(AuthenticationException.class,
() -> basicProvider.verifyJWT(keyPair.getPublic(), SignatureAlgorithm.RS256.getValue(), jwt));
}
|
protected String concat( String path, String name ) {
return FilenameUtils.concat( path, name );
}
|
@Test
public void testConcat() {
assertEquals( "/home/devuser/files/food.txt",
testInstance.concat( "/home/devuser/files", "food.txt" ).replace('\\', '/') );
assertEquals( "/home/devuser/files/food.txt",
testInstance.concat( "/home/devuser/files/", "food.txt" ).replace('\\', '/') );
assertEquals( "/home/devuser/files/food.txt",
testInstance.concat( "/", "home/devuser/files/food.txt" ).replace('\\', '/') );
assertEquals( "/",
testInstance.concat( "/", "" ).replace('\\', '/') );
assertEquals( "/home/devuser/files/",
testInstance.concat( "/home/devuser/files", "" ).replace('\\', '/') );
}
|
@SuppressWarnings("unchecked")
public static <R extends Tuple> TupleSummaryAggregator<R> create(TupleTypeInfoBase<?> inType) {
Aggregator[] columnAggregators = new Aggregator[inType.getArity()];
for (int field = 0; field < inType.getArity(); field++) {
Class clazz = inType.getTypeAt(field).getTypeClass();
columnAggregators[field] = SummaryAggregatorFactory.create(clazz);
}
return new TupleSummaryAggregator<>(columnAggregators);
}
|
@Test
void testCreate() {
// supported primitive types
assertThat(SummaryAggregatorFactory.create(String.class).getClass())
.isEqualTo(StringSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Short.class).getClass())
.isEqualTo(ShortSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Integer.class).getClass())
.isEqualTo(IntegerSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Long.class).getClass())
.isEqualTo(LongSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Float.class).getClass())
.isEqualTo(FloatSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Double.class).getClass())
.isEqualTo(DoubleSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(Boolean.class).getClass())
.isEqualTo(BooleanSummaryAggregator.class);
// supported value types
assertThat(SummaryAggregatorFactory.create(StringValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.StringValueSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(ShortValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.ShortValueSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(IntValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.IntegerValueSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(LongValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.LongValueSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(FloatValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.FloatValueSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(DoubleValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.DoubleValueSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(BooleanValue.class).getClass())
.isEqualTo(ValueSummaryAggregator.BooleanValueSummaryAggregator.class);
// some not well supported types - these fallback to ObjectSummaryAggregator
assertThat(SummaryAggregatorFactory.create(Object.class).getClass())
.isEqualTo(ObjectSummaryAggregator.class);
assertThat(SummaryAggregatorFactory.create(List.class).getClass())
.isEqualTo(ObjectSummaryAggregator.class);
}
|
@Override
public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext)
{
doEvaluateDisruptContext(request, requestContext);
return _client.sendRequest(request, requestContext);
}
|
@Test
public void testSendRequest13()
{
when(_controller.getDisruptContext(any(String.class))).thenReturn(_disrupt);
_client.sendRequest(_multiplexed, _context, _multiplexedCallback);
verify(_underlying, times(1)).sendRequest(eq(_multiplexed), eq(_context), eq(_multiplexedCallback));
verify(_context, times(1)).putLocalAttr(eq(DISRUPT_CONTEXT_KEY), eq(_disrupt));
verify(_context, times(1)).putLocalAttr(eq(DISRUPT_SOURCE_KEY), any(String.class));
}
|
public String getInstanceStatus() {
String serviceId = RegisterContext.INSTANCE.getClientInfo().getServiceId();
String group = nacosRegisterConfig.getGroup();
try {
NamingService namingService = nacosServiceManager.getNamingService();
List<Instance> instances = namingService.getAllInstances(serviceId, group);
for (Instance serviceInstance : instances) {
if (serviceInstance.getIp().equalsIgnoreCase(RegisterContext.INSTANCE.getClientInfo().getIp())
&& serviceInstance.getPort() == RegisterContext.INSTANCE.getClientInfo().getPort()) {
return serviceInstance.isEnabled() ? "UP" : "DOWN";
}
}
} catch (NacosException e) {
LOGGER.log(Level.SEVERE, String.format(Locale.ENGLISH, "getInstanceStatus failed,serviceId={%s}",
serviceId), e);
}
return STATUS_UNKNOW;
}
|
@Test
public void testGetInstanceStatus() throws NacosException {
mockNamingService();
Assert.assertNotNull(nacosClient.getInstanceStatus());
}
|
public static FlowGraph of(GraphCluster graph) throws IllegalVariableEvaluationException {
return FlowGraph.builder()
.nodes(GraphUtils.nodes(graph))
.edges(GraphUtils.edges(graph))
.clusters(GraphUtils.clusters(graph, new ArrayList<>())
.stream()
.map(g -> new Cluster(g.getKey(), g.getKey().getGraph()
.nodes()
.stream()
.map(AbstractGraph::getUid)
.toList(),
g.getValue(),
g.getKey().getRoot().getUid(),
g.getKey().getEnd().getUid()
))
.toList()
)
.build();
}
|
@Test
void dynamicIdSubflow() throws IllegalVariableEvaluationException, TimeoutException {
Flow flow = this.parse("flows/valids/task-flow-dynamic.yaml").toBuilder().revision(1).build();
IllegalArgumentException illegalArgumentException = Assertions.assertThrows(IllegalArgumentException.class, () -> graphService.flowGraph(flow, Collections.singletonList("root.launch")));
assertThat(illegalArgumentException.getMessage(), is("Can't expand subflow task 'launch' because namespace and/or flowId contains dynamic values. This can only be viewed on an execution."));
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-flow-dynamic", 1, (f, e) -> Map.of(
"namespace", f.getNamespace(),
"flowId", "switch"
));
FlowGraph flowGraph = graphService.flowGraph(flow, Collections.singletonList("root.launch"), execution);
assertThat(flowGraph.getNodes().size(), is(20));
assertThat(flowGraph.getEdges().size(), is(23));
assertThat(flowGraph.getClusters().size(), is(4));
}
|
public static void createTrustedCertificatesVolumeMounts(List<VolumeMount> volumeMountList, List<CertSecretSource> trustedCertificates, String tlsVolumeMountPath) {
createTrustedCertificatesVolumeMounts(volumeMountList, trustedCertificates, tlsVolumeMountPath, null);
}
|
@Test
public void testTrustedCertificatesVolumeMounts() {
CertSecretSource cert1 = new CertSecretSourceBuilder()
.withSecretName("first-certificate")
.withCertificate("ca.crt")
.build();
CertSecretSource cert2 = new CertSecretSourceBuilder()
.withSecretName("second-certificate")
.withCertificate("tls.crt")
.build();
CertSecretSource cert3 = new CertSecretSourceBuilder()
.withSecretName("first-certificate")
.withCertificate("ca2.crt")
.build();
List<VolumeMount> mounts = new ArrayList<>();
CertUtils.createTrustedCertificatesVolumeMounts(mounts, List.of(cert1, cert2, cert3), "/my/path/");
assertThat(mounts.size(), is(2));
assertThat(mounts.get(0).getName(), is("first-certificate"));
assertThat(mounts.get(0).getMountPath(), is("/my/path/first-certificate"));
assertThat(mounts.get(1).getName(), is("second-certificate"));
assertThat(mounts.get(1).getMountPath(), is("/my/path/second-certificate"));
}
|
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, TimeLimiter timeLimiter, String methodName)
throws Throwable {
TimeLimiterTransformer<?> timeLimiterTransformer = TimeLimiterTransformer.of(timeLimiter);
Object returnValue = proceedingJoinPoint.proceed();
return executeRxJava2Aspect(timeLimiterTransformer, returnValue, methodName);
}
|
@Test
public void shouldThrowIllegalArgumentExceptionWithNotRxJava2Type() throws Throwable{
TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn("NOT RXJAVA2 TYPE");
try {
rxJava2TimeLimiterAspectExt.handle(proceedingJoinPoint, timeLimiter, "testMethod");
fail("exception missed");
} catch (Throwable e) {
assertThat(e).isInstanceOf(IllegalReturnTypeException.class)
.hasMessage(
"java.lang.String testMethod has unsupported by @TimeLimiter return type. RxJava2 expects Flowable/Single/...");
}
}
|
@Override
public boolean shouldClientThrottle(short version) {
return version >= 4;
}
|
@Test
public void testShouldThrottle() {
for (short version : ApiKeys.OFFSET_FETCH.allVersions()) {
if (version < 8) {
OffsetFetchResponse response = new OffsetFetchResponse(throttleTimeMs, Errors.NONE, partitionDataMap);
if (version >= 4) {
assertTrue(response.shouldClientThrottle(version));
} else {
assertFalse(response.shouldClientThrottle(version));
}
} else {
OffsetFetchResponse response = new OffsetFetchResponse(
throttleTimeMs,
Collections.singletonMap(groupOne, Errors.NOT_COORDINATOR),
Collections.singletonMap(groupOne, partitionDataMap));
assertTrue(response.shouldClientThrottle(version));
}
}
}
|
@Override
protected void onStateExpiry(UUID sessionId, TransportProtos.SessionInfoProto sessionInfo) {
log.debug("Session with id: [{}] has expired due to last activity time.", sessionId);
SessionMetaData expiredSession = sessions.remove(sessionId);
if (expiredSession != null) {
deregisterSession(sessionInfo);
process(sessionInfo, SESSION_EVENT_MSG_CLOSED, null);
expiredSession.getListener().onRemoteSessionCloseCommand(sessionId, SESSION_EXPIRED_NOTIFICATION_PROTO);
}
}
|
@Test
void givenSessionExists_whenOnStateExpiryCalled_thenShouldPerformExpirationActions() {
// GIVEN
TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder()
.setSessionIdMSB(SESSION_ID.getMostSignificantBits())
.setSessionIdLSB(SESSION_ID.getLeastSignificantBits())
.build();
SessionMsgListener listenerMock = mock(SessionMsgListener.class);
sessions.put(SESSION_ID, new SessionMetaData(sessionInfo, TransportProtos.SessionType.ASYNC, listenerMock));
doCallRealMethod().when(transportServiceMock).onStateExpiry(SESSION_ID, sessionInfo);
// WHEN
transportServiceMock.onStateExpiry(SESSION_ID, sessionInfo);
// THEN
assertThat(sessions.containsKey(SESSION_ID)).isFalse();
verify(transportServiceMock).deregisterSession(sessionInfo);
verify(transportServiceMock).process(sessionInfo, SESSION_EVENT_MSG_CLOSED, null);
verify(listenerMock).onRemoteSessionCloseCommand(SESSION_ID, SESSION_EXPIRED_NOTIFICATION_PROTO);
}
|
@Override
public ExecuteContext onThrow(ExecuteContext context) {
if (shouldHandle(context)) {
ThreadLocalUtils.removeRequestTag();
}
return context;
}
|
@Test
public void testOnThrow() {
ThreadLocalUtils.addRequestTag(Collections.singletonMap("bar", Collections.singletonList("foo")));
Assert.assertNotNull(ThreadLocalUtils.getRequestTag());
// Test the on Throw method to verify whether the thread variable is released
interceptor.onThrow(context);
Assert.assertNull(ThreadLocalUtils.getRequestTag());
}
|
public void generateAcknowledgementPayload(
MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode)
throws MllpAcknowledgementGenerationException {
generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null);
}
|
@Test
public void testGenerateAcknowledgementPayload() throws Exception {
MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
hl7util.generateAcknowledgementPayload(mllpSocketBuffer, TEST_MESSAGE.getBytes(), "AA");
String actual = mllpSocketBuffer.toString();
assertThat(actual, startsWith(EXPECTED_ACKNOWLEDGEMENT_PAYLOAD_START));
assertThat(actual, endsWith(EXPECTED_ACKNOWLEDGEMENT_PAYLOAD_END));
}
|
public static boolean isAllInventoryTasksFinished(final Collection<PipelineTask> inventoryTasks) {
if (inventoryTasks.isEmpty()) {
log.warn("inventoryTasks is empty");
}
return inventoryTasks.stream().allMatch(each -> each.getTaskProgress().getPosition() instanceof IngestFinishedPosition);
}
|
@Test
void assertAllInventoryTasksAreFinishedWhenCollectionIsEmpty() {
assertTrue(PipelineJobProgressDetector.isAllInventoryTasksFinished(Collections.emptyList()));
}
|
@Udf
public String lcase(
@UdfParameter(description = "The string to lower-case") final String input) {
if (input == null) {
return null;
}
return input.toLowerCase();
}
|
@Test
public void shouldReturnNullForNullInput() {
final String result = udf.lcase(null);
assertThat(result, is(nullValue()));
}
|
CompletionStage<HttpServer> serve(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route()
.handler(BodyHandler.create())
.failureHandler(this::handleFailure);
router.route(HttpMethod.GET, "/catalog/model/:kind/:name")
.produces(MIME_TYPE_JSON)
.blockingHandler(this::handleCatalogModel);
router.route(HttpMethod.GET, "/catalog/capability/:name")
.produces(MIME_TYPE_JSON)
.blockingHandler(this::handleCatalogCapability);
router.route(HttpMethod.POST, "/inspect/:location")
.produces(MIME_TYPE_JSON)
.blockingHandler(this::handleInspect);
return server.requestHandler(router).listen(port, host).toCompletionStage();
}
|
@Test
public void testInspect() throws Exception {
Agent agent = cmd();
agent.port = 0;
Vertx vertx = Vertx.vertx();
HttpServer server = agent.serve(vertx).toCompletableFuture().get();
try {
int port = server.actualPort();
String route = """
- route:
from:
uri: 'timer:tick'
steps:
- to: 'log:info'
""";
RestAssured.given()
.baseUri("http://localhost")
.port(port)
.body(route)
.when()
.post("/inspect/routes.yaml")
.then()
.statusCode(200)
.body("resources.components", hasItems("timer", "log"));
} finally {
server.close();
vertx.close();
}
}
|
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not found.", groupId));
}
if (group == null) {
ClassicGroup classicGroup = new ClassicGroup(logContext, groupId, ClassicGroupState.EMPTY, time, metrics);
groups.put(groupId, classicGroup);
metrics.onClassicGroupStateTransition(null, classicGroup.currentState());
return classicGroup;
} else {
if (group.type() == CLASSIC) {
return (ClassicGroup) group;
} else {
// We don't support upgrading/downgrading between protocols at the moment so
// we throw an exception if a group exists with the wrong type.
throw new GroupIdNotFoundException(String.format("Group %s is not a classic group.",
groupId));
}
}
}
|
@Test
public void testGenerateRecordsOnNewClassicGroup() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
JoinGroupRequestData request = new GroupMetadataManagerTestContext.JoinGroupRequestBuilder()
.withGroupId("group-id")
.withMemberId(UNKNOWN_MEMBER_ID)
.withDefaultProtocolTypeAndProtocols()
.build();
GroupMetadataManagerTestContext.JoinResult joinResult = context.sendClassicGroupJoin(request, true);
assertTrue(joinResult.joinFuture.isDone());
assertEquals(Errors.MEMBER_ID_REQUIRED.code(), joinResult.joinFuture.get().errorCode());
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup("group-id", false);
assertEquals(
Collections.singletonList(GroupCoordinatorRecordHelpers.newEmptyGroupMetadataRecord(group, MetadataVersion.latestTesting())),
joinResult.records
);
}
|
public static String getViewGroupTypeByReflect(View view) {
Class<?> compatClass;
String viewType = SnapCache.getInstance().getCanonicalName(view.getClass());
compatClass = ReflectUtil.getClassByName("android.support.v7.widget.CardView");
if (compatClass != null && compatClass.isInstance(view)) {
return SAViewUtils.getViewType(viewType, "CardView");
}
compatClass = ReflectUtil.getClassByName("androidx.cardview.widget.CardView");
if (compatClass != null && compatClass.isInstance(view)) {
return SAViewUtils.getViewType(viewType, "CardView");
}
compatClass = ReflectUtil.getClassByName("android.support.design.widget.NavigationView");
if (compatClass != null && compatClass.isInstance(view)) {
return SAViewUtils.getViewType(viewType, "NavigationView");
}
compatClass = ReflectUtil.getClassByName("com.google.android.material.navigation.NavigationView");
if (compatClass != null && compatClass.isInstance(view)) {
return SAViewUtils.getViewType(viewType, "NavigationView");
}
return viewType;
}
|
@Test
public void getViewGroupTypeByReflect() {
LinearLayout linearLayout = new LinearLayout(mApplication);
Assert.assertEquals("android.widget.LinearLayout",
SAViewUtils.getViewGroupTypeByReflect(linearLayout));
}
|
public Struct(Schema schema) {
if (schema.type() != Schema.Type.STRUCT)
throw new DataException("Not a struct schema: " + schema);
this.schema = schema;
this.values = new Object[schema.fields().size()];
}
|
@Test
public void testMissingFieldValidation() {
// Required int8 field
Schema schema = SchemaBuilder.struct().field("field", REQUIRED_FIELD_SCHEMA).build();
Struct struct = new Struct(schema);
assertThrows(DataException.class, struct::validate);
}
|
@Override
public boolean mayHaveMergesPending(String bucketSpace, int contentNodeIndex) {
if (!stats.hasUpdatesFromAllDistributors()) {
return true;
}
ContentNodeStats nodeStats = stats.getStats().getNodeStats(contentNodeIndex);
if (nodeStats != null) {
ContentNodeStats.BucketSpaceStats bucketSpaceStats = nodeStats.getBucketSpace(bucketSpace);
return (bucketSpaceStats != null &&
bucketSpaceStats.mayHaveBucketsPending(minMergeCompletionRatio));
}
return true;
}
|
@Test
void unknown_content_node_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 2));
}
|
@Override
public UrlPattern doGetPattern() {
return UrlPattern.create("/" + SamlValidationWs.SAML_VALIDATION_CONTROLLER + "/" + VALIDATION_INIT_KEY);
}
|
@Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern().matches("/saml/validation_init")).isTrue();
assertThat(underTest.doGetPattern().matches("/api/saml")).isFalse();
assertThat(underTest.doGetPattern().matches("/api/saml/validation_init")).isFalse();
assertThat(underTest.doGetPattern().matches("/saml/validation_init2")).isFalse();
}
|
public RunConfiguration getRunConfigurationByType( String type ) {
RunConfigurationProvider runConfigurationProvider = getProvider( type );
if ( runConfigurationProvider != null ) {
return runConfigurationProvider.getConfiguration();
}
return null;
}
|
@Test
public void testGetRunConfigurationByType() {
DefaultRunConfiguration defaultRunConfiguration =
(DefaultRunConfiguration) executionConfigurationManager.getRunConfigurationByType( DefaultRunConfiguration.TYPE );
assertNotNull( defaultRunConfiguration );
}
|
ObjectFactory loadObjectFactory() {
Class<? extends ObjectFactory> objectFactoryClass = options.getObjectFactoryClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class, classLoader);
if (objectFactoryClass == null) {
return loadSingleObjectFactoryOrDefault(loader);
}
return loadSelectedObjectFactory(loader, objectFactoryClass);
}
|
@Test
void shouldLoadSelectedObjectFactoryService() {
Options options = () -> DefaultObjectFactory.class;
ObjectFactoryServiceLoader loader = new ObjectFactoryServiceLoader(
ObjectFactoryServiceLoaderTest.class::getClassLoader,
options);
assertThat(loader.loadObjectFactory(), instanceOf(DefaultObjectFactory.class));
}
|
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
}
|
@Test
void shouldLoadFromSvnPartial() throws Exception {
String buildXmlPartial =
"<svn url=\"https://foo.bar\" username=\"cruise\" password=\"password\" materialName=\"https___foo.bar\"/>";
MaterialConfig materialConfig = xmlLoader.fromXmlPartial(buildXmlPartial, SvnMaterialConfig.class);
MaterialConfig svnMaterial = MaterialConfigsMother.svnMaterialConfig("https://foo.bar", null, "cruise", "password", false, null);
assertThat(materialConfig).isEqualTo(svnMaterial);
}
|
public QueryParseResult parse(String sql, @Nonnull SqlSecurityContext ssc) {
try {
return parse0(sql, ssc);
} catch (QueryException e) {
throw e;
} catch (Exception e) {
String message;
// Check particular type of exception which causes typical long multiline error messages.
if (e instanceof SqlParseException && e.getCause() instanceof ParseException) {
message = trimMessage(e.getMessage());
} else {
message = e.getMessage();
}
throw QueryException.error(SqlErrorCode.PARSING, message, e);
}
}
|
@Test
public void test_trailingSemicolon() {
given(sqlValidator.validate(isA(SqlNode.class))).willReturn(validatedNode);
parser.parse("SELECT * FROM t;");
parser.parse("SELECT * FROM t;;");
}
|
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported schema type: " + type.baseType());
}
return (S) handler.apply(visitor, type);
}
|
@Test
public void shouldThrowOnUnknownType() {
// Given:
final SqlBaseType unknownType = mock(SqlBaseType.class, "bob");
final SqlType type = mock(SqlType.class);
when(type.baseType()).thenReturn(unknownType);
// When:
final UnsupportedOperationException e = assertThrows(
UnsupportedOperationException.class,
() -> SqlTypeWalker.visit(type, visitor)
);
// Then:
assertThat(e.getMessage(), containsString(
"Unsupported schema type: bob"
));
}
|
static List<Locale> negotiatePreferredLocales(String headerValue) {
if (headerValue == null || headerValue.isBlank()) {
headerValue = DEFAULT_LOCALE.toLanguageTag();
}
try {
var languageRanges = Locale.LanguageRange.parse(headerValue);
return Locale.filter(languageRanges, supportedLocales);
} catch (IllegalArgumentException e) {
throw new ValidationException(new Message("error.unparsableHeader"));
}
}
|
@Test
void test_negotiatePreferredLocales_brokenThrowsValidationException() {
assertThrows(ValidationException.class, () -> LocaleUtils.negotiatePreferredLocales("x21;"));
}
|
@InterfaceAudience.Private
@VisibleForTesting
int scanActiveLogs() throws IOException {
long startTime = Time.monotonicNow();
// Store the Last Processed Time and Offset
if (recoveryEnabled && appIdLogMap.size() > 0) {
try (FSDataOutputStream checkPointStream = fs.create(checkpointFile, true)) {
storeLogFiles(appIdLogMap.values(), checkPointStream);
} catch (Exception e) {
LOG.warn("Failed to checkpoint the summarylog files", e);
}
}
int logsToScanCount = scanActiveLogs(activeRootPath);
metrics.addActiveLogDirScanTime(Time.monotonicNow() - startTime);
return logsToScanCount;
}
|
@Test
void testScanActiveLogsWithInvalidFile() throws Exception {
Path invalidFile = new Path(testActiveDirPath, "invalidfile");
try {
if (!fs.exists(invalidFile)) {
fs.createNewFile(invalidFile);
}
store.scanActiveLogs();
} catch (StackOverflowError error) {
fail("EntityLogScanner crashed with StackOverflowError");
} finally {
if (fs.exists(invalidFile)) {
fs.delete(invalidFile, false);
}
}
}
|
@PostMapping("/token")
@PermitAll
@Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@Parameters({
@Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"),
@Parameter(name = "code", description = "授权范围", example = "userinfo.read"),
@Parameter(name = "redirect_uri", description = "重定向 URI", example = "https://www.iocoder.cn"),
@Parameter(name = "state", description = "状态", example = "1"),
@Parameter(name = "username", example = "tudou"),
@Parameter(name = "password", example = "cai"), // 多个使用空格分隔
@Parameter(name = "scope", example = "user_info"),
@Parameter(name = "refresh_token", example = "123424233"),
})
public CommonResult<OAuth2OpenAccessTokenRespVO> postAccessToken(HttpServletRequest request,
@RequestParam("grant_type") String grantType,
@RequestParam(value = "code", required = false) String code, // 授权码模式
@RequestParam(value = "redirect_uri", required = false) String redirectUri, // 授权码模式
@RequestParam(value = "state", required = false) String state, // 授权码模式
@RequestParam(value = "username", required = false) String username, // 密码模式
@RequestParam(value = "password", required = false) String password, // 密码模式
@RequestParam(value = "scope", required = false) String scope, // 密码模式
@RequestParam(value = "refresh_token", required = false) String refreshToken) { // 刷新模式
List<String> scopes = OAuth2Utils.buildScopes(scope);
// 1.1 校验授权类型
OAuth2GrantTypeEnum grantTypeEnum = OAuth2GrantTypeEnum.getByGrantType(grantType);
if (grantTypeEnum == null) {
throw exception0(BAD_REQUEST.getCode(), StrUtil.format("未知授权类型({})", grantType));
}
if (grantTypeEnum == OAuth2GrantTypeEnum.IMPLICIT) {
throw exception0(BAD_REQUEST.getCode(), "Token 接口不支持 implicit 授权模式");
}
// 1.2 校验客户端
String[] clientIdAndSecret = obtainBasicAuthorization(request);
OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1],
grantType, scopes, redirectUri);
// 2. 根据授权模式,获取访问令牌
OAuth2AccessTokenDO accessTokenDO;
switch (grantTypeEnum) {
case AUTHORIZATION_CODE:
accessTokenDO = oauth2GrantService.grantAuthorizationCodeForAccessToken(client.getClientId(), code, redirectUri, state);
break;
case PASSWORD:
accessTokenDO = oauth2GrantService.grantPassword(username, password, client.getClientId(), scopes);
break;
case CLIENT_CREDENTIALS:
accessTokenDO = oauth2GrantService.grantClientCredentials(client.getClientId(), scopes);
break;
case REFRESH_TOKEN:
accessTokenDO = oauth2GrantService.grantRefreshToken(refreshToken, client.getClientId());
break;
default:
throw new IllegalArgumentException("未知授权类型:" + grantType);
}
Assert.notNull(accessTokenDO, "访问令牌不能为空"); // 防御性检查
return success(OAuth2OpenConvert.INSTANCE.convert(accessTokenDO));
}
|
@Test
public void testPostAccessToken_password() {
// 准备参数
String granType = OAuth2GrantTypeEnum.PASSWORD.getGrantType();
String username = randomString();
String password = randomString();
String scope = "write read";
HttpServletRequest request = mockRequest("test_client_id", "test_client_secret");
// mock 方法(client)
OAuth2ClientDO client = randomPojo(OAuth2ClientDO.class).setClientId("test_client_id");
when(oauth2ClientService.validOAuthClientFromCache(eq("test_client_id"), eq("test_client_secret"),
eq(granType), eq(Lists.newArrayList("write", "read")), isNull())).thenReturn(client);
// mock 方法(访问令牌)
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class)
.setExpiresTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 30000L, ChronoUnit.MILLIS));
when(oauth2GrantService.grantPassword(eq(username), eq(password), eq("test_client_id"),
eq(Lists.newArrayList("write", "read")))).thenReturn(accessTokenDO);
// 调用
CommonResult<OAuth2OpenAccessTokenRespVO> result = oauth2OpenController.postAccessToken(request, granType,
null, null, null, username, password, scope, null);
// 断言
assertEquals(0, result.getCode());
assertPojoEquals(accessTokenDO, result.getData());
assertTrue(ObjectUtils.equalsAny(result.getData().getExpiresIn(), 29L, 30L)); // 执行过程会过去几毫秒
}
|
public String getStringForDisplay() {
if (isEmpty()) {
return "";
}
StringBuilder display = new StringBuilder();
for (IgnoredFiles ignoredFiles : this) {
display.append(ignoredFiles.getPattern()).append(",");
}
return display.substring(0, display.length() - 1);
}
|
@Test
public void shouldConcatenateIgnoredFilesWithCommaWhenDisplaying() {
Filter filter = new Filter(new IgnoredFiles("/foo/**.*"), new IgnoredFiles("/another/**.*"), new IgnoredFiles("bar"));
assertThat(filter.getStringForDisplay(), is("/foo/**.*,/another/**.*,bar"));
}
|
public CompletableFuture<Void> subscribeAsync(String topicName, boolean createTopicIfDoesNotExist) {
TopicName topicNameInstance = getTopicName(topicName);
if (topicNameInstance == null) {
return FutureUtil.failedFuture(
new PulsarClientException.AlreadyClosedException("Topic name not valid"));
}
String fullTopicName = topicNameInstance.toString();
if (consumers.containsKey(fullTopicName)
|| partitionedTopics.containsKey(topicNameInstance.getPartitionedTopicName())) {
return FutureUtil.failedFuture(
new PulsarClientException.AlreadyClosedException("Already subscribed to " + topicName));
}
if (getState() == State.Closing || getState() == State.Closed) {
return FutureUtil.failedFuture(
new PulsarClientException.AlreadyClosedException("Topics Consumer was already closed"));
}
CompletableFuture<Void> subscribeResult = new CompletableFuture<>();
client.getPartitionedTopicMetadata(topicName, true, false)
.thenAccept(metadata -> subscribeTopicPartitions(subscribeResult, fullTopicName, metadata.partitions,
createTopicIfDoesNotExist))
.exceptionally(ex1 -> {
log.warn("[{}] Failed to get partitioned topic metadata: {}", fullTopicName, ex1.getMessage());
subscribeResult.completeExceptionally(ex1);
return null;
});
return subscribeResult;
}
|
@Test(timeOut = 10000)
public void testParallelSubscribeAsync() throws Exception {
String topicName = "parallel-subscribe-async-topic";
MultiTopicsConsumerImpl<byte[]> impl = createMultiTopicsConsumer();
CompletableFuture<Void> firstInvocation = impl.subscribeAsync(topicName, true);
Thread.sleep(5); // less than completionDelayMillis
CompletableFuture<Void> secondInvocation = impl.subscribeAsync(topicName, true);
firstInvocation.get(); // does not throw
Throwable t = expectThrows(ExecutionException.class, secondInvocation::get);
Throwable cause = t.getCause();
assertEquals(cause.getClass(), PulsarClientException.class);
assertTrue(cause.getMessage().endsWith("Topic is already being subscribed for in other thread."));
}
|
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credentials);
LOGGER.fine("AWS ECS DescribeTasks found the following addresses: %s", taskAddresses);
}
if (!taskAddresses.isEmpty()) {
return awsEc2Api.describeNetworkInterfaces(taskAddresses, credentials);
} else if (DiscoveryMode.Client == awsConfig.getDiscoveryMode() && !awsConfig.anyOfEcsPropertiesConfigured()) {
LOGGER.fine("No tasks found in ECS cluster: '%s'. Trying AWS EC2 Discovery.", cluster);
return awsEc2Api.describeInstances(credentials);
}
return emptyMap();
}
|
@Test
public void doNotGetEcsAddressesIfEc2Configured() {
// given
AwsConfig awsConfig = AwsConfig.builder()
.setSecurityGroupName("my-security-group")
.setDiscoveryMode(DiscoveryMode.Client)
.build();
awsEcsClient = new AwsEcsClient(CLUSTER, awsConfig, awsEcsApi, awsEc2Api, awsMetadataApi, awsCredentialsProvider);
Map<String, String> expectedResult = singletonMap("123.12.1.0", "1.4.6.2");
given(awsEc2Api.describeInstances(CREDENTIALS)).willReturn(expectedResult);
// when
Map<String, String> result = awsEcsClient.getAddresses();
// then
then(awsEcsApi).should(never()).listTaskPrivateAddresses(CLUSTER, CREDENTIALS);
assertEquals(expectedResult, result);
}
|
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
}
|
@Test(expected = EncodingException.class)
public void testParsingNoSubType() {
MediaType.fromString("something");
}
|
String getFileName(double lat, double lon) {
int lonInt = getMinLonForTile(lon);
int latInt = getMinLatForTile(lat);
return toLowerCase(getLatString(latInt) + getNorthString(latInt) + getLonString(lonInt) + getEastString(lonInt) + FILE_NAME_END);
}
|
@Disabled
@Test
public void testGetEleVerticalBorder() {
// Border between the tiles 50n000e and 70n000e
assertEquals("50n000e_20101117_gmted_mea075", instance.getFileName(69.999999, 19.493));
assertEquals(268, instance.getEle(69.999999, 19.5249), precision);
assertEquals("70n000e_20101117_gmted_mea075", instance.getFileName(70, 19.493));
assertEquals(298, instance.getEle(70, 19.5249), precision);
// Second location at the border
assertEquals("50n000e_20101117_gmted_mea075", instance.getFileName(69.999999, 19.236));
assertEquals(245, instance.getEle(69.999999, 19.236), precision);
assertEquals("70n000e_20101117_gmted_mea075", instance.getFileName(70, 19.236));
assertEquals(241, instance.getEle(70, 19.236), precision);
}
|
@Override
public boolean containsValue(Object value) {
return false;
}
|
@Test
public void testContainsValue() {
assertFalse(NULL_QUERY_CACHE.containsValue(1));
}
|
public void removeUpTo(long item1, long item2) {
lock.writeLock().lock();
try {
Map.Entry<Long, RoaringBitmap> firstEntry = map.firstEntry();
while (firstEntry != null && firstEntry.getKey() <= item1) {
if (firstEntry.getKey() < item1) {
map.remove(firstEntry.getKey(), firstEntry.getValue());
} else {
RoaringBitmap bitSet = firstEntry.getValue();
if (bitSet != null) {
bitSet.remove(0, item2);
if (bitSet.isEmpty()) {
map.remove(firstEntry.getKey(), bitSet);
}
}
break;
}
firstEntry = map.firstEntry();
}
} finally {
lock.writeLock().unlock();
}
}
|
@Test
public void testRemoveUpTo() {
ConcurrentBitmapSortedLongPairSet set = new ConcurrentBitmapSortedLongPairSet();
set.removeUpTo(0, 1000);
set.removeUpTo(10, 10000);
assertTrue(set.isEmpty());
set.add(1, 0);
int items = 10;
for (int i = 0; i < items; i++) {
set.add(1, i);
}
set.removeUpTo(1, 5);
assertFalse(set.isEmpty());
assertEquals(set.size(), 5);
for (int i = 5; i < items; i++) {
assertTrue(set.contains(1, i));
}
set.removeUpTo(2, 0);
assertTrue(set.isEmpty());
}
|
void startup(@Observes StartupEvent event) {
if (jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) {
backgroundJobServerInstance.get().start();
}
if (jobRunrBuildTimeConfiguration.dashboard().enabled()) {
dashboardWebServerInstance.get().start();
}
}
|
@Test
void jobRunrStarterStartsBackgroundJobServerIfConfigured() {
when(backgroundJobServerConfiguration.enabled()).thenReturn(true);
jobRunrStarter.startup(new StartupEvent());
verify(backgroundJobServer).start();
}
|
public static Object coerceValue(DMNType requiredType, Object valueToCoerce) {
return (requiredType != null && valueToCoerce != null) ? actualCoerceValue(requiredType, valueToCoerce) :
valueToCoerce;
}
|
@Test
void coerceValueCollectionToArrayNotConverted() {
Object item = "TESTED_OBJECT";
Object value = Collections.singleton(item);
DMNType requiredType = new SimpleTypeImpl("http://www.omg.org/spec/DMN/20180521/FEEL/",
"string",
null,
true,
null,
null,
null,
BuiltInType.STRING);
Object retrieved = CoerceUtil.coerceValue(requiredType, value);
assertNotNull(retrieved);
assertEquals(value, retrieved);
value = "TESTED_OBJECT";
requiredType = new SimpleTypeImpl("http://www.omg.org/spec/DMN/20180521/FEEL/",
"string",
null,
false,
null,
null,
null,
BuiltInType.STRING);
retrieved = CoerceUtil.coerceValue(requiredType, value);
assertNotNull(retrieved);
assertEquals(value, retrieved);
requiredType = null;
retrieved = CoerceUtil.coerceValue(requiredType, value);
assertEquals(value, retrieved);
value = null;
requiredType = new SimpleTypeImpl("http://www.omg.org/spec/DMN/20180521/FEEL/",
"string",
null,
false,
null,
null,
null,
BuiltInType.STRING);
retrieved = CoerceUtil.coerceValue(requiredType, value);
assertEquals(value, retrieved);
}
|
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {
return new String[] {};
}
int sepLen = separator.length();
int from = 0;
int end = string.length() - sepLen + 1;
for ( int i = from; i < end; i += sepLen ) {
if ( string.substring( i, i + sepLen ).equalsIgnoreCase( separator ) ) {
// OK, we found a separator, the string to add to the list
// is [from, i[
list.add( nullToEmpty( string.substring( from, i ) ) );
from = i + sepLen;
}
}
// Wait, if the string didn't end with a separator, we still have information at the end of the string...
// In our example that would be "d"...
if ( from + sepLen <= string.length() ) {
list.add( nullToEmpty( string.substring( from, string.length() ) ) );
}
return list.toArray( new String[list.size()] );
}
|
@Test
public void testSplitStringWithEscaping() {
String[] result;
result = Const.splitString( null, null, null );
assertNull( result );
result = Const.splitString( "Hello, world", null, null );
assertNotNull( result );
assertEquals( result.length, 1 );
assertEquals( result[0], "Hello, world" );
result = Const.splitString( "Hello\\, world,Hello\\, planet,Hello\\, 3rd rock", ',', true );
assertNotNull( result );
assertEquals( result.length, 3 );
assertEquals( result[0], "Hello\\, world" );
assertEquals( result[1], "Hello\\, planet" );
assertEquals( result[2], "Hello\\, 3rd rock" );
}
|
public static String[] getParentFirstLoaderPatterns(ReadableConfig config) {
List<String> base = config.get(ALWAYS_PARENT_FIRST_LOADER_PATTERNS);
List<String> append = config.get(ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL);
return mergeListsToArray(base, append);
}
|
@Test
void testGetParentFirstLoaderPatterns() {
testParentFirst(
CoreOptions::getParentFirstLoaderPatterns,
CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS,
CoreOptions.ALWAYS_PARENT_FIRST_LOADER_PATTERNS_ADDITIONAL);
}
|
@Transactional
@Cacheable(CACHE_DATABASE_SEARCH)
@CacheEvict(value = CACHE_AVERAGE_REVIEW_RATING, allEntries = true)
public SearchHits<ExtensionSearch> search(ISearchService.Options options) {
// grab all extensions
var matchingExtensions = repositories.findAllActiveExtensions();
// no extensions in the database
if (matchingExtensions.isEmpty()) {
return new SearchHitsImpl<>(0,TotalHitsRelation.OFF, 0f, null, null, Collections.emptyList(), null, null);
}
// exlude namespaces
if(options.namespacesToExclude != null) {
for(var namespaceToExclude : options.namespacesToExclude) {
matchingExtensions = matchingExtensions.filter(extension -> !extension.getNamespace().getName().equals(namespaceToExclude));
}
}
// filter target platform
if(TargetPlatform.isValid(options.targetPlatform)) {
matchingExtensions = matchingExtensions.filter(extension -> extension.getVersions().stream().anyMatch(ev -> ev.getTargetPlatform().equals(options.targetPlatform)));
}
// filter category
if (options.category != null) {
matchingExtensions = matchingExtensions.filter(extension -> {
var latest = repositories.findLatestVersion(extension, null, false, true);
return latest.getCategories().stream().anyMatch(category -> category.equalsIgnoreCase(options.category));
});
}
// filter text
if (options.queryString != null) {
matchingExtensions = matchingExtensions.filter(extension -> {
var latest = repositories.findLatestVersion(extension, null, false, true);
return extension.getName().toLowerCase().contains(options.queryString.toLowerCase())
|| extension.getNamespace().getName().contains(options.queryString.toLowerCase())
|| (latest.getDescription() != null && latest.getDescription()
.toLowerCase().contains(options.queryString.toLowerCase()))
|| (latest.getDisplayName() != null && latest.getDisplayName()
.toLowerCase().contains(options.queryString.toLowerCase()));
});
}
// need to perform the sortBy ()
// 'relevance' | 'timestamp' | 'rating' | 'downloadCount';
Stream<ExtensionSearch> searchEntries;
if("relevance".equals(options.sortBy) || "rating".equals(options.sortBy)) {
var searchStats = new SearchStats(repositories);
searchEntries = matchingExtensions.stream().map(extension -> relevanceService.toSearchEntry(extension, searchStats));
} else {
searchEntries = matchingExtensions.stream().map(extension -> {
var latest = repositories.findLatestVersion(extension, null, false, true);
var targetPlatforms = repositories.findExtensionTargetPlatforms(extension);
return extension.toSearch(latest, targetPlatforms);
});
}
var comparators = new HashMap<>(Map.of(
"relevance", new RelevanceComparator(),
"timestamp", new TimestampComparator(),
"rating", new RatingComparator(),
"downloadCount", new DownloadedCountComparator()
));
var comparator = comparators.get(options.sortBy);
if(comparator != null) {
searchEntries = searchEntries.sorted(comparator);
}
var sortedExtensions = searchEntries.collect(Collectors.toList());
// need to do sortOrder
// 'asc' | 'desc';
if ("desc".equals(options.sortOrder)) {
// reverse the order
Collections.reverse(sortedExtensions);
}
// Paging
var totalHits = sortedExtensions.size();
var endIndex = Math.min(sortedExtensions.size(), options.requestedOffset + options.requestedSize);
var startIndex = Math.min(endIndex, options.requestedOffset);
sortedExtensions = sortedExtensions.subList(startIndex, endIndex);
List<SearchHit<ExtensionSearch>> searchHits;
if (sortedExtensions.isEmpty()) {
searchHits = Collections.emptyList();
} else {
// client is interested only in the extension IDs
searchHits = sortedExtensions.stream().map(extensionSearch -> new SearchHit<>(null, null, null, 0.0f, null, null, null, null, null, null, extensionSearch)).collect(Collectors.toList());
}
return new SearchHitsImpl<>(totalHits, TotalHitsRelation.OFF, 0f, null, null, searchHits, null, null);
}
|
@Test
public void testQueryStringExtensionName() {
var ext1 = mockExtension("yaml", 3.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages"));
var ext2 = mockExtension("java", 4.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages"));
var ext3 = mockExtension("openshift", 4.0, 100, 0, "redhat", List.of("Snippets", "Other"));
var ext4 = mockExtension("foo", 4.0, 100, 0, "bar", List.of("Other"));
Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4)));
var searchOptions = new ISearchService.Options("openshift", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false);
var result = search.search(searchOptions);
// extension name finding
assertThat(result.getTotalHits()).isEqualTo(1);
// Check it found the correct extension
var hits = result.getSearchHits();
assertThat(getIdFromExtensionHits(hits, 0)).isEqualTo(getIdFromExtensionName("openshift"));
}
|
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchingFunctionException(arguments);
}
// if none were found (candidate isn't present) try again with implicit casting
candidate = findMatchingCandidate(arguments, true);
if (candidate.isPresent()) {
return candidate.get();
}
throw createNoMatchingFunctionException(arguments);
}
|
@Test
public void shouldMatchGenericMethodWithMultipleIdenticalGenerics() {
// Given:
final GenericType generic = GenericType.of("A");
givenFunctions(
function(EXPECTED, -1, generic, generic)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(INTEGER), SqlArgument.of(INTEGER)));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
}
|
@Override
protected List<DavResource> list(final Path file) throws IOException {
return session.getClient().list(new DAVPathEncoder().encode(file), 0, Collections.unmodifiableSet(Stream.concat(
Stream.of(GUID_QN), ALL_ACL_QN.stream()
).collect(Collectors.toSet())));
}
|
@Test
public void testFindDirectory() throws Exception {
final Path home = new DefaultHomeFinderService(session).find();
final Path test = new CteraDirectoryFeature(session).mkdir(new Path(home,
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus());
final DAVAttributesFinderFeature f = new CteraAttributesFinderFeature(session);
final PathAttributes attributes = f.find(test);
assertTrue(attributes.getAcl().asList().stream().anyMatch(userAndRole -> userAndRole.getRole().equals(READPERMISSION)));
assertTrue(attributes.getAcl().asList().stream().anyMatch(userAndRole -> userAndRole.getRole().equals(WRITEPERMISSION)));
assertTrue(attributes.getAcl().asList().stream().anyMatch(userAndRole -> userAndRole.getRole().equals(CREATEDIRECTORIESPERMISSION)));
assertNotEquals(-1L, attributes.getModificationDate());
assertNotNull(attributes.getETag());
assertNotNull(new CteraListService(session).list(home, new DisabledListProgressListener()).find(new SimplePathPredicate(test)));
assertEquals(attributes, new CteraListService(session).list(home, new DisabledListProgressListener()).find(new SimplePathPredicate(test)).attributes());
// Test wrong type
assertThrows(NotfoundException.class, () -> f.find(new Path(test.getAbsolute(), EnumSet.of(Path.Type.file))));
}
|
public static List<Tab> getTabsFromJson(@Nullable final String tabsJson)
throws InvalidJsonException {
if (tabsJson == null || tabsJson.isEmpty()) {
return getDefaultTabs();
}
final List<Tab> returnTabs = new ArrayList<>();
final JsonObject outerJsonObject;
try {
outerJsonObject = JsonParser.object().from(tabsJson);
if (!outerJsonObject.has(JSON_TABS_ARRAY_KEY)) {
throw new InvalidJsonException("JSON doesn't contain \"" + JSON_TABS_ARRAY_KEY
+ "\" array");
}
final JsonArray tabsArray = outerJsonObject.getArray(JSON_TABS_ARRAY_KEY);
for (final Object o : tabsArray) {
if (!(o instanceof JsonObject)) {
continue;
}
final Tab tab = Tab.from((JsonObject) o);
if (tab != null) {
returnTabs.add(tab);
}
}
} catch (final JsonParserException e) {
throw new InvalidJsonException(e);
}
if (returnTabs.isEmpty()) {
return getDefaultTabs();
}
return returnTabs;
}
|
@Test
public void testInvalidIdRead() throws TabsJsonHelper.InvalidJsonException {
final int blankTabId = Tab.Type.BLANK.getTabId();
final String emptyTabsJson = "{\"" + JSON_TABS_ARRAY_KEY + "\":["
+ "{\"" + JSON_TAB_ID_KEY + "\":" + blankTabId + "},"
+ "{\"" + JSON_TAB_ID_KEY + "\":" + 12345678 + "}" + "]}";
final List<Tab> items = TabsJsonHelper.getTabsFromJson(emptyTabsJson);
assertEquals("Should ignore the tab with invalid id", 1, items.size());
assertEquals(blankTabId, items.get(0).getTabId());
}
|
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
if ( group != null && !group.equals( " " ) && !group.equals( "." ) && !group.equals( "," ) ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "group", "not a valid one, can only be one of: dot ('.'), comma (','), space (' ') "));
}
if ( decimal != null ) {
if (!decimal.equals( "." ) && !decimal.equals( "," )) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "decimal", "not a valid one, can only be one of: dot ('.'), comma (',') "));
} else if (group != null && decimal.equals( group )) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "decimal", "cannot be the same as parameter 'group' "));
}
}
if ( group != null ) {
from = from.replaceAll( "\\" + group, "" );
}
if ( decimal != null ) {
from = from.replaceAll( "\\" + decimal, "." );
}
BigDecimal result = NumberEvalHelper.getBigDecimalOrNull(from );
if( from != null && result == null ) {
// conversion failed
return FEELFnResult.ofError( new InvalidParametersEvent(Severity.ERROR, "unable to calculate final number result" ) );
} else {
return FEELFnResult.ofResult( result );
}
}
|
@Test
void invokeNumberWithGroupCharSpace() {
FunctionTestUtil.assertResult(numberFunction.invoke("9 876", " ", null), BigDecimal.valueOf(9876));
FunctionTestUtil.assertResult(numberFunction.invoke("9 876 000", " ", null), BigDecimal.valueOf(9876000));
}
|
public int readInt2() {
return byteBuf.readUnsignedShortLE();
}
|
@Test
void assertReadInt2() {
when(byteBuf.readUnsignedShortLE()).thenReturn(1);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt2(), is(1));
}
|
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(distance, edgeState, reverse);
if (Double.isInfinite(seconds)) return Double.POSITIVE_INFINITY;
// add penalty at start/stop/via points
if (edgeState.get(EdgeIteratorState.UNFAVORED_EDGE)) seconds += headingPenaltySeconds;
double distanceCosts = distance * distanceInfluence;
if (Double.isInfinite(distanceCosts)) return Double.POSITIVE_INFINITY;
return seconds / priority + distanceCosts;
}
|
@Test
public void testPrivateTag() {
DecimalEncodedValue carSpeedEnc = new DecimalEncodedValueImpl("car_speed", 5, 5, false);
DecimalEncodedValue bikeSpeedEnc = new DecimalEncodedValueImpl("bike_speed", 4, 2, false);
EncodingManager em = EncodingManager.start().add(carSpeedEnc).add(bikeSpeedEnc).add(RoadAccess.create()).build();
BaseGraph graph = new BaseGraph.Builder(em).create();
EdgeIteratorState edge = graph.edge(0, 1).setDistance(1000);
edge.set(carSpeedEnc, 60);
edge.set(bikeSpeedEnc, 18);
EnumEncodedValue<RoadAccess> roadAccessEnc = em.getEnumEncodedValue(RoadAccess.KEY, RoadAccess.class);
CustomModel customModel = createSpeedCustomModel(carSpeedEnc)
.addToPriority(If("road_access == PRIVATE", MULTIPLY, ".1"));
Weighting weighting = CustomModelParser.createWeighting(em, NO_TURN_COST_PROVIDER, customModel);
customModel = createSpeedCustomModel(bikeSpeedEnc)
.addToPriority(If("road_access == PRIVATE", MULTIPLY, "0.8333"));
Weighting bikeWeighting = CustomModelParser.createWeighting(em, NO_TURN_COST_PROVIDER, customModel);
ReaderWay way = new ReaderWay(1);
way.setTag("highway", "secondary");
edge.set(roadAccessEnc, RoadAccess.YES);
assertEquals(60, weighting.calcEdgeWeight(edge, false), .01);
assertEquals(200, bikeWeighting.calcEdgeWeight(edge, false), .01);
edge.set(roadAccessEnc, RoadAccess.PRIVATE);
assertEquals(600, weighting.calcEdgeWeight(edge, false), .01);
// private should influence bike only slightly
assertEquals(240, bikeWeighting.calcEdgeWeight(edge, false), .01);
}
|
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return DatasourceConfiguration.isEmbeddedStorage() && !EnvUtil.getStandaloneMode();
}
|
@Test
void testMatches() {
MockedStatic<DatasourceConfiguration> propertyUtilMockedStatic = Mockito.mockStatic(DatasourceConfiguration.class);
MockedStatic<EnvUtil> envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class);
propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true);
envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true);
assertFalse(conditionDistributedEmbedStorage.matches(context, metadata));
Mockito.when(DatasourceConfiguration.isEmbeddedStorage()).thenReturn(true);
Mockito.when(EnvUtil.getStandaloneMode()).thenReturn(false);
propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true);
envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(false);
assertTrue(conditionDistributedEmbedStorage.matches(context, metadata));
propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false);
envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true);
assertFalse(conditionDistributedEmbedStorage.matches(context, metadata));
propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false);
envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(false);
assertFalse(conditionDistributedEmbedStorage.matches(context, metadata));
propertyUtilMockedStatic.close();
envUtilMockedStatic.close();
}
|
public BundleProcessor getProcessor(
BeamFnApi.ProcessBundleDescriptor descriptor,
List<RemoteInputDestination> remoteInputDesinations) {
checkState(
!descriptor.hasStateApiServiceDescriptor(),
"The %s cannot support a %s containing a state %s.",
BundleProcessor.class.getSimpleName(),
BeamFnApi.ProcessBundleDescriptor.class.getSimpleName(),
Endpoints.ApiServiceDescriptor.class.getSimpleName());
return getProcessor(descriptor, remoteInputDesinations, NoOpStateDelegator.INSTANCE);
}
|
@Test
public void handleCleanupWithStateWhenProcessingBundleFails() throws Exception {
RuntimeException testException = new RuntimeException();
BeamFnDataOutboundAggregator mockInputSender = mock(BeamFnDataOutboundAggregator.class);
StateDelegator mockStateDelegator = mock(StateDelegator.class);
StateDelegator.Registration mockStateRegistration = mock(StateDelegator.Registration.class);
when(mockStateDelegator.registerForProcessBundleInstructionId(any(), any()))
.thenReturn(mockStateRegistration);
StateRequestHandler mockStateHandler = mock(StateRequestHandler.class);
when(mockStateHandler.getCacheTokens()).thenReturn(Collections.emptyList());
BundleProgressHandler mockProgressHandler = mock(BundleProgressHandler.class);
CompletableFuture<InstructionResponse> processBundleResponseFuture = new CompletableFuture<>();
when(fnApiControlClient.handle(any(BeamFnApi.InstructionRequest.class)))
.thenReturn(processBundleResponseFuture);
FullWindowedValueCoder<String> coder =
FullWindowedValueCoder.of(StringUtf8Coder.of(), Coder.INSTANCE);
BundleProcessor processor =
sdkHarnessClient.getProcessor(
descriptor,
Collections.singletonList(
RemoteInputDestination.of((FullWindowedValueCoder) coder, SDK_GRPC_READ_TRANSFORM)),
mockStateDelegator);
when(dataService.createOutboundAggregator(any(), anyBoolean())).thenReturn(mockInputSender);
try {
try (RemoteBundle activeBundle =
processor.newBundle(
ImmutableMap.of(
SDK_GRPC_WRITE_TRANSFORM,
RemoteOutputReceiver.of(ByteArrayCoder.of(), mock(FnDataReceiver.class))),
mockStateHandler,
mockProgressHandler)) {
processBundleResponseFuture.completeExceptionally(testException);
}
fail("Exception expected");
} catch (ExecutionException e) {
assertEquals(testException, e.getCause());
verify(mockStateRegistration).abort();
// We expect that we don't register the receiver and the next accept call will raise an error
// making the data service aware of the error.
verify(dataService, never()).unregisterReceiver(any());
assertThrows(
"Inbound observer closed.",
Exception.class,
() -> outputReceiverCaptor.getValue().accept(Elements.getDefaultInstance()));
}
}
|
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if (StringUtils.isBlank(msg)) {
ctx.writeAndFlush(QosProcessHandler.PROMPT);
} else {
CommandContext commandContext = TelnetCommandDecoder.decode(msg);
commandContext.setQosConfiguration(qosConfiguration);
commandContext.setRemote(ctx.channel());
try {
String result = commandExecutor.execute(commandContext);
if (StringUtils.isEquals(QosConstants.CLOSE, result)) {
ctx.writeAndFlush(getByeLabel()).addListener(ChannelFutureListener.CLOSE);
} else {
ctx.writeAndFlush(result + QosConstants.BR_STR + QosProcessHandler.PROMPT);
}
} catch (NoSuchCommandException ex) {
ctx.writeAndFlush(msg + " :no such command");
ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT);
log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not found command " + commandContext, ex);
} catch (PermissionDenyException ex) {
ctx.writeAndFlush(msg + " :permission deny");
ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT);
log.error(
QOS_PERMISSION_DENY_EXCEPTION,
"",
"",
"permission deny to access command " + commandContext,
ex);
} catch (Exception ex) {
ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage());
ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT);
log.error(
QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext got exception " + commandContext, ex);
}
}
}
|
@Test
void testBye() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush("BYE!\n")).thenReturn(future);
handler.channelRead0(context, "quit");
verify(future).addListener(ChannelFutureListener.CLOSE);
}
|
void setReplicas(PartitionReplica[] newReplicas) {
PartitionReplica[] oldReplicas = replicas;
replicas = newReplicas;
onReplicasChange(newReplicas, oldReplicas);
}
|
@Test
public void testSetReplicaAddresses_afterInitialSet() {
replicaOwners[0] = localReplica;
partition.setReplicas(replicaOwners);
partition.setReplicas(replicaOwners);
}
|
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
Num refValue = ref.getValue(index);
final boolean satisfied = refValue.isLessThanOrEqual(upper.getValue(index))
&& refValue.isGreaterThanOrEqual(lower.getValue(index));
traceIsSatisfied(index, satisfied);
return satisfied;
}
|
@Test
public void isSatisfied() {
assertTrue(rule.isSatisfied(0));
assertTrue(rule.isSatisfied(1));
assertTrue(rule.isSatisfied(2));
assertFalse(rule.isSatisfied(3));
assertFalse(rule.isSatisfied(4));
assertTrue(rule.isSatisfied(5));
assertTrue(rule.isSatisfied(6));
assertTrue(rule.isSatisfied(7));
assertFalse(rule.isSatisfied(8));
assertFalse(rule.isSatisfied(9));
}
|
@Override
protected ActivityState<TransportProtos.SessionInfoProto> updateState(UUID sessionId, ActivityState<TransportProtos.SessionInfoProto> state) {
SessionMetaData session = sessions.get(sessionId);
if (session == null) {
return null;
}
state.setMetadata(session.getSessionInfo());
var sessionInfo = state.getMetadata();
if (sessionInfo.getGwSessionIdMSB() == 0L || sessionInfo.getGwSessionIdLSB() == 0L) {
return state;
}
var gwSessionId = new UUID(sessionInfo.getGwSessionIdMSB(), sessionInfo.getGwSessionIdLSB());
SessionMetaData gwSession = sessions.get(gwSessionId);
if (gwSession == null || !gwSession.isOverwriteActivityTime()) {
return state;
}
long lastRecordedTime = state.getLastRecordedTime();
long gwLastRecordedTime = getLastRecordedTime(gwSessionId);
log.debug("Session with id: [{}] has gateway session with id: [{}] with overwrite activity time enabled. " +
"Updating last activity time. Session last recorded time: [{}], gateway session last recorded time: [{}].",
sessionId, gwSessionId, lastRecordedTime, gwLastRecordedTime);
state.setLastRecordedTime(Math.max(lastRecordedTime, gwLastRecordedTime));
return state;
}
|
@Test
void givenSessionDoesNotExist_whenUpdatingActivityState_thenShouldReturnNull() {
// GIVEN
TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder()
.setSessionIdMSB(SESSION_ID.getMostSignificantBits())
.setSessionIdLSB(SESSION_ID.getLeastSignificantBits())
.build();
ActivityState<TransportProtos.SessionInfoProto> state = new ActivityState<>();
state.setLastRecordedTime(123L);
state.setMetadata(sessionInfo);
when(transportServiceMock.updateState(SESSION_ID, state)).thenCallRealMethod();
// WHEN
ActivityState<TransportProtos.SessionInfoProto> updatedState = transportServiceMock.updateState(SESSION_ID, state);
// THEN
assertThat(updatedState).isNull();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.