focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public Block toBlock(Type desiredType)
{
checkArgument(BIGINT.equals(desiredType), "type doesn't match: %s", desiredType);
int numberOfRecords = numberOfRecords();
return new LongArrayBlock(
numberOfRecords,
Optional.ofNullable(nulls),
longs == null ? new long[numberOfRecords] : longs);
} | @Test
public void testReadBlock()
{
PrestoThriftBlock columnsData = longColumn(
new boolean[] {false, true, false, false, false, false, true},
new long[] {2, 0, 1, 3, 8, 4, 0});
Block actual = columnsData.toBlock(BIGINT);
assertBlockEquals(actual, list(2L, null, 1L, 3L, 8L, 4L, null));
} |
public static Collection<PerStepNamespaceMetrics> convert(
String stepName,
Map<MetricName, Long> counters,
Map<MetricName, LockFreeHistogram.Snapshot> histograms,
Map<MetricName, LabeledMetricNameUtils.ParsedMetricName> parsedPerWorkerMetricsCache) {
Map<String, PerStepNamespaceMetrics> metricsByNamespace = new HashMap<>();
for (Entry<MetricName, Long> entry : counters.entrySet()) {
MetricName metricName = entry.getKey();
Optional<MetricValue> metricValue =
convertCounterToMetricValue(metricName, entry.getValue(), parsedPerWorkerMetricsCache);
if (!metricValue.isPresent()) {
continue;
}
PerStepNamespaceMetrics stepNamespaceMetrics =
metricsByNamespace.get(metricName.getNamespace());
if (stepNamespaceMetrics == null) {
stepNamespaceMetrics =
new PerStepNamespaceMetrics()
.setMetricValues(new ArrayList<>())
.setOriginalStep(stepName)
.setMetricsNamespace(metricName.getNamespace());
metricsByNamespace.put(metricName.getNamespace(), stepNamespaceMetrics);
}
stepNamespaceMetrics.getMetricValues().add(metricValue.get());
}
for (Entry<MetricName, LockFreeHistogram.Snapshot> entry : histograms.entrySet()) {
MetricName metricName = entry.getKey();
Optional<MetricValue> metricValue =
convertHistogramToMetricValue(metricName, entry.getValue(), parsedPerWorkerMetricsCache);
if (!metricValue.isPresent()) {
continue;
}
PerStepNamespaceMetrics stepNamespaceMetrics =
metricsByNamespace.get(metricName.getNamespace());
if (stepNamespaceMetrics == null) {
stepNamespaceMetrics =
new PerStepNamespaceMetrics()
.setMetricValues(new ArrayList<>())
.setOriginalStep(stepName)
.setMetricsNamespace(metricName.getNamespace());
metricsByNamespace.put(metricName.getNamespace(), stepNamespaceMetrics);
}
stepNamespaceMetrics.getMetricValues().add(metricValue.get());
}
return metricsByNamespace.values();
} | @Test
public void testConvert_skipInvalidMetricNames() {
Map<MetricName, LabeledMetricNameUtils.ParsedMetricName> parsedMetricNames = new HashMap<>();
Map<MetricName, Long> counters = new HashMap<>();
MetricName invalidName1 = MetricName.named("BigQuerySink", "**");
counters.put(invalidName1, 5L);
Map<MetricName, LockFreeHistogram.Snapshot> histograms = new HashMap<>();
MetricName invalidName2 = MetricName.named("BigQuerySink", "****");
LockFreeHistogram nonEmptyLinearHistogram = new LockFreeHistogram(invalidName2, lienarBuckets);
nonEmptyLinearHistogram.update(-5.0);
histograms.put(invalidName2, nonEmptyLinearHistogram.getSnapshotAndReset().get());
Collection<PerStepNamespaceMetrics> conversionResult =
MetricsToPerStepNamespaceMetricsConverter.convert(
"testStep", counters, histograms, parsedMetricNames);
assertThat(conversionResult.size(), equalTo(0));
assertThat(parsedMetricNames.size(), equalTo(0));
} |
@Override
public ObjectNode encode(KubevirtNode node, CodecContext context) {
checkNotNull(node, "Kubevirt node cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(HOST_NAME, node.hostname())
.put(TYPE, node.type().name())
.put(STATE, node.state().name())
.put(MANAGEMENT_IP, node.managementIp().toString());
// serialize integration bridge config
if (node.intgBridge() != null) {
result.put(INTEGRATION_BRIDGE, node.intgBridge().toString());
}
// serialize tunnel bridge config
if (node.tunBridge() != null) {
result.put(TUNNEL_BRIDGE, node.tunBridge().toString());
}
// serialize data IP only if it presents
if (node.dataIp() != null) {
result.put(DATA_IP, node.dataIp().toString());
}
// serialize physical interfaces, it is valid only if any of physical interface presents
if (node.phyIntfs() != null && !node.phyIntfs().isEmpty()) {
ArrayNode phyIntfs = context.mapper().createArrayNode();
node.phyIntfs().forEach(phyIntf -> {
ObjectNode phyIntfJson =
context.codec(KubevirtPhyInterface.class).encode(phyIntf, context);
phyIntfs.add(phyIntfJson);
});
result.set(PHYSICAL_INTERFACES, phyIntfs);
}
// serialize external bridge if exist
if (node.gatewayBridgeName() != null) {
result.put(GATEWAY_BRIDGE_NAME, node.gatewayBridgeName());
}
return result;
} | @Test
public void testKubevirtComputeNodeEncode() {
KubevirtPhyInterface phyIntf1 = DefaultKubevirtPhyInterface.builder()
.network("mgmtnetwork")
.intf("eth3")
.physBridge(DEVICE_ID_1)
.build();
KubevirtPhyInterface phyIntf2 = DefaultKubevirtPhyInterface.builder()
.network("oamnetwork")
.intf("eth4")
.physBridge(DEVICE_ID_2)
.build();
KubevirtNode node = DefaultKubevirtNode.builder()
.hostname("worker")
.type(KubevirtNode.Type.WORKER)
.state(KubevirtNodeState.INIT)
.managementIp(IpAddress.valueOf("10.10.10.1"))
.intgBridge(DeviceId.deviceId("br-int"))
.tunBridge(DeviceId.deviceId("br-tun"))
.dataIp(IpAddress.valueOf("20.20.20.2"))
.phyIntfs(ImmutableList.of(phyIntf1, phyIntf2))
.build();
ObjectNode nodeJson = kubevirtNodeCodec.encode(node, context);
assertThat(nodeJson, matchesKubevirtNode(node));
} |
public boolean isValid() {
if (tokens == null)
getTokens();
return valid;
} | @Test
public void testValidationProcess() {
// TopicMultiInTheMiddle
assertThat(new Topic("finance/#/closingprice")).isInValid();
// MultiNotAfterSeparator
assertThat(new Topic("finance#")).isInValid();
// TopicMultiNotAlone
assertThat(new Topic("/finance/#closingprice")).isInValid();
// SingleNotAferSeparator
assertThat(new Topic("finance+")).isInValid();
assertThat(new Topic("finance/+")).isValid();
} |
public String stringify(boolean value) {
throw new UnsupportedOperationException(
"stringify(boolean) was called on a non-boolean stringifier: " + toString());
} | @Test
public void testDefaultStringifier() {
PrimitiveStringifier stringifier = DEFAULT_STRINGIFIER;
assertEquals("true", stringifier.stringify(true));
assertEquals("false", stringifier.stringify(false));
assertEquals("0.0", stringifier.stringify(0.0));
assertEquals("123456.7891234567", stringifier.stringify(123456.7891234567));
assertEquals("-98765.43219876543", stringifier.stringify(-98765.43219876543));
assertEquals("0.0", stringifier.stringify(0.0f));
assertEquals("987.6543", stringifier.stringify(987.6543f));
assertEquals("-123.4567", stringifier.stringify(-123.4567f));
assertEquals("0", stringifier.stringify(0));
assertEquals("1234567890", stringifier.stringify(1234567890));
assertEquals("-987654321", stringifier.stringify(-987654321));
assertEquals("0", stringifier.stringify(0l));
assertEquals("1234567890123456789", stringifier.stringify(1234567890123456789l));
assertEquals("-987654321987654321", stringifier.stringify(-987654321987654321l));
assertEquals("null", stringifier.stringify(null));
assertEquals("0x", stringifier.stringify(Binary.EMPTY));
assertEquals(
"0x0123456789ABCDEF", stringifier.stringify(toBinary(0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF)));
} |
public static String buildErrorMessage(final Throwable throwable) {
if (throwable == null) {
return "";
}
final List<String> messages = dedup(getErrorMessages(throwable));
final String msg = messages.remove(0);
final String causeMsg = messages.stream()
.filter(s -> !s.isEmpty())
.map(cause -> WordUtils.wrap(PREFIX + cause, 80, "\n\t", true))
.collect(Collectors.joining(System.lineSeparator()));
return causeMsg.isEmpty() ? msg : msg + System.lineSeparator() + causeMsg;
} | @Test
public void shouldHandleRecursiveExceptions() {
assertThat(
buildErrorMessage(new RecursiveException("It went boom")),
is("It went boom")
);
} |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testLessThanEqualsOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg =
builder.startAnd().lessThanEquals("salary", PredicateLeaf.Type.LONG, 3000L).end().build();
UnboundPredicate expected = Expressions.lessThanOrEqual("salary", 3000L);
UnboundPredicate actual =
(UnboundPredicate) HiveIcebergFilterFactory.generateFilterExpression(arg);
assertPredicatesMatch(expected, actual);
} |
@Override
public List<Long> selectAllComputeNodes() {
List<Long> nodeIds = availableID2ComputeNode.values().stream()
.map(ComputeNode::getId)
.collect(Collectors.toList());
nodeIds.forEach(this::selectWorkerUnchecked);
return nodeIds;
} | @Test
public void testChooseAllComputedNodes() {
{ // empty compute nodes
WorkerProvider workerProvider =
new DefaultSharedDataWorkerProvider(ImmutableMap.of(), ImmutableMap.of());
Assert.assertTrue(workerProvider.selectAllComputeNodes().isEmpty());
}
{ // both compute nodes and backend are treated as compute nodes
WorkerProvider workerProvider =
new DefaultSharedDataWorkerProvider(ImmutableMap.copyOf(id2AllNodes),
ImmutableMap.copyOf(id2AllNodes));
List<Long> computeNodeIds = workerProvider.selectAllComputeNodes();
Assert.assertEquals(id2AllNodes.size(), computeNodeIds.size());
Set<Long> computeNodeIdSet = new HashSet<>(computeNodeIds);
for (ComputeNode computeNode : id2AllNodes.values()) {
Assert.assertTrue(computeNodeIdSet.contains(computeNode.getId()));
testUsingWorkerHelper(workerProvider, computeNode.getId());
}
}
} |
public Map<String, Object> getContext(Map<String, Object> modelMap, Class<? extends SparkController> controller, String viewName) {
Map<String, Object> context = new HashMap<>(modelMap);
context.put("currentGoCDVersion", CurrentGoCDVersion.getInstance().getGocdDistVersion());
context.put("railsAssetsService", railsAssetsService);
context.put("webpackAssetsService", webpackAssetsService);
context.put("securityService", securityService);
context.put("maintenanceModeService", maintenanceModeService);
context.put("currentUser", SessionUtils.currentUsername());
context.put("controllerName", humanizedControllerName(controller));
context.put("viewName", viewName);
context.put("currentVersion", CurrentGoCDVersion.getInstance());
context.put("toggles", Toggles.class);
context.put("goUpdate", versionInfoService.getGoUpdate());
context.put("goUpdateCheckEnabled", versionInfoService.isGOUpdateCheckEnabled());
context.put("serverTimezoneUTCOffset", TimeZone.getDefault().getOffset(new Date().getTime()));
context.put("spaRefreshInterval", SystemEnvironment.goSpaRefreshInterval());
context.put("spaTimeout", SystemEnvironment.goSpaTimeout());
context.put("showAnalyticsDashboard", showAnalyticsDashboard());
context.put("devMode", !new SystemEnvironment().useCompressedJs());
context.put("serverSiteUrls", GSON.toJson(serverConfigService.getServerSiteUrls()));
return context;
} | @Test
void shouldNotShowAnalyticsDashboardPluginIsNotPresent() {
Map<String, Object> modelMap = new HashMap<>();
when(securityService.isUserAdmin(any(Username.class))).thenReturn(true);
when(pluginInfoFinder.allPluginInfos(PluginConstants.ANALYTICS_EXTENSION)).thenReturn(List.of(new CombinedPluginInfo()));
Map<String, Object> contect = initialContextProvider.getContext(modelMap, dummySparkController.getClass(), "viewName");
assertThat(contect.get("showAnalyticsDashboard")).isEqualTo(false);
} |
protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) {
HttpPost httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
List<NameValuePair> list = new ArrayList<>(params.size());
for (Entry<String, String> entry : params.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8));
if (!supportEnhancedContentType) {
httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED);
}
}
return httpPost;
} | @Test
public void postRequest() throws HttpException, IOException {
// Processor is required because it will determine the final request body including
// headers before outgoing.
RequestContent processor = new RequestContent();
Map<String, String> params = new HashMap<String, String>();
params.put("a", "1");
params.put("b", "2+");
params.put("c", "3 ");
HttpUriRequest request;
request = SentinelApiClient.postRequest("/test", params, false);
assertNotNull(request);
processor.process(request, null);
assertNotNull(request.getFirstHeader("Content-Type"));
assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue());
request = SentinelApiClient.postRequest("/test", params, true);
assertNotNull(request);
processor.process(request, null);
assertNotNull(request.getFirstHeader("Content-Type"));
assertEquals("application/x-www-form-urlencoded; charset=UTF-8", request.getFirstHeader("Content-Type").getValue());
} |
public static DataSource createDataSource(final File yamlFile) throws SQLException, IOException {
YamlJDBCConfiguration rootConfig = YamlEngine.unmarshal(yamlFile, YamlJDBCConfiguration.class);
return createDataSource(new YamlDataSourceConfigurationSwapper().swapToDataSources(rootConfig.getDataSources()), rootConfig);
} | @Test
void assertCreateDataSourceWithBytesForExternalDataSources() throws Exception {
Map<String, DataSource> dataSourceMap = new HashMap<>(2, 1F);
dataSourceMap.put("ds_0", new MockedDataSource());
dataSourceMap.put("ds_1", new MockedDataSource());
assertDataSource(YamlShardingSphereDataSourceFactory.createDataSource(dataSourceMap, readFile(getYamlFileUrl()).getBytes()));
} |
public FloatArrayAsIterable usingTolerance(double tolerance) {
return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_containsAtLeast_primitiveFloatArray_inOrder_success() {
assertThat(array(1.1f, TOLERABLE_2POINT2, 3.3f))
.usingTolerance(DEFAULT_TOLERANCE)
.containsAtLeast(array(1.1f, 2.2f))
.inOrder();
} |
public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args)
{
Socket pipe = ctx.createSocket(SocketType.PAIR);
assert (pipe != null);
pipe.bind(String.format(Locale.ENGLISH, "inproc://zctx-pipe-%d", pipe.hashCode()));
// Connect child pipe to our pipe
ZContext ccontext = ctx.shadow();
Socket cpipe = ccontext.createSocket(SocketType.PAIR);
assert (cpipe != null);
cpipe.connect(String.format(Locale.ENGLISH, "inproc://zctx-pipe-%d", pipe.hashCode()));
// Prepare child thread
Thread shim = new ShimThread(ccontext, runnable, args, cpipe);
shim.start();
return pipe;
} | @Test
@Ignore
public void testClosePipe()
{
ZContext ctx = new ZContext();
Socket pipe = ZThread.fork(ctx, (args, ctx1, pipe1) -> {
pipe1.recvStr();
pipe1.send("pong");
});
assertThat(pipe, notNullValue());
boolean rc = pipe.send("ping");
assertThat(rc, is(true));
String pong = pipe.recvStr();
assertThat(pong, is("pong"));
try {
rc = pipe.send("boom ?!");
assertThat("pipe was closed pretty fast", rc, is(true));
}
catch (ZMQException e) {
int errno = e.getErrorCode();
assertThat("Expected exception has the wrong code", ZError.ETERM, is(errno));
}
ctx.close();
} |
public boolean areAllowedAllNamespaces(String tenant, String fromTenant, String fromNamespace) {
return true;
} | @Test
void areAllowedAllNamespaces() {
assertTrue(flowService.areAllowedAllNamespaces("tenant", "fromTenant", "fromNamespace"));
} |
public void addServletListeners(EventListener... listeners) {
for (EventListener listener : listeners) {
handler.addEventListener(listener);
}
} | @Test
void addsServletListeners() {
final ServletContextListener listener = new DebugListener();
environment.addServletListeners(listener);
assertThat(handler.getEventListeners()).contains(listener);
} |
@Override
@Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入
public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
// 1.1 参数校验
if (CollUtil.isEmpty(importUsers)) {
throw exception(USER_IMPORT_LIST_IS_EMPTY);
}
// 1.2 初始化密码不能为空
String initPassword = configApi.getConfigValueByKey(USER_INIT_PASSWORD_KEY).getCheckedData();
if (StrUtil.isEmpty(initPassword)) {
throw exception(USER_IMPORT_INIT_PASSWORD);
}
// 2. 遍历,逐个创建 or 更新
UserImportRespVO respVO = UserImportRespVO.builder().createUsernames(new ArrayList<>())
.updateUsernames(new ArrayList<>()).failureUsernames(new LinkedHashMap<>()).build();
importUsers.forEach(importUser -> {
// 2.1.1 校验字段是否符合要求
try {
ValidationUtils.validate(BeanUtils.toBean(importUser, UserSaveReqVO.class).setPassword(initPassword));
} catch (ConstraintViolationException ex){
respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
return;
}
// 2.1.2 校验,判断是否有不符合的原因
try {
validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(),
importUser.getDeptId(), null);
} catch (ServiceException ex) {
respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
return;
}
// 2.2.1 判断如果不存在,在进行插入
AdminUserDO existUser = userMapper.selectByUsername(importUser.getUsername());
if (existUser == null) {
userMapper.insert(BeanUtils.toBean(importUser, AdminUserDO.class)
.setPassword(encodePassword(initPassword)).setPostIds(new HashSet<>())); // 设置默认密码及空岗位编号数组
respVO.getCreateUsernames().add(importUser.getUsername());
return;
}
// 2.2.2 如果存在,判断是否允许更新
if (!isUpdateSupport) {
respVO.getFailureUsernames().put(importUser.getUsername(), USER_USERNAME_EXISTS.getMsg());
return;
}
AdminUserDO updateUser = BeanUtils.toBean(importUser, AdminUserDO.class);
updateUser.setId(existUser.getId());
userMapper.updateById(updateUser);
respVO.getUpdateUsernames().add(importUser.getUsername());
});
return respVO;
} | @Test
public void testImportUserList_03() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser);
// 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
o.setUsername(dbUser.getUsername());
o.setEmail(randomEmail());
o.setMobile(randomMobile());
});
// mock deptService 的方法
DeptDO dept = randomPojo(DeptDO.class, o -> {
o.setId(importUser.getDeptId());
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
});
when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
// 调用
UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), false);
// 断言
assertEquals(0, respVO.getCreateUsernames().size());
assertEquals(0, respVO.getUpdateUsernames().size());
assertEquals(1, respVO.getFailureUsernames().size());
assertEquals(USER_USERNAME_EXISTS.getMsg(), respVO.getFailureUsernames().get(importUser.getUsername()));
} |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void fuzzy() {
String q = Q.p("f1").fuzzy("text to match").build();
assertEquals("yql=select * from sources * where f1 contains (fuzzy(\"text to match\"))", q);
} |
public static String getGlobalContextEntry(String key) {
return GLOBAL_CONTEXT_MAP.get(key);
} | @Test
public void testVerifyProcessID() throws Throwable {
assertThat(
getGlobalContextEntry(PARAM_PROCESS))
.describedAs("global context value of %s", PARAM_PROCESS)
.isEqualTo(PROCESS_ID);
} |
public static BytesInput concat(BytesInput... inputs) {
return new SequenceBytesIn(Arrays.asList(inputs));
} | @Test
public void testConcat() throws IOException {
byte[] data = new byte[1000];
RANDOM.nextBytes(data);
Supplier<BytesInput> factory = () -> BytesInput.concat(
BytesInput.from(toByteBuffer(data, 0, 250)),
BytesInput.empty(),
BytesInput.from(toByteBuffer(data, 250, 250)),
BytesInput.from(data, 500, 250),
BytesInput.from(new ByteArrayInputStream(data, 750, 250), 250));
validate(data, factory);
} |
public String getFiltersFile() {
return filtersFile;
} | @Test
public void testExclusionsOption() {
final DistCpOptions.Builder builder = new DistCpOptions.Builder(
new Path("hdfs://localhost:8020/source/first"),
new Path("hdfs://localhost:8020/target/"));
Assert.assertNull(builder.build().getFiltersFile());
builder.withFiltersFile("/tmp/filters.txt");
Assert.assertEquals("/tmp/filters.txt", builder.build().getFiltersFile());
} |
@Cacheable(value = "metadata-response", key = "#samlMetadataRequest.cacheableKey()")
public SamlMetadataResponse resolveSamlMetadata(SamlMetadataRequest samlMetadataRequest) {
LOGGER.info("Cache not found for saml-metadata {}", samlMetadataRequest.hashCode());
Connection connection = connectionService.getConnectionByEntityId(samlMetadataRequest.getConnectionEntityId());
MetadataResponseStatus metadataResponseStatus = null;
nl.logius.digid.dc.domain.service.Service service = null;
if (connection == null) {
metadataResponseStatus = CONNECTION_NOT_FOUND;
} else if (!connection.getStatus().isAllowed()) {
metadataResponseStatus = CONNECTION_INACTIVE;
} else if (!connection.getOrganization().getStatus().isAllowed()) {
metadataResponseStatus = ORGANIZATION_INACTIVE;
} else if (Boolean.FALSE.equals(connection.getOrganizationRole().getStatus().isAllowed())) {
metadataResponseStatus = ORGANIZATION_ROLE_INACTIVE;
} else {
String serviceUUID = samlMetadataRequest.getServiceUuid() == null ? getServiceUUID(connection, samlMetadataRequest.getServiceEntityId(), samlMetadataRequest.getServiceIdx()) : samlMetadataRequest.getServiceUuid();
samlMetadataRequest.setServiceUuid(serviceUUID);
service = serviceService.serviceExists(connection, samlMetadataRequest.getServiceEntityId(), serviceUUID);
if (service == null) {
metadataResponseStatus = SERVICE_NOT_FOUND;
} else if (!service.getStatus().isAllowed()) {
metadataResponseStatus = SERVICE_INACTIVE;
}
}
if (metadataResponseStatus != null) {
return metadataResponseMapper.mapErrorResponse(metadataResponseStatus.name(), metadataResponseStatus.label);
} else {
String samlMetadata = generateReducedMetadataString(connection, service.getEntityId());
return metadataResponseMapper.mapSuccessResponse(samlMetadata, connection, service, STATUS_OK.name());
}
} | @Test
void serviceNotFoundTest() {
Connection connection = newConnection(SAML_COMBICONNECT, true, true, true);
when(connectionServiceMock.getConnectionByEntityId(anyString())).thenReturn(connection);
when(serviceServiceMock.serviceExists(any(Connection.class), anyString(), anyString())).thenReturn(null);
SamlMetadataResponse response = metadataRetrieverServiceMock.resolveSamlMetadata(newMetadataRequest());
assertEquals(SERVICE_NOT_FOUND.name(), response.getRequestStatus());
assertEquals(SERVICE_NOT_FOUND.label, response.getErrorDescription());
} |
public String createULID(Message message) {
checkTimestamp(message.getTimestamp().getMillis());
try {
return createULID(message.getTimestamp().getMillis(), message.getSequenceNr());
} catch (Exception e) {
LOG.error("Exception while creating ULID.", e);
return ulid.nextULID(message.getTimestamp().getMillis());
}
} | @Test
public void intMaxGenerate() {
final MessageULIDGenerator generator = new MessageULIDGenerator(new ULID());
final long ts = Tools.nowUTC().getMillis();
ULID.Value parsedULID = ULID.parseULID(generator.createULID(ts, Integer.MAX_VALUE));
assertThat(extractSequenceNr(parsedULID)).isEqualTo(Integer.MAX_VALUE);
} |
@Override
public boolean exists() {
setupClientIfNeeded();
try (Reader<String> historyReader = createHistoryReader()) {
return historyReader.hasMessageAvailable();
} catch (IOException e) {
log.error("Encountered issues on checking existence of database history", e);
throw new RuntimeException("Encountered issues on checking existence of database history", e);
}
} | @Test
public void testExists() throws Exception {
// happy path
testHistoryTopicContent(true, false);
assertTrue(history.exists());
// Set history to use dummy topic
Configuration config = Configuration.create()
.with(PulsarDatabaseHistory.SERVICE_URL, brokerUrl.toString())
.with(PulsarDatabaseHistory.TOPIC, "persistent://my-property/my-ns/dummytopic")
.with(DatabaseHistory.NAME, "my-db-history")
.with(DatabaseHistory.SKIP_UNPARSEABLE_DDL_STATEMENTS, true)
.build();
history.configure(config, null, DatabaseHistoryListener.NOOP, true);
history.start();
// dummytopic should not exist yet
assertFalse(history.exists());
} |
@Udf
public String rpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (padding == null || padding.isEmpty() || targetLen == null || targetLen < 0) {
return null;
}
final StringBuilder sb = new StringBuilder(targetLen + padding.length());
sb.append(input);
final int padChars = Math.max(targetLen - input.length(), 0);
for (int i = 0; i < padChars; i += padding.length()) {
sb.append(padding);
}
sb.setLength(targetLen);
return sb.toString();
} | @Test
public void shouldReturnEmptyStringForZeroLength() {
final String result = udf.rpad("foo", 0, "bar");
assertThat(result, is(""));
} |
public int runInteractively() {
displayWelcomeMessage();
RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient);
boolean eof = false;
while (!eof) {
try {
handleLine(nextNonCliCommand());
} catch (final EndOfFileException exception) {
// EOF is fine, just terminate the REPL
terminal.writer().println("Exiting ksqlDB.");
eof = true;
} catch (final Exception exception) {
LOGGER.error("An error occurred while running a command. Error = "
+ exception.getMessage(), exception);
terminal.printError(ErrorMessageUtil.buildErrorMessage(exception),
exception.toString());
}
terminal.flush();
}
return NO_ERROR;
} | @Test
public void shouldPrintWarningOnUnknownServerVersion() throws Exception {
givenRunInteractivelyWillExit();
final KsqlRestClient mockRestClient = givenMockRestClient("bad-version");
new Cli(1L, 1L, mockRestClient, console)
.runInteractively();
assertThat(
terminal.getOutputString(),
containsString("WARNING: Could not identify server version.")
);
} |
@Override
public void process(HttpResponse response, HttpContext context) throws
HttpException, IOException {
List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList());
response.removeHeaders("Warning");
warnings.stream().forEach(header -> response.addHeader(header));
} | @Test
public void testInterceptorMultipleHeaderFilteredWarning() throws IOException, HttpException {
OpenSearchFilterDeprecationWarningsInterceptor interceptor = new OpenSearchFilterDeprecationWarningsInterceptor();
HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 0, 0), 0, null));
response.addHeader("Test", "This header should not trigger the interceptor.");
response.addHeader("Warning", "This warning should not trigger the interceptor.");
response.addHeader("Warning", "This text contains the trigger: setting was deprecated in OpenSearch - and should be filtered out");
assertThat(response.getAllHeaders())
.as("Number of Headers should be 3 before start.")
.hasSize(3);
interceptor.process(response, null);
assertThat(response.getAllHeaders())
.as("Number of Headers should be 1 less after running the interceptor.")
.hasSize(2);
} |
@ScalarOperator(LESS_THAN)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThan(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right)
{
return left < right;
} | @Test
public void testLessThan()
{
assertFunction("INTEGER'37' < INTEGER'37'", BOOLEAN, false);
assertFunction("INTEGER'37' < INTEGER'17'", BOOLEAN, false);
assertFunction("INTEGER'17' < INTEGER'37'", BOOLEAN, true);
assertFunction("INTEGER'17' < INTEGER'17'", BOOLEAN, false);
} |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testParseNewStyleResourceMemoryNegative() throws Exception {
expectNegativeValueOfResource("memory");
parseResourceConfigValue("memory-mb=-5120,vcores=2");
} |
@Override
void toHtml() throws IOException {
writeHtmlHeader();
htmlCoreReport.toHtml();
writeHtmlFooter();
} | @Test
public void testEmptyCounter() throws IOException {
final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,
Period.TOUT, writer);
// rapport avec counter sans requête
counter.clear();
errorCounter.clear();
htmlReport.toHtml(null, null);
assertNotEmptyAndClear(writer);
} |
@Override
public void close() {
if (_executionFuture != null) {
_executionFuture.cancel(true);
}
} | @Test
public void shouldNotErrorOutWhenIncorrectDataSchemaProvidedWithEmptyRowsSelection() {
// Given:
QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT strCol, intCol FROM tbl");
DataSchema resultSchema = new DataSchema(new String[]{"strCol", "intCol"},
new DataSchema.ColumnDataType[]{DataSchema.ColumnDataType.STRING, DataSchema.ColumnDataType.STRING});
DataSchema desiredSchema = new DataSchema(new String[]{"strCol", "intCol"},
new DataSchema.ColumnDataType[]{DataSchema.ColumnDataType.STRING, DataSchema.ColumnDataType.INT});
List<BaseResultsBlock> dataBlocks = Collections.emptyList();
InstanceResponseBlock emptySelectionResponseBlock =
new InstanceResponseBlock(new SelectionResultsBlock(resultSchema, Collections.emptyList(), queryContext));
QueryExecutor queryExecutor = mockQueryExecutor(dataBlocks, emptySelectionResponseBlock);
LeafStageTransferableBlockOperator operator =
new LeafStageTransferableBlockOperator(OperatorTestUtil.getTracingContext(), mockQueryRequests(1),
desiredSchema, queryExecutor, _executorService);
_operatorRef.set(operator);
// When:
TransferableBlock resultBlock = operator.nextBlock();
// Then:
Assert.assertTrue(resultBlock.isEndOfStreamBlock());
operator.close();
} |
public static String getHeartbeatClientIp() {
String ip = SentinelConfig.getConfig(HEARTBEAT_CLIENT_IP, true);
if (StringUtil.isBlank(ip)) {
ip = HostNameUtil.getIp();
}
return ip;
} | @Test
public void testGetHeartbeatClientIp() {
String clientIp = "10.10.10.10";
SentinelConfig.setConfig(TransportConfig.HEARTBEAT_CLIENT_IP, clientIp);
// Set heartbeat client ip to system property.
String ip = TransportConfig.getHeartbeatClientIp();
assertNotNull(ip);
assertEquals(clientIp, ip);
// Set no heartbeat client ip.
SentinelConfig.setConfig(TransportConfig.HEARTBEAT_CLIENT_IP, "");
assertTrue(StringUtil.isNotEmpty(TransportConfig.getHeartbeatClientIp()));
} |
public void addResources(ConcurrentMap<String, ? extends LocallyCachedBlob> blobs) {
for (LocallyCachedBlob b : blobs.values()) {
currentSize += b.getSizeOnDisk();
if (b.isUsed()) {
LOG.debug("NOT going to clean up {}, {} depends on it", b.getKey(), b.getDependencies());
// always retain resources in use
continue;
}
LOG.debug("Possibly going to clean up {} ts {} size {}", b.getKey(), b.getLastUsed(), b.getSizeOnDisk());
noReferences.put(b, blobs);
}
} | @Test
public void testAddResources() {
PortAndAssignment pna1 = new PortAndAssignmentImpl(1, new LocalAssignment("topo1", Collections.emptyList()));
PortAndAssignment pna2 = new PortAndAssignmentImpl(1, new LocalAssignment("topo2", Collections.emptyList()));
String user = "user";
Map<String, Object> conf = new HashMap<>();
IAdvancedFSOps ops = mock(IAdvancedFSOps.class);
LocalizedResourceRetentionSet lrretset = new LocalizedResourceRetentionSet(10);
ConcurrentMap<String, LocalizedResource> lrset = new ConcurrentHashMap<>();
StormMetricsRegistry metricsRegistry = new StormMetricsRegistry();
LocalizedResource localresource1 = new LocalizedResource("key1", Paths.get("testfile1"), false, ops, conf, user, metricsRegistry);
localresource1.addReference(pna1, null);
LocalizedResource localresource2 = new LocalizedResource("key2", Paths.get("testfile2"), false, ops, conf, user, metricsRegistry);
localresource2.addReference(pna1, null);
// check adding reference to local resource with topology of same name
localresource2.addReference(pna2, null);
lrset.put("key1", localresource1);
lrset.put("key2", localresource2);
lrretset.addResources(lrset);
assertEquals(0, lrretset.getSizeWithNoReferences(), "number to clean is not 0 " + lrretset.noReferences);
assertTrue(localresource1.removeReference(pna1));
lrretset = new LocalizedResourceRetentionSet(10);
lrretset.addResources(lrset);
assertEquals(1, lrretset.getSizeWithNoReferences(), "number to clean is not 1 " + lrretset.noReferences);
assertTrue(localresource2.removeReference(pna1));
lrretset = new LocalizedResourceRetentionSet(10);
lrretset.addResources(lrset);
assertEquals(1, lrretset.getSizeWithNoReferences(), "number to clean is not 1 " + lrretset.noReferences);
assertTrue(localresource2.removeReference(pna2));
lrretset = new LocalizedResourceRetentionSet(10);
lrretset.addResources(lrset);
assertEquals(2, lrretset.getSizeWithNoReferences(), "number to clean is not 2 " + lrretset.noReferences);
} |
public OrderedProperties addStringPairs(String keyValuePairs) {
PropertiesReader reader = new PropertiesReader(pairs);
reader.read(keyValuePairs);
return this;
} | @Test
public void addStringPairs() {
OrderedProperties pairs = new OrderedProperties()
.addStringPairs("first=1\nsecond=2\nthird=3\nFOURTH=4");
assertValueOrder(pairs, "1", "2", "3", "4");
} |
@Override
public WindowStoreIterator<V> backwardFetch(final K key,
final Instant timeFrom,
final Instant timeTo) throws IllegalArgumentException {
Objects.requireNonNull(key, "key can't be null");
final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType);
for (final ReadOnlyWindowStore<K, V> windowStore : stores) {
try {
final WindowStoreIterator<V> result = windowStore.backwardFetch(key, timeFrom, timeTo);
if (!result.hasNext()) {
result.close();
} else {
return result;
}
} catch (final InvalidStateStoreException e) {
throw new InvalidStateStoreException(
"State store is not available anymore and may have been migrated to another instance; " +
"please re-discover its location from the state metadata.");
}
}
return KeyValueIterators.emptyWindowStoreIterator();
} | @Test
public void shouldThrowInvalidStateStoreExceptionOnRebalanceWhenBackwards() {
final StateStoreProvider storeProvider = mock(StateStoreProvider.class);
when(storeProvider.stores(anyString(), any()))
.thenThrow(new InvalidStateStoreException("store is unavailable"));
final CompositeReadOnlyWindowStore<Object, Object> store = new CompositeReadOnlyWindowStore<>(
storeProvider,
QueryableStoreTypes.windowStore(),
"foo"
);
assertThrows(InvalidStateStoreException.class, () -> store.backwardFetch("key", ofEpochMilli(1), ofEpochMilli(10)));
} |
public static Validator parses(final Function<String, ?> parser) {
return (name, val) -> {
if (val != null && !(val instanceof String)) {
throw new IllegalArgumentException("validator should only be used with STRING defs");
}
try {
parser.apply((String)val);
} catch (final Exception e) {
throw new ConfigException("Configuration " + name + " is invalid: " + e.getMessage());
}
};
} | @Test
public void shouldPassNullsToParser() {
// Given:
final Validator validator = ConfigValidators.parses(parser);
// When:
validator.ensureValid("propName", null);
// Then:
verify(parser).apply(null);
} |
@Override
public MetricType getType() {
return MetricType.GAUGE_UNKNOWN;
} | @Test
public void getValue() {
UnknownGauge gauge = new UnknownGauge("bar", URI.create("baz"));
assertThat(gauge.getValue()).isEqualTo(URI.create("baz"));
assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_UNKNOWN);
//Null initialize
gauge = new UnknownGauge("bar");
assertThat(gauge.getValue()).isNull();
assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_UNKNOWN);
} |
@NonNull
public RouterFunction<ServerResponse> create() {
var getHandler = new ExtensionGetHandler(scheme, client);
var listHandler = new ExtensionListHandler(scheme, client);
var createHandler = new ExtensionCreateHandler(scheme, client);
var updateHandler = new ExtensionUpdateHandler(scheme, client);
var deleteHandler = new ExtensionDeleteHandler(scheme, client);
var patchHandler = new ExtensionPatchHandler(scheme, client);
// TODO More handlers here
var gvk = scheme.groupVersionKind();
var kind = gvk.kind();
var tagName = gvk.kind() + StringUtils.capitalize(gvk.version());
return SpringdocRouteBuilder.route()
.GET(getHandler.pathPattern(), getHandler,
builder -> builder.operationId("get" + kind)
.description("Get " + kind)
.tag(tagName)
.parameter(parameterBuilder().in(ParameterIn.PATH)
.name("name")
.description("Name of " + scheme.singular()))
.response(responseBuilder().responseCode("200")
.description("Response single " + scheme.singular())
.implementation(scheme.type())))
.GET(listHandler.pathPattern(), listHandler,
builder -> {
builder.operationId("list" + kind)
.description("List " + kind)
.tag(tagName)
.response(responseBuilder().responseCode("200")
.description("Response " + scheme.plural())
.implementation(ListResult.generateGenericClass(scheme)));
SortableRequest.buildParameters(builder);
})
.POST(createHandler.pathPattern(), createHandler,
builder -> builder.operationId("create" + kind)
.description("Create " + kind)
.tag(tagName)
.requestBody(requestBodyBuilder()
.description("Fresh " + scheme.singular())
.implementation(scheme.type()))
.response(responseBuilder().responseCode("200")
.description("Response " + scheme.plural() + " created just now")
.implementation(scheme.type())))
.PUT(updateHandler.pathPattern(), updateHandler,
builder -> builder.operationId("update" + kind)
.description("Update " + kind)
.tag(tagName)
.parameter(parameterBuilder().in(ParameterIn.PATH)
.name("name")
.description("Name of " + scheme.singular()))
.requestBody(requestBodyBuilder()
.description("Updated " + scheme.singular())
.implementation(scheme.type()))
.response(responseBuilder().responseCode("200")
.description("Response " + scheme.plural() + " updated just now")
.implementation(scheme.type())))
.PATCH(patchHandler.pathPattern(), patchHandler,
builder -> builder.operationId("patch" + kind)
.description("Patch " + kind)
.tag(tagName)
.parameter(parameterBuilder().in(ParameterIn.PATH)
.name("name")
.description("Name of " + scheme.singular()))
.requestBody(requestBodyBuilder()
.content(contentBuilder()
.mediaType("application/json-patch+json")
.schema(
schemaBuilder().ref(RefUtils.constructRef(JsonPatch.SCHEMA_NAME))
)
)
)
.response(responseBuilder().responseCode("200")
.description("Response " + scheme.singular() + " patched just now")
.implementation(scheme.type())
)
)
.DELETE(deleteHandler.pathPattern(), deleteHandler,
builder -> builder.operationId("delete" + kind)
.description("Delete " + kind)
.tag(tagName)
.parameter(parameterBuilder().in(ParameterIn.PATH)
.name("name")
.description("Name of " + scheme.singular()))
.response(responseBuilder().responseCode("200")
.description("Response " + scheme.singular() + " deleted just now")))
.build();
} | @Test
void shouldCreateSuccessfully() {
var routerFunction = factory.create();
testCases().forEach(testCase -> {
List<HttpMessageReader<?>> messageReaders =
HandlerStrategies.withDefaults().messageReaders();
var request = ServerRequest.create(testCase.webExchange, messageReaders);
var handlerFunc = routerFunction.route(request).block();
assertInstanceOf(testCase.expectHandlerType, handlerFunc);
});
} |
public static NamespaceName get(String tenant, String namespace) {
validateNamespaceName(tenant, namespace);
return get(tenant + '/' + namespace);
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void namespace_emptyTenantElement() {
NamespaceName.get("/cluster/namespace");
} |
@Override
public RemoteData.Builder serialize() {
final RemoteData.Builder remoteBuilder = RemoteData.newBuilder();
remoteBuilder.addDataObjectStrings(total.toStorageData());
remoteBuilder.addDataLongs(getTimeBucket());
remoteBuilder.addDataStrings(getEntityId());
remoteBuilder.addDataStrings(getServiceId());
return remoteBuilder;
} | @Test
public void testSerialize() {
function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), table1);
SumPerMinLabeledFunction function2 = Mockito.spy(SumPerMinLabeledFunction.class);
function2.deserialize(function.serialize().build());
assertThat(function2.getEntityId()).isEqualTo(function.getEntityId());
assertThat(function2.getTimeBucket()).isEqualTo(function.getTimeBucket());
} |
public Main() {
addOption(new Option("h", "help", "Displays the help screen") {
protected void doProcess(String arg, LinkedList<String> remainingArgs) {
showOptions();
// no need to process further if user just wants help
System.exit(0);
}
});
addOption(new ParameterOption("c", "command", "Command can be encrypt or decrypt", "command") {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
if ("encrypt".equals(parameter) || "decrypt".equals(parameter)) {
command = parameter;
} else {
throw new IllegalArgumentException("Unknown command, was: " + parameter);
}
}
});
addOption(new ParameterOption("p", "password", "Password to use", "password") {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
password = parameter;
}
});
addOption(new ParameterOption("i", "input", "Text to encrypt or decrypt", "input") {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
input = parameter;
}
});
addOption(new ParameterOption("a", "algorithm", "Optional algorithm to use", "algorithm") {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
algorithm = parameter;
}
});
addOption(new ParameterOption("rsga", "salt", "Optional random salt generator algorithm to use", "salt") {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
randomSaltGeneratorAlgorithm = parameter;
}
});
addOption(new ParameterOption("riga", "iv", "Optional random iv generator algorithm to use", "iv") {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
randomIvGeneratorAlgorithm = parameter;
}
});
} | @Test
public void testMainShowOptions() {
assertDoesNotThrow(() -> Main.main(new String[] {}));
} |
public static <E> boolean addWithoutChecking(CheckedList<E> list, E element)
{
return list.addWithAssertChecking(element);
} | @Test(expectedExceptions = AssertionError.class)
public void testAddCycleWithAssertChecking()
{
final DataList list = new DataList();
CheckedUtil.addWithoutChecking(list, list);
} |
@Override
public int permitMinimum() {
return minConnections;
} | @Test
void permitMinimum() {
builder.minConnections(2);
Http2AllocationStrategy strategy = builder.build();
assertThat(strategy.maxConcurrentStreams()).isEqualTo(DEFAULT_MAX_CONCURRENT_STREAMS);
assertThat(strategy.permitMaximum()).isEqualTo(DEFAULT_MAX_CONNECTIONS);
assertThat(strategy.permitMinimum()).isEqualTo(2);
} |
public static List<String> getJavaOpts(Configuration conf) {
String adminOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_KEY,
YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_DEFAULT);
String userOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_KEY,
YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_DEFAULT);
boolean isExtraJDK17OptionsConfigured =
conf.getBoolean(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_ADD_EXPORTS_KEY,
YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_ADD_EXPORTS_DEFAULT);
if (Shell.isJavaVersionAtLeast(17) && isExtraJDK17OptionsConfigured) {
userOpts = userOpts.trim().concat(" " + ADDITIONAL_JDK17_PLUS_OPTIONS);
}
List<String> adminOptionList = Arrays.asList(adminOpts.split("\\s+"));
List<String> userOptionList = Arrays.asList(userOpts.split("\\s+"));
return Stream.concat(adminOptionList.stream(), userOptionList.stream())
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
} | @Test
public void testDefaultJavaOptionsWhenExtraJDK17OptionsAreConfigured() throws Exception {
ContainerLocalizerWrapper wrapper = new ContainerLocalizerWrapper();
ContainerLocalizer localizer = wrapper.setupContainerLocalizerForTest();
Configuration conf = new Configuration();
conf.setBoolean(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_ADD_EXPORTS_KEY,
true);
List<String> javaOpts = localizer.getJavaOpts(conf);
if (Shell.isJavaVersionAtLeast(17)) {
Assert.assertTrue(javaOpts.contains("--add-exports=java.base/sun.net.dns=ALL-UNNAMED"));
Assert.assertTrue(javaOpts.contains("--add-exports=java.base/sun.net.util=ALL-UNNAMED"));
}
Assert.assertTrue(javaOpts.contains("-Xmx256m"));
} |
public String defaultRemoteUrl() {
final String sanitizedUrl = sanitizeUrl();
try {
URI uri = new URI(sanitizedUrl);
if (uri.getUserInfo() != null) {
uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
return uri.toString();
}
} catch (URISyntaxException e) {
return sanitizedUrl;
}
return sanitizedUrl;
} | @Test
void shouldNotModifyFileURIS() {
assertThat(new HgUrlArgument("file://junk").defaultRemoteUrl(), is("file://junk"));
} |
public static NodeList selectNodeList(Document document, String xPathExpression) throws TransformerException {
XObject xObject = XPathAPI.eval(document, xPathExpression, getPrefixResolver(document));
return xObject.nodelist();
} | @Test
public void testSelectNodeList() throws ParserConfigurationException, SAXException, IOException, TidyException, TransformerException {
String responseData = "<book><page>one</page><page>two</page><empty></empty><a><b></b></a></book>";
Document testDoc = XPathUtil.makeDocument(
new ByteArrayInputStream(responseData.getBytes(StandardCharsets.UTF_8)), false, false, false, false,
false, false, false, false, false);
String xpathquery = "/book/page";
NodeList nodeList = XPathUtil.selectNodeList(testDoc, xpathquery);
assertEquals(2, nodeList.getLength());
Element e0 = (Element) nodeList.item(0);
Element e1 = (Element) nodeList.item(1);
assertEquals("one", e0.getTextContent());
assertEquals("two", e1.getTextContent());
} |
static Schema removeFields(Schema schema, String... fields) {
List<String> exclude = Arrays.stream(fields).collect(Collectors.toList());
Schema.Builder builder = Schema.builder();
for (Field field : schema.getFields()) {
if (exclude.contains(field.getName())) {
continue;
}
builder.addField(field);
}
return builder.build();
} | @Test
public void testPubsubRowToMessageParDo_attributesWithoutTimestamp() {
Map<String, String> attributes = new HashMap<>();
attributes.put("a", "1");
attributes.put("b", "2");
attributes.put("c", "3");
Row withAttributes =
Row.withSchema(NON_USER_WITH_BYTES_PAYLOAD)
.addValues(attributes, Instant.now(), new byte[] {})
.build();
assertEquals(
attributes,
doFn(NON_USER_WITH_BYTES_PAYLOAD, null).attributesWithoutTimestamp(withAttributes));
Schema withoutAttributesSchema =
removeFields(NON_USER_WITH_BYTES_PAYLOAD, DEFAULT_ATTRIBUTES_KEY_NAME);
Row withoutAttributes =
Row.withSchema(withoutAttributesSchema).addValues(Instant.now(), new byte[] {}).build();
assertEquals(
ImmutableMap.of(),
doFn(withoutAttributesSchema, null).attributesWithoutTimestamp(withoutAttributes));
} |
public Record convert(final AbstractWALEvent event) {
if (filter(event)) {
return createPlaceholderRecord(event);
}
if (!(event instanceof AbstractRowEvent)) {
return createPlaceholderRecord(event);
}
PipelineTableMetaData tableMetaData = getPipelineTableMetaData(((AbstractRowEvent) event).getTableName());
if (event instanceof WriteRowEvent) {
return handleWriteRowEvent((WriteRowEvent) event, tableMetaData);
}
if (event instanceof UpdateRowEvent) {
return handleUpdateRowEvent((UpdateRowEvent) event, tableMetaData);
}
if (event instanceof DeleteRowEvent) {
return handleDeleteRowEvent((DeleteRowEvent) event, tableMetaData);
}
throw new UnsupportedSQLOperationException("");
} | @Test
void assertConvertFailure() {
AbstractRowEvent event = new AbstractRowEvent() {
};
event.setSchemaName("");
event.setTableName("t_order");
assertThrows(UnsupportedSQLOperationException.class, () -> walEventConverter.convert(event));
} |
@Override
public ShenyuContext build(final ServerWebExchange exchange) {
Pair<String, MetaData> buildData = buildData(exchange);
return decoratorMap.get(buildData.getLeft()).decorator(buildDefaultContext(exchange.getRequest()), buildData.getRight());
} | @Test
public void testBuild() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost:8080/http")
.remoteAddress(new InetSocketAddress(8092))
.header("MetaDataCache", "Hello")
.build());
ShenyuContext shenyuContext = defaultShenyuContextBuilder.build(exchange);
assertNotNull(shenyuContext);
assertEquals(RpcTypeEnum.HTTP.getName(), shenyuContext.getRpcType());
} |
public static ConnAckBuilder connAck() {
return new ConnAckBuilder();
} | @Test
public void testConnAckWithProperties() {
final MqttConnAckMessage ackMsg = MqttMessageBuilders.connAck()
.properties(new PropertiesInitializer<MqttMessageBuilders.ConnAckPropertiesBuilder>() {
@Override
public void apply(MqttMessageBuilders.ConnAckPropertiesBuilder builder) {
builder.assignedClientId("client1234");
builder.userProperty("custom_property", "value");
}
}).build();
final String clientId = (String) ackMsg.variableHeader()
.properties()
.getProperty(MqttProperties.MqttPropertyType.ASSIGNED_CLIENT_IDENTIFIER.value())
.value();
assertEquals("client1234", clientId);
} |
public static String toJsonStr(JSON json, int indentFactor) {
if (null == json) {
return null;
}
return json.toJSONString(indentFactor);
} | @Test
public void toJsonStrTest() {
final UserA a1 = new UserA();
a1.setA("aaaa");
a1.setDate(DateUtil.date());
a1.setName("AAAAName");
final UserA a2 = new UserA();
a2.setA("aaaa222");
a2.setDate(DateUtil.date());
a2.setName("AAAA222Name");
final ArrayList<UserA> list = CollectionUtil.newArrayList(a1, a2);
final HashMap<String, Object> map = MapUtil.newHashMap();
map.put("total", 13);
map.put("rows", list);
final String str = JSONUtil.toJsonPrettyStr(map);
JSONUtil.parse(str);
assertNotNull(str);
} |
@VisibleForTesting
Path getActualPath() throws IOException {
Path path = localPath;
FileStatus status = localFs.getFileStatus(path);
if (status != null && status.isDirectory()) {
// for certain types of resources that get unpacked, the original file may
// be found under the directory with the same name (see
// FSDownload.unpack); check if the path is a directory and if so look
// under it
path = new Path(path, path.getName());
}
return path;
} | @Test
public void testGetActualPath() throws Exception {
Configuration conf = new Configuration();
conf.setBoolean(YarnConfiguration.SHARED_CACHE_ENABLED, true);
LocalResource resource = mock(LocalResource.class);
// give public visibility
when(resource.getVisibility()).thenReturn(LocalResourceVisibility.PUBLIC);
Path localPath = new Path("foo.jar");
String user = "joe";
SCMUploaderProtocol scmClient = mock(SCMUploaderProtocol.class);
FileSystem fs = mock(FileSystem.class);
FileSystem localFs = mock(FileSystem.class);
// stub it to return a status that indicates a directory
FileStatus status = mock(FileStatus.class);
when(status.isDirectory()).thenReturn(true);
when(localFs.getFileStatus(localPath)).thenReturn(status);
SharedCacheUploader spied =
createSpiedUploader(resource, localPath, user, conf, scmClient, fs,
localFs);
Path actualPath = spied.getActualPath();
assertEquals(actualPath.getName(), localPath.getName());
assertEquals(actualPath.getParent().getName(), localPath.getName());
} |
public URI buildEncodedUri(String endpointUrl) {
if (endpointUrl == null) {
throw new RuntimeException("Url string cannot be null!");
}
if (endpointUrl.isEmpty()) {
throw new RuntimeException("Url string cannot be empty!");
}
URI uri = UriComponentsBuilder.fromUriString(endpointUrl).build().encode().toUri();
if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
throw new RuntimeException("Transport scheme(protocol) must be provided!");
}
boolean authorityNotValid = uri.getAuthority() == null || uri.getAuthority().isEmpty();
boolean hostNotValid = uri.getHost() == null || uri.getHost().isEmpty();
if (authorityNotValid || hostNotValid) {
throw new RuntimeException("Url string is invalid!");
}
return uri;
} | @Test
public void testBuildSimpleUri() {
Mockito.when(client.buildEncodedUri(any())).thenCallRealMethod();
String url = "http://localhost:8080/";
URI uri = client.buildEncodedUri(url);
Assertions.assertEquals(url, uri.toString());
} |
@Override
public void serialize(Asn1OutputStream out, BigInteger obj) {
out.write(BCD.encode(obj));
} | @Test
public void shouldSerialize() {
assertArrayEquals(
new byte[] { 0x13, 0x37 },
serialize(new BcdConverter(), BigInteger.class, BigInteger.valueOf(1337))
);
} |
@Produces
@DefaultBean
@Singleton
JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration() {
if (jobRunrBuildTimeConfiguration.dashboard().enabled()) {
final JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration = usingStandardDashboardConfiguration();
jobRunrRuntimeConfiguration.dashboard().port().ifPresent(dashboardWebServerConfiguration::andPort);
if (jobRunrRuntimeConfiguration.dashboard().username().isPresent() && jobRunrRuntimeConfiguration.dashboard().password().isPresent()) {
dashboardWebServerConfiguration.andBasicAuthentication(jobRunrRuntimeConfiguration.dashboard().username().get(), jobRunrRuntimeConfiguration.dashboard().password().get());
}
dashboardWebServerConfiguration.andAllowAnonymousDataUsage(jobRunrRuntimeConfiguration.miscellaneous().allowAnonymousDataUsage());
return dashboardWebServerConfiguration;
}
return null;
} | @Test
void dashboardWebServerConfigurationIsSetupWhenConfigured() {
when(dashboardBuildTimeConfiguration.enabled()).thenReturn(true);
assertThat(jobRunrProducer.dashboardWebServerConfiguration()).isNotNull();
} |
@Override
public Long del(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key: keys) {
write(key, LongCodec.INSTANCE, RedisCommands.DEL, key);
}
return null;
}
CommandBatchService es = new CommandBatchService(executorService);
for (byte[] key: keys) {
es.writeAsync(key, StringCodec.INSTANCE, RedisCommands.DEL, key);
}
BatchResult<Long> b = (BatchResult<Long>) es.execute();
return b.getResponses().stream().collect(Collectors.summarizingLong(v -> v)).getSum();
} | @Test
public void testDelPipeline() {
byte[] k = "key".getBytes();
byte[] v = "val".getBytes();
connection.set(k, v);
connection.openPipeline();
connection.get(k);
connection.del(k);
List<Object> results = connection.closePipeline();
byte[] val = (byte[])results.get(0);
assertThat(val).isEqualTo(v);
Long res = (Long) results.get(1);
assertThat(res).isEqualTo(1);
} |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefinition());
if (op != null) {
switch (op) {
case IS_NULL:
return onlyChildAs(call, FieldReferenceExpression.class)
.map(FieldReferenceExpression::getName)
.map(Expressions::isNull);
case NOT_NULL:
return onlyChildAs(call, FieldReferenceExpression.class)
.map(FieldReferenceExpression::getName)
.map(Expressions::notNull);
case LT:
return convertFieldAndLiteral(Expressions::lessThan, Expressions::greaterThan, call);
case LT_EQ:
return convertFieldAndLiteral(
Expressions::lessThanOrEqual, Expressions::greaterThanOrEqual, call);
case GT:
return convertFieldAndLiteral(Expressions::greaterThan, Expressions::lessThan, call);
case GT_EQ:
return convertFieldAndLiteral(
Expressions::greaterThanOrEqual, Expressions::lessThanOrEqual, call);
case EQ:
return convertFieldAndLiteral(
(ref, lit) -> {
if (NaNUtil.isNaN(lit)) {
return Expressions.isNaN(ref);
} else {
return Expressions.equal(ref, lit);
}
},
call);
case NOT_EQ:
return convertFieldAndLiteral(
(ref, lit) -> {
if (NaNUtil.isNaN(lit)) {
return Expressions.notNaN(ref);
} else {
return Expressions.notEqual(ref, lit);
}
},
call);
case NOT:
return onlyChildAs(call, CallExpression.class)
.flatMap(FlinkFilters::convert)
.map(Expressions::not);
case AND:
return convertLogicExpression(Expressions::and, call);
case OR:
return convertLogicExpression(Expressions::or, call);
case STARTS_WITH:
return convertLike(call);
}
}
return Optional.empty();
} | @Test
public void testLike() {
UnboundPredicate<?> expected =
org.apache.iceberg.expressions.Expressions.startsWith("field5", "abc");
Expression expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions.lit("abc%")));
Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert(expr);
assertThat(actual).isPresent();
assertPredicatesMatch(expected, actual.get());
expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions.lit("%abc")));
actual = FlinkFilters.convert(expr);
assertThat(actual).isNotPresent();
expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE,
Expressions.$("field5"),
Expressions.lit("%abc%")));
actual = FlinkFilters.convert(expr);
assertThat(actual).isNotPresent();
expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE,
Expressions.$("field5"),
Expressions.lit("abc%d")));
actual = FlinkFilters.convert(expr);
assertThat(actual).isNotPresent();
expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions.lit("%")));
actual = FlinkFilters.convert(expr);
assertThat(actual).isNotPresent();
expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions.lit("a_")));
actual = FlinkFilters.convert(expr);
assertThat(actual).isNotPresent();
expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions.lit("a%b")));
actual = FlinkFilters.convert(expr);
assertThat(actual).isNotPresent();
} |
public static int toIntSize(long size) {
assert size >= 0 : "Invalid size value: " + size;
return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
} | @Test
public void toIntSize_whenLessThanIntMax() {
long size = 123456789;
assertEquals((int) size, toIntSize(size));
} |
public boolean isAbilitySupportedByServer(AbilityKey abilityKey) {
return rpcClient.getConnectionAbility(abilityKey) == AbilityStatus.SUPPORTED;
} | @Test
void testIsAbilitySupportedByServer3() {
when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(
AbilityStatus.UNKNOWN);
assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC));
verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
} |
public static FileMetaData readFileMetaData(InputStream from) throws IOException {
return readFileMetaData(from, null, null);
} | @Test
public void testReadFileMetadata() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileMetaData md = new FileMetaData(
1,
asList(new SchemaElement("foo")),
10,
asList(
new RowGroup(asList(new ColumnChunk(0), new ColumnChunk(1)), 10, 5),
new RowGroup(asList(new ColumnChunk(2), new ColumnChunk(3)), 11, 5)));
writeFileMetaData(md, baos);
FileMetaData md2 = readFileMetaData(in(baos));
FileMetaData md3 = new FileMetaData();
readFileMetaData(in(baos), new DefaultFileMetaDataConsumer(md3));
FileMetaData md4 = new FileMetaData();
readFileMetaData(in(baos), new DefaultFileMetaDataConsumer(md4), true);
FileMetaData md5 = readFileMetaData(in(baos), true);
FileMetaData md6 = readFileMetaData(in(baos), false);
assertEquals(md, md2);
assertEquals(md, md3);
assertNull(md4.getRow_groups());
assertNull(md5.getRow_groups());
assertEquals(md4, md5);
md4.setRow_groups(md.getRow_groups());
md5.setRow_groups(md.getRow_groups());
assertEquals(md, md4);
assertEquals(md, md5);
assertEquals(md4, md5);
assertEquals(md, md6);
} |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromString(
result, forwarded, nonForwarded, readSet, inType, outType, false);
} | @Test
void testForwardedWildCardInvalidTypes3() {
String[] forwardedFields = {"*"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, forwardedFields, null, null, pojoType, pojo2Type))
.isInstanceOf(InvalidSemanticAnnotationException.class);
} |
@Override
protected void runAfterCatalogReady() {
try {
process();
} catch (Throwable e) {
LOG.warn("Failed to process one round of RoutineLoadScheduler", e);
}
} | @Test
public void testEmptyTaskQueue(@Injectable RoutineLoadMgr routineLoadManager) {
RoutineLoadTaskScheduler routineLoadTaskScheduler = new RoutineLoadTaskScheduler(routineLoadManager);
new Expectations() {
{
routineLoadManager.getClusterIdleSlotNum();
result = 1;
times = 1;
}
};
routineLoadTaskScheduler.runAfterCatalogReady();
} |
@VisibleForTesting
static SingleSegmentAssignment getNextSingleSegmentAssignment(Map<String, String> currentInstanceStateMap,
Map<String, String> targetInstanceStateMap, int minAvailableReplicas, boolean lowDiskMode,
Map<String, Integer> numSegmentsToOffloadMap, Map<Pair<Set<String>, Set<String>>, Set<String>> assignmentMap) {
Map<String, String> nextInstanceStateMap = new TreeMap<>();
// Assign the segment the same way as other segments if the current and target instances are the same. We need this
// to guarantee the mirror servers for replica-group based routing strategies.
Set<String> currentInstances = currentInstanceStateMap.keySet();
Set<String> targetInstances = targetInstanceStateMap.keySet();
Pair<Set<String>, Set<String>> assignmentKey = Pair.of(currentInstances, targetInstances);
Set<String> instancesToAssign = assignmentMap.get(assignmentKey);
if (instancesToAssign != null) {
Set<String> availableInstances = new TreeSet<>();
for (String instanceName : instancesToAssign) {
String currentInstanceState = currentInstanceStateMap.get(instanceName);
String targetInstanceState = targetInstanceStateMap.get(instanceName);
if (currentInstanceState != null) {
availableInstances.add(instanceName);
// Use target instance state if available in case the state changes
nextInstanceStateMap.put(instanceName,
targetInstanceState != null ? targetInstanceState : currentInstanceState);
} else {
nextInstanceStateMap.put(instanceName, targetInstanceState);
}
}
return new SingleSegmentAssignment(nextInstanceStateMap, availableInstances);
}
// Add all the common instances
// Use target instance state in case the state changes
for (Map.Entry<String, String> entry : targetInstanceStateMap.entrySet()) {
String instanceName = entry.getKey();
if (currentInstanceStateMap.containsKey(instanceName)) {
nextInstanceStateMap.put(instanceName, entry.getValue());
}
}
// Add current instances until the min available replicas achieved
int numInstancesToKeep = minAvailableReplicas - nextInstanceStateMap.size();
if (numInstancesToKeep > 0) {
// Sort instances by number of segments to offload, and keep the ones with the least segments to offload
List<Triple<String, String, Integer>> instancesInfo =
getSortedInstancesOnNumSegmentsToOffload(currentInstanceStateMap, nextInstanceStateMap,
numSegmentsToOffloadMap);
numInstancesToKeep = Integer.min(numInstancesToKeep, instancesInfo.size());
for (int i = 0; i < numInstancesToKeep; i++) {
Triple<String, String, Integer> instanceInfo = instancesInfo.get(i);
nextInstanceStateMap.put(instanceInfo.getLeft(), instanceInfo.getMiddle());
}
}
Set<String> availableInstances = new TreeSet<>(nextInstanceStateMap.keySet());
// After achieving the min available replicas, when low disk mode is enabled, only add new instances when all
// current instances exist in the next assignment.
// We want to first drop the extra instances as one step, then add the target instances as another step to avoid the
// case where segments are first added to the instance before other segments are dropped from the instance, which
// might cause server running out of disk. Note that even if segment addition and drop happen in the same step,
// there is no guarantee that server process the segment drop before the segment addition.
if (!lowDiskMode || currentInstanceStateMap.size() == nextInstanceStateMap.size()) {
int numInstancesToAdd = targetInstanceStateMap.size() - nextInstanceStateMap.size();
if (numInstancesToAdd > 0) {
// Sort instances by number of segments to offload, and add the ones with the least segments to offload
List<Triple<String, String, Integer>> instancesInfo =
getSortedInstancesOnNumSegmentsToOffload(targetInstanceStateMap, nextInstanceStateMap,
numSegmentsToOffloadMap);
for (int i = 0; i < numInstancesToAdd; i++) {
Triple<String, String, Integer> instanceInfo = instancesInfo.get(i);
nextInstanceStateMap.put(instanceInfo.getLeft(), instanceInfo.getMiddle());
}
}
}
assignmentMap.put(assignmentKey, nextInstanceStateMap.keySet());
return new SingleSegmentAssignment(nextInstanceStateMap, availableInstances);
} | @Test
public void testOneMinAvailableReplicasWithLowDiskMode() {
// With 2 common instances, first assignment should keep the common instances and remove the not common instance
Map<String, String> currentInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "host3"), ONLINE);
Map<String, String> targetInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "host4"), ONLINE);
TableRebalancer.SingleSegmentAssignment assignment =
getNextSingleSegmentAssignment(currentInstanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2"), ONLINE));
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host1", "host2")));
// Second assignment should be the same as target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, targetInstanceStateMap);
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host1", "host2")));
// With 1 common instance, first assignment should keep the common instance and remove the not common instances
targetInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host4", "host5"), ONLINE);
assignment = getNextSingleSegmentAssignment(currentInstanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, Collections.singletonMap("host1", ONLINE));
assertEquals(assignment._availableInstances, Collections.singletonList("host1"));
// Second assignment should be the same as target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, targetInstanceStateMap);
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Without common instance, fist assignment should keep 1 instance from current assignment
targetInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host4", "host5", "host6"), ONLINE);
assignment = getNextSingleSegmentAssignment(currentInstanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, Collections.singletonMap("host1", ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Second assignment should add 2 instances from target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host4", "host5"), ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Third assignment should remove the old instance from current assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host4", "host5"), ONLINE));
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host4", "host5")));
// Fourth assignment should make the assignment the same as target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, targetInstanceStateMap);
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host4", "host5")));
// With increasing number of replicas, fist assignment should keep 1 instance from current assignment
targetInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host4", "host5", "host6", "host7"), ONLINE);
assignment = getNextSingleSegmentAssignment(currentInstanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, Collections.singletonMap("host1", ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Second assignment should add 3 instances from target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host4", "host5", "host6"), ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Third assignment should remove the old instance from current assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host4", "host5", "host6"), ONLINE));
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host4", "host5", "host6")));
// Fourth assignment should make the assignment the same as target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, targetInstanceStateMap);
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host4", "host5", "host6")));
// With decreasing number of replicas, fist assignment should keep 1 instance from current assignment
currentInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "host3", "host4"), ONLINE);
targetInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host5", "host6", "host7"), ONLINE);
assignment = getNextSingleSegmentAssignment(currentInstanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, Collections.singletonMap("host1", ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Second assignment should add 2 instances from target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host5", "host6"), ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Third assignment should remove the old instance from current assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host5", "host6"), ONLINE));
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host5", "host6")));
// Fourth assignment should make the assignment the same as target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, targetInstanceStateMap);
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host5", "host6")));
// With increasing from 1 replica, fist assignment should keep the instance from current assignment, and add 2
// instances from target assignment
currentInstanceStateMap = SegmentAssignmentUtils.getInstanceStateMap(Collections.singletonList("host1"), ONLINE);
targetInstanceStateMap =
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host2", "host3", "host4"), ONLINE);
assignment = getNextSingleSegmentAssignment(currentInstanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "host3"), ONLINE));
assertEquals(assignment._availableInstances, Collections.singleton("host1"));
// Second assignment should remove the old instance from current assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap,
SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host2", "host3"), ONLINE));
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host2", "host3")));
// Third assignment should make the assignment the same as target assignment
assignment = getNextSingleSegmentAssignment(assignment._instanceStateMap, targetInstanceStateMap, 1, true);
assertEquals(assignment._instanceStateMap, targetInstanceStateMap);
assertEquals(assignment._availableInstances, new TreeSet<>(Arrays.asList("host2", "host3")));
} |
static Time toTime(final JsonNode object) {
if (object instanceof NumericNode) {
return returnTimeOrThrow(object.asLong());
}
if (object instanceof TextNode) {
try {
return returnTimeOrThrow(Long.parseLong(object.textValue()));
} catch (final NumberFormatException e) {
throw failedStringCoercionException(SqlBaseType.TIME);
}
}
throw invalidConversionException(object, SqlBaseType.TIME);
} | @Test(expected = IllegalArgumentException.class)
public void shouldFailWhenConvertingIncompatibleTime() {
JsonSerdeUtils.toTime(JsonNodeFactory.instance.booleanNode(false));
} |
public static boolean isChineseName(CharSequence value) {
return isMatchRegex(PatternPool.CHINESE_NAME, value);
} | @Test
public void isChineseNameTest() {
assertTrue(Validator.isChineseName("阿卜杜尼亚孜·毛力尼亚孜"));
assertFalse(Validator.isChineseName("阿卜杜尼亚孜./毛力尼亚孜"));
assertTrue(Validator.isChineseName("段正淳"));
assertFalse(Validator.isChineseName("孟 伟"));
assertFalse(Validator.isChineseName("李"));
assertFalse(Validator.isChineseName("连逍遥0"));
assertFalse(Validator.isChineseName("SHE"));
} |
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@PutMapping(IMAGE_URL + "/info")
public TbResourceInfo updateImageInfo(@Parameter(description = IMAGE_TYPE_PARAM_DESCRIPTION, schema = @Schema(allowableValues = {"tenant", "system"}), required = true)
@PathVariable String type,
@Parameter(description = IMAGE_KEY_PARAM_DESCRIPTION, required = true)
@PathVariable String key,
@RequestBody TbResourceInfo request) throws ThingsboardException {
TbResourceInfo imageInfo = checkImageInfo(type, key, Operation.WRITE);
TbResourceInfo newImageInfo = new TbResourceInfo(imageInfo);
newImageInfo.setTitle(request.getTitle());
return tbImageService.save(newImageInfo, imageInfo, getCurrentUser());
} | @Test
public void testUpdateImageInfo() throws Exception {
String filename = "my_png_image.png";
TbResourceInfo imageInfo = uploadImage(HttpMethod.POST, "/api/image", filename, "image/png", PNG_IMAGE);
ImageDescriptor imageDescriptor = imageInfo.getDescriptor(ImageDescriptor.class);
assertThat(imageInfo.getTitle()).isEqualTo(filename);
assertThat(imageInfo.getResourceKey()).isEqualTo(filename);
assertThat(imageInfo.getFileName()).isEqualTo(filename);
String newTitle = "My PNG image";
TbResourceInfo newImageInfo = new TbResourceInfo(imageInfo);
newImageInfo.setTitle(newTitle);
newImageInfo.setDescriptor(JacksonUtil.newObjectNode());
newImageInfo = doPut("/api/images/tenant/" + filename + "/info", newImageInfo, TbResourceInfo.class);
assertThat(newImageInfo.getTitle()).isEqualTo(newTitle);
assertThat(newImageInfo.getDescriptor(ImageDescriptor.class)).isEqualTo(imageDescriptor);
assertThat(newImageInfo.getResourceKey()).isEqualTo(imageInfo.getResourceKey());
assertThat(newImageInfo.getPublicResourceKey()).isEqualTo(newImageInfo.getPublicResourceKey());
} |
public void cacheRuleData(final String path, final RuleData ruleData, final int initialCapacity, final long maximumSize) {
MapUtils.computeIfAbsent(RULE_DATA_MAP, ruleData.getPluginName(), map ->
new WindowTinyLFUMap<>(initialCapacity, maximumSize, Boolean.FALSE)).put(path, ruleData);
} | @Test
public void testCacheRuleData() throws NoSuchFieldException, IllegalAccessException {
RuleData cacheRuleData = RuleData.builder().id("1").pluginName(mockPluginName1).sort(1).build();
MatchDataCache.getInstance().cacheRuleData(path1, cacheRuleData, 100, 100);
ConcurrentHashMap<String, WindowTinyLFUMap<String, RuleData>> ruleMap = getFieldByName(ruleMapStr);
assertEquals(cacheRuleData, ruleMap.get(mockPluginName1).get(path1));
ruleMap.clear();
} |
public static String UU32(java.util.UUID uu) {
StringBuilder sb = new StringBuilder();
long m = uu.getMostSignificantBits();
long l = uu.getLeastSignificantBits();
for (int i = 0; i < 13; i++) {
sb.append(_UU32[(int) (m >> ((13 - i - 1) * 5)) & 31]);
}
for (int i = 0; i < 13; i++) {
sb.append(_UU32[(int) (l >> ((13 - i - 1)) * 5) & 31]);
}
return sb.toString();
} | @Test
public void testUU32(){
String uu32 = UUID.UU32();
System.out.println(uu32);
} |
@Override
public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListener listener)
throws Http2Exception {
if (readError) {
input.skipBytes(input.readableBytes());
return;
}
try {
do {
if (readingHeaders && !preProcessFrame(input)) {
return;
}
// The header is complete, fall into the next case to process the payload.
// This is to ensure the proper handling of zero-length payloads. In this
// case, we don't want to loop around because there may be no more data
// available, causing us to exit the loop. Instead, we just want to perform
// the first pass at payload processing now.
// Wait until the entire payload has been read.
if (input.readableBytes() < payloadLength) {
return;
}
// Slice to work only on the frame being read
ByteBuf framePayload = input.readSlice(payloadLength);
// We have consumed the data for this frame, next time we read,
// we will be expecting to read a new frame header.
readingHeaders = true;
verifyFrameState();
processPayloadState(ctx, framePayload, listener);
} while (input.isReadable());
} catch (Http2Exception e) {
readError = !Http2Exception.isStreamError(e);
throw e;
} catch (RuntimeException e) {
readError = true;
throw e;
} catch (Throwable cause) {
readError = true;
PlatformDependent.throwException(cause);
}
} | @Test
public void failedWhenSettingsFrameOnNonZeroStream() throws Http2Exception {
final ByteBuf input = Unpooled.buffer();
try {
writeFrameHeader(input, 6, SETTINGS, new Http2Flags(), 1);
input.writeShort(SETTINGS_MAX_HEADER_LIST_SIZE);
input.writeInt(1024);
Http2Exception ex = assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
frameReader.readFrame(ctx, input, listener);
}
});
assertFalse(ex instanceof Http2Exception.StreamException);
} finally {
input.release();
}
} |
public Document process(Document input) throws TransformerException {
Document doc = Xml.copyDocument(input);
Document document = buildProperties(doc);
applyProperties(document.getDocumentElement());
return document;
} | @Test
public void testWarnIfDuplicatePropertyForSameEnvironment() throws TransformerException {
String input = """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<services xmlns:deploy="vespa" xmlns:preprocess="properties" version="1.0">
<preprocess:properties>
<slobrok.port>4099</slobrok.port>
<slobrok.port>5000</slobrok.port>
<redundancy>2</redundancy>
</preprocess:properties>
<admin version="2.0">
<adminserver hostalias="node0"/>
<slobroks>
<slobrok hostalias="node1" baseport="${slobrok.port}"/>
</slobroks>
</admin>
</services>""";
// Should get the last defined value
String expected = """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<services xmlns:deploy="vespa" xmlns:preprocess="properties" version="1.0">
<admin version="2.0">
<adminserver hostalias="node0"/>
<slobroks>
<slobrok hostalias="node1" baseport="5000"/>
</slobroks>
</admin>
</services>""";
Document inputDoc = Xml.getDocument(new StringReader(input));
Document newDoc = new PropertiesProcessor().process(inputDoc);
TestBase.assertDocument(expected, newDoc);
} |
Converter<E> compile() {
head = tail = null;
for (Node n = top; n != null; n = n.next) {
switch (n.type) {
case Node.LITERAL:
addToList(new LiteralConverter<E>((String) n.getValue()));
break;
case Node.COMPOSITE_KEYWORD:
CompositeNode cn = (CompositeNode) n;
CompositeConverter<E> compositeConverter = createCompositeConverter(cn);
if(compositeConverter == null) {
addError("Failed to create converter for [%"+cn.getValue()+"] keyword");
addToList(new LiteralConverter<E>("%PARSER_ERROR["+cn.getValue()+"]"));
break;
}
compositeConverter.setFormattingInfo(cn.getFormatInfo());
compositeConverter.setOptionList(cn.getOptions());
Compiler<E> childCompiler = new Compiler<E>(cn.getChildNode(),
converterMap);
childCompiler.setContext(context);
Converter<E> childConverter = childCompiler.compile();
compositeConverter.setChildConverter(childConverter);
addToList(compositeConverter);
break;
case Node.SIMPLE_KEYWORD:
SimpleKeywordNode kn = (SimpleKeywordNode) n;
DynamicConverter<E> dynaConverter = createConverter(kn);
if (dynaConverter != null) {
dynaConverter.setFormattingInfo(kn.getFormatInfo());
dynaConverter.setOptionList(kn.getOptions());
addToList(dynaConverter);
} else {
// if the appropriate dynaconverter cannot be found, then replace
// it with a dummy LiteralConverter indicating an error.
Converter<E> errConveter = new LiteralConverter<E>("%PARSER_ERROR["
+ kn.getValue() + "]");
addStatus(new ErrorStatus("[" + kn.getValue()
+ "] is not a valid conversion word", this));
addToList(errConveter);
}
}
}
return head;
} | @Test
public void testWithNopEscape() throws Exception {
{
Parser<Object> p = new Parser<Object>("xyz %hello\\_world");
p.setContext(context);
Node t = p.parse();
Converter<Object> head = p.compile(t, converterMap);
String result = write(head, new Object());
assertEquals("xyz Helloworld", result);
}
} |
@Override
public void onDraw(Canvas canvas) {
final boolean keyboardChanged = mKeyboardChanged;
super.onDraw(canvas);
// switching animation
if (mAnimationLevel != AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) {
startAnimation(mInAnimation);
mInAnimation = null;
}
if (mGestureTypingPathShouldBeDrawn) {
mGestureDrawingHelper.draw(canvas);
}
// showing any requested watermark
float watermarkX = mWatermarkEdgeX;
final float watermarkY = getHeight() - mWatermarkDimen - mWatermarkMargin;
for (Drawable watermark : mWatermarks) {
watermarkX -= (mWatermarkDimen + mWatermarkMargin);
canvas.translate(watermarkX, watermarkY);
watermark.draw(canvas);
canvas.translate(-watermarkX, -watermarkY);
}
} | @Test
public void testDoesNotAddExtraDrawIfAnimationsAreOff() {
SharedPrefsHelper.setPrefsValue(R.string.settings_key_tweak_animations_level, "none");
ExtraDraw mockDraw1 = Mockito.mock(ExtraDraw.class);
Mockito.doReturn(true).when(mockDraw1).onDraw(any(), any(), same(mViewUnderTest));
Robolectric.getForegroundThreadScheduler().pause();
Assert.assertFalse(Robolectric.getForegroundThreadScheduler().areAnyRunnable());
mViewUnderTest.addExtraDraw(mockDraw1);
Mockito.verify(mockDraw1, Mockito.never()).onDraw(any(), any(), any());
Assert.assertEquals(0, Robolectric.getForegroundThreadScheduler().size());
} |
@Override
public String toString() {
return "MetadataVersionChange(" +
"oldVersion=" + oldVersion +
", newVersion=" + newVersion +
")";
} | @Test
public void testMetadataVersionChangeExceptionToString() {
assertEquals("org.apache.kafka.image.MetadataVersionChangeException: The metadata.version " +
"is changing from 3.0-IV1 to 3.3-IV0",
new MetadataVersionChangeException(CHANGE_3_0_IV1_TO_3_3_IV0).toString());
assertEquals("org.apache.kafka.image.MetadataVersionChangeException: The metadata.version " +
"is changing from 3.3-IV0 to 3.0-IV1",
new MetadataVersionChangeException(CHANGE_3_3_IV0_TO_3_0_IV1).toString());
} |
@Override
public boolean onTouchEvent(@NonNull MotionEvent nativeMotionEvent) {
if (mKeyboard == null) {
// I mean, if there isn't any keyboard I'm handling, what's the point?
return false;
}
final int action = nativeMotionEvent.getActionMasked();
final int pointerCount = nativeMotionEvent.getPointerCount();
if (pointerCount > 1) {
mLastTimeHadTwoFingers =
SystemClock.elapsedRealtime(); // marking the time. Read isAtTwoFingersState()
}
if (mTouchesAreDisabledTillLastFingerIsUp) {
if (!areTouchesDisabled(nativeMotionEvent) /*this means it was just reset*/) {
mTouchesAreDisabledTillLastFingerIsUp = false;
// continue with onTouchEvent flow.
if (action != MotionEvent.ACTION_DOWN) {
// swallowing the event.
// in case this is a DOWN event, we do want to pass it
return true;
}
} else {
// swallowing touch event until we reset mTouchesAreDisabledTillLastFingerIsUp
return true;
}
}
final long eventTime = nativeMotionEvent.getEventTime();
final int index = nativeMotionEvent.getActionIndex();
final int id = nativeMotionEvent.getPointerId(index);
final int x = (int) nativeMotionEvent.getX(index);
final int y = (int) nativeMotionEvent.getY(index);
if (mKeyPressTimingHandler.isInKeyRepeat()) {
// It will keep being in the key repeating mode while the key is
// being pressed.
if (action == MotionEvent.ACTION_MOVE) {
return true;
}
final PointerTracker tracker = getPointerTracker(id);
// Key repeating timer will be canceled if 2 or more keys are in
// action, and current
// event (UP or DOWN) is non-modifier key.
if (pointerCount > 1 && !tracker.isModifier()) {
mKeyPressTimingHandler.cancelKeyRepeatTimer();
}
// Up event will pass through.
}
if (action == MotionEvent.ACTION_MOVE) {
for (int i = 0; i < pointerCount; i++) {
PointerTracker tracker = getPointerTracker(nativeMotionEvent.getPointerId(i));
tracker.onMoveEvent(
(int) nativeMotionEvent.getX(i), (int) nativeMotionEvent.getY(i), eventTime);
}
} else {
PointerTracker tracker = getPointerTracker(id);
sendOnXEvent(action, eventTime, x, y, tracker);
}
return true;
} | @Test
public void testRegularPressKeyPressState() {
final Keyboard.Key key = findKey('f');
KeyDrawableStateProvider provider =
new KeyDrawableStateProvider(
R.attr.key_type_function,
R.attr.key_type_action,
R.attr.action_done,
R.attr.action_search,
R.attr.action_go);
Assert.assertArrayEquals(provider.KEY_STATE_NORMAL, key.getCurrentDrawableState(provider));
Point keyPoint = ViewTestUtils.getKeyCenterPoint(key);
ViewTestUtils.navigateFromTo(mUnderTest, keyPoint, keyPoint, 60, true, false);
Assert.assertArrayEquals(provider.KEY_STATE_PRESSED, key.getCurrentDrawableState(provider));
mUnderTest.onTouchEvent(
MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP,
keyPoint.x,
keyPoint.y,
0));
Assert.assertArrayEquals(provider.KEY_STATE_NORMAL, key.getCurrentDrawableState(provider));
} |
public boolean sendHeartbeatToBroker(long id, String brokerName, String addr) {
if (this.lockHeartbeat.tryLock()) {
final HeartbeatData heartbeatDataWithSub = this.prepareHeartbeatData(false);
final boolean producerEmpty = heartbeatDataWithSub.getProducerDataSet().isEmpty();
final boolean consumerEmpty = heartbeatDataWithSub.getConsumerDataSet().isEmpty();
if (producerEmpty && consumerEmpty) {
log.warn("sendHeartbeatToBroker sending heartbeat, but no consumer and no producer. [{}]", this.clientId);
return false;
}
try {
if (clientConfig.isUseHeartbeatV2()) {
int currentHeartbeatFingerprint = heartbeatDataWithSub.computeHeartbeatFingerprint();
heartbeatDataWithSub.setHeartbeatFingerprint(currentHeartbeatFingerprint);
HeartbeatData heartbeatDataWithoutSub = this.prepareHeartbeatData(true);
heartbeatDataWithoutSub.setHeartbeatFingerprint(currentHeartbeatFingerprint);
return this.sendHeartbeatToBrokerV2(id, brokerName, addr, heartbeatDataWithSub, heartbeatDataWithoutSub, currentHeartbeatFingerprint);
} else {
return this.sendHeartbeatToBroker(id, brokerName, addr, heartbeatDataWithSub);
}
} catch (final Exception e) {
log.error("sendHeartbeatToAllBroker exception", e);
} finally {
this.lockHeartbeat.unlock();
}
} else {
log.warn("lock heartBeat, but failed. [{}]", this.clientId);
}
return false;
} | @Test
public void testSendHeartbeatToBrokerV1() {
consumerTable.put(group, createMQConsumerInner());
assertTrue(mqClientInstance.sendHeartbeatToBroker(0L, defaultBroker, defaultBrokerAddr));
} |
public ColumnConstraints getConstraints() {
return constraints;
} | @Test
public void shouldReturnKeyConstraint() {
// Given:
final TableElement valueElement = new TableElement(NAME, new Type(SqlTypes.STRING),
KEY_CONSTRAINT);
// Then:
assertThat(valueElement.getConstraints(), is(KEY_CONSTRAINT));
} |
public static Builder withSchema(Schema schema) {
return new Builder(schema);
} | @Test
public void testCreateWithCollectionNames() {
Schema type =
Stream.of(
Schema.Field.of("f_array", FieldType.array(FieldType.INT32)),
Schema.Field.of("f_iterable", FieldType.iterable(FieldType.INT32)),
Schema.Field.of("f_map", FieldType.map(FieldType.STRING, FieldType.STRING)))
.collect(toSchema());
Row row =
Row.withSchema(type)
.withFieldValue("f_array", ImmutableList.of(1, 2, 3))
.withFieldValue("f_iterable", ImmutableList.of(1, 2, 3))
.withFieldValue("f_map", ImmutableMap.of("one", "two"))
.build();
Row expectedRow =
Row.withSchema(type)
.addValues(
ImmutableList.of(1, 2, 3), ImmutableList.of(1, 2, 3), ImmutableMap.of("one", "two"))
.build();
assertEquals(expectedRow, row);
} |
@Override
public boolean postpone(
String queueName, String messageId, int priority, long postponeDurationInSeconds) {
remove(queueName, messageId);
push(queueName, messageId, priority, postponeDurationInSeconds);
return true;
} | @Test
public void testPostpone() {
String queueName = "test-queue";
String id = "abcd-1234-defg-5678";
assertTrue(queueDao.postpone(queueName, id, 0, 0));
assertEquals(1, internalQueue.size());
assertEquals(1, internalQueue.get(queueName).size());
assertEquals(id, internalQueue.get(queueName).peek());
} |
Single<Post> save(Post post) {
Post saved = Post.builder().id(UUID.randomUUID()).title(post.getTitle()).content(post.getContent()).build();
DATA.add(saved);
return Single.just(saved);
} | @Test
void save() {
var testObserver = new TestObserver<Post>();
this.posts.save(Post.builder().title("test title").content("test content").build())
.subscribe(testObserver);
testObserver.assertComplete();
testObserver.assertNoErrors();
testObserver.assertValue(p -> null != p.getId());
} |
@Override
public void render(Node node, Appendable output) {
RendererContext context = new RendererContext(new MarkdownWriter(output));
context.render(node);
} | @Test
public void testBulletListItemsFromAst() {
var doc = new Document();
var list = new BulletList();
var item = new ListItem();
item.appendChild(new Text("Test"));
list.appendChild(item);
doc.appendChild(list);
assertRendering("", "- Test\n", render(doc));
list.setMarker("*");
assertRendering("", "* Test\n", render(doc));
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i = 0; i < ntrees; i++) {
base += shrinkage * trees[i].predict(xj);
prediction[i][j] = base;
}
}
return prediction;
} | @Test
public void testKin8nmHuber() {
test(Loss.huber(0.9), "kin8nm", Kin8nm.formula, Kin8nm.data, 0.1795);
} |
public void resetOffsetsTo(final Consumer<byte[], byte[]> client,
final Set<TopicPartition> inputTopicPartitions,
final Long offset) {
final Map<TopicPartition, Long> endOffsets = client.endOffsets(inputTopicPartitions);
final Map<TopicPartition, Long> beginningOffsets = client.beginningOffsets(inputTopicPartitions);
final Map<TopicPartition, Long> topicPartitionsAndOffset = new HashMap<>(inputTopicPartitions.size());
for (final TopicPartition topicPartition : inputTopicPartitions) {
topicPartitionsAndOffset.put(topicPartition, offset);
}
final Map<TopicPartition, Long> validatedTopicPartitionsAndOffset =
checkOffsetRange(topicPartitionsAndOffset, beginningOffsets, endOffsets);
for (final TopicPartition topicPartition : inputTopicPartitions) {
client.seek(topicPartition, validatedTopicPartitionsAndOffset.get(topicPartition));
}
} | @Test
public void testResetToSpecificOffsetWhenBeforeBeginningOffset() {
final Map<TopicPartition, Long> endOffsets = new HashMap<>();
endOffsets.put(topicPartition, 4L);
consumer.updateEndOffsets(endOffsets);
final Map<TopicPartition, Long> beginningOffsets = new HashMap<>();
beginningOffsets.put(topicPartition, 3L);
consumer.updateBeginningOffsets(beginningOffsets);
streamsResetter.resetOffsetsTo(consumer, inputTopicPartitions, 2L);
final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500));
assertEquals(2, records.count());
} |
@Override
public boolean needLoad() {
try {
Class.forName("com.alipay.lookout.spi.MetricsImporterLocator");
return true;
} catch (Exception e) {
return false;
}
} | @Test
public void testNeedLoad() {
LookoutModule lookoutModule = new LookoutModule();
Assert.assertEquals(true, lookoutModule.needLoad());
} |
@Override
public boolean match(final String rule) {
return rule.matches("^phone$");
} | @Test
void match() {
assertTrue(generator.match("phone"));
assertFalse(generator.match("mobile"));
} |
@Override
@NonNull
public Predicate<E> convert(SelectorCriteria criteria) {
return ext -> {
var labels = ext.getMetadata().getLabels();
switch (criteria.operator()) {
case Equals -> {
if (labels == null || !labels.containsKey(criteria.key())) {
return false;
}
return criteria.values().contains(labels.get(criteria.key()));
}
case NotEquals -> {
if (labels == null || !labels.containsKey(criteria.key())) {
return false;
}
return !criteria.values().contains(labels.get(criteria.key()));
}
case NotExist -> {
return labels == null || !labels.containsKey(criteria.key());
}
case Exist -> {
return labels != null && labels.containsKey(criteria.key());
}
default -> {
return false;
}
}
};
} | @Test
void shouldConvertNotEqualsCorrectly() {
var criteria = new SelectorCriteria("name", Operator.NotEquals, Set.of("value1", "value2"));
var predicate = convert.convert(criteria);
assertNotNull(predicate);
var fakeExt = new FakeExtension();
var metadata = new Metadata();
fakeExt.setMetadata(metadata);
assertFalse(predicate.test(fakeExt));
metadata.setLabels(Map.of("name", "value"));
assertTrue(predicate.test(fakeExt));
metadata.setLabels(Map.of("name", "value1"));
assertFalse(predicate.test(fakeExt));
metadata.setLabels(Map.of("name", "value2"));
assertFalse(predicate.test(fakeExt));
} |
static long toLong(final JsonNode object) {
if (object instanceof NumericNode) {
return object.asLong();
}
if (object instanceof TextNode) {
try {
return Long.parseLong(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionException(SqlBaseType.BIGINT);
}
}
throw invalidConversionException(object, SqlBaseType.BIGINT);
} | @Test
public void shouldConvertToLongCorrectly() {
final Long l = JsonSerdeUtils.toLong(JsonNodeFactory.instance.numberNode(1L));
assertThat(l, equalTo(1L));
} |
public static ExpressionTree parseFilterTree(String filter) throws MetaException {
return PartFilterParser.parseFilter(filter);
} | @Test
public void testDateColumnNameKeyword() throws MetaException {
MetaException exception = assertThrows(MetaException.class,
() -> PartFilterExprUtil.parseFilterTree("date='1990-11-10'"));
assertTrue(exception.getMessage().contains("Error parsing partition filter"));
} |
public static Number jsToNumber( Object value, String classType ) {
if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
return null;
} else if ( classType.equalsIgnoreCase( JS_NATIVE_JAVA_OBJ ) ) {
try {
// Is it a java Value class ?
Value v = (Value) Context.jsToJava( value, Value.class );
return v.getNumber();
} catch ( Exception e ) {
String string = Context.toString( value );
return Double.parseDouble( Const.trim( string ) );
}
} else if ( classType.equalsIgnoreCase( JS_NATIVE_NUM ) ) {
Number nb = Context.toNumber( value );
return nb.doubleValue();
} else {
Number nb = (Number) value;
return nb.doubleValue();
}
} | @Test
public void jsToNumber_Undefined() throws Exception {
assertNull( JavaScriptUtils.jsToNumber( null, UNDEFINED ) );
} |
@Nullable
public Supplier<? extends SocketAddress> bindAddressSupplier() {
return bindAddressSupplier;
} | @Test
void bindAddressSupplier() {
assertThat(builder.build().bindAddressSupplier()).isNull();
Supplier<SocketAddress> addressSupplier = () -> new InetSocketAddress("localhost", 9527);
builder.bindAddressSupplier(addressSupplier);
assertThat(builder.build().bindAddressSupplier()).isEqualTo(addressSupplier);
} |
public static String from(Query query) {
if (query instanceof SqmInterpretationsKey.InterpretationsKeySource &&
query instanceof QueryImplementor &&
query instanceof QuerySqmImpl) {
QueryInterpretationCache.Key cacheKey = SqmInterpretationsKey.createInterpretationsKey((SqmInterpretationsKey.InterpretationsKeySource) query);
QuerySqmImpl querySqm = (QuerySqmImpl) query;
Supplier buildSelectQueryPlan = () -> ReflectionUtils.invokeMethod(querySqm, "buildSelectQueryPlan");
SelectQueryPlan plan = cacheKey != null ? ((QueryImplementor) query).getSession().getFactory().getQueryEngine()
.getInterpretationCache()
.resolveSelectQueryPlan(cacheKey, buildSelectQueryPlan) :
(SelectQueryPlan) buildSelectQueryPlan.get();
if (plan instanceof ConcreteSqmSelectQueryPlan) {
ConcreteSqmSelectQueryPlan selectQueryPlan = (ConcreteSqmSelectQueryPlan) plan;
Object cacheableSqmInterpretation = ReflectionUtils.getFieldValueOrNull(selectQueryPlan, "cacheableSqmInterpretation");
if (cacheableSqmInterpretation == null) {
DomainQueryExecutionContext domainQueryExecutionContext = DomainQueryExecutionContext.class.cast(querySqm);
cacheableSqmInterpretation = ReflectionUtils.invokeStaticMethod(
ReflectionUtils.getMethod(
ConcreteSqmSelectQueryPlan.class,
"buildCacheableSqmInterpretation",
SqmSelectStatement.class,
DomainParameterXref.class,
DomainQueryExecutionContext.class
),
ReflectionUtils.getFieldValueOrNull(selectQueryPlan, "sqm"),
ReflectionUtils.getFieldValueOrNull(selectQueryPlan, "domainParameterXref"),
domainQueryExecutionContext
);
}
if (cacheableSqmInterpretation != null) {
JdbcSelect jdbcSelect = ReflectionUtils.getFieldValueOrNull(cacheableSqmInterpretation, "jdbcSelect");
if (jdbcSelect != null) {
return jdbcSelect.getSql();
}
}
}
}
return ReflectionUtils.invokeMethod(query, "getQueryString");
} | @Test
public void testCriteriaAPI() {
doInJPA(entityManager -> {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class);
Root<PostComment> postComment = criteria.from(PostComment.class);
Join<PostComment, Post> post = postComment.join("post");
criteria.where(
builder.like(post.get("title"), "%Java%")
);
criteria.orderBy(
builder.asc(postComment.get("id"))
);
Query criteriaQuery = entityManager.createQuery(criteria);
String sql = SQLExtractor.from(criteriaQuery);
assertNotNull(sql);
LOGGER.info(
"The Criteria API query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]",
criteriaQuery.unwrap(org.hibernate.query.Query.class).getQueryString(),
sql
);
});
} |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
metadata.set(Metadata.CONTENT_TYPE, "application/rtf");
TaggedInputStream tagged = new TaggedInputStream(stream);
try {
XHTMLContentHandler xhtmlHandler = new XHTMLContentHandler(handler, metadata);
RTFEmbObjHandler embObjHandler =
new RTFEmbObjHandler(xhtmlHandler, metadata, context, getMemoryLimitInKb());
final TextExtractor ert = new TextExtractor(xhtmlHandler, metadata, embObjHandler);
ert.setIgnoreListMarkup(ignoreListMarkup);
ert.extract(stream);
} catch (IOException e) {
tagged.throwIfCauseOf(e);
throw new TikaException("Error parsing an RTF document", e);
}
} | @Test
public void testEmbeddedLinkedDocument() throws Exception {
Set<MediaType> skipTypes = new HashSet<>();
skipTypes.add(MediaType.parse("image/emf"));
skipTypes.add(MediaType.parse("image/wmf"));
TrackingHandler tracker = new TrackingHandler(skipTypes);
try (TikaInputStream tis = TikaInputStream
.get(getResourceAsStream("/test-documents/testRTFEmbeddedLink.rtf"))) {
ContainerExtractor ex = new ParserContainerExtractor();
assertEquals(true, ex.isSupported(tis));
ex.extract(tis, ex, tracker);
}
//should gracefully skip link and not throw NPE, IOEx, etc
assertEquals(0, tracker.filenames.size());
tracker = new TrackingHandler();
try (TikaInputStream tis = TikaInputStream
.get(getResourceAsStream("/test-documents/testRTFEmbeddedLink.rtf"))) {
ContainerExtractor ex = new ParserContainerExtractor();
assertEquals(true, ex.isSupported(tis));
ex.extract(tis, ex, tracker);
}
//should gracefully skip link and not throw NPE, IOEx, etc
assertEquals(2, tracker.filenames.size());
} |
public static ILogger noLogger() {
return new NoLogFactory.NoLogger();
} | @Test
public void noLogger() {
assertInstanceOf(NoLogFactory.NoLogger.class, Logger.noLogger());
} |
public int max() {
return size > 0 ? data[size - 1] : 0;
} | @Test public void max() {
SortedIntList l = new SortedIntList(5);
assertEquals(0, l.max());
l.add(1);
assertEquals(1, l.max());
l.add(5);
assertEquals(5, l.max());
l.add(10);
assertEquals(10, l.max());
} |
@Override
public ProviderInfo doSelect(SofaRequest invocation, List<ProviderInfo> providerInfos) {
String localhost = SystemInfo.getLocalHost();
if (StringUtils.isEmpty(localhost)) {
return super.doSelect(invocation, providerInfos);
}
List<ProviderInfo> localProviderInfo = new ArrayList<ProviderInfo>();
for (ProviderInfo providerInfo : providerInfos) { // 解析IP,看是否和本地一致
if (localhost.equals(providerInfo.getHost())) {
localProviderInfo.add(providerInfo);
}
}
if (CommonUtils.isNotEmpty(localProviderInfo)) { // 命中本机的服务端
return super.doSelect(invocation, localProviderInfo);
} else { // 没有命中本机上的服务端
return super.doSelect(invocation, providerInfos);
}
} | @Test
public void doSelect() throws Exception {
LocalPreferenceLoadBalancer loadBalancer = new LocalPreferenceLoadBalancer(null);
Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
int size = 20;
int total = 100000;
SofaRequest request = new SofaRequest();
{
for (int i = 0; i < size; i++) {
cnt.put(9000 + i, 0);
}
List<ProviderInfo> providers = buildSameWeightProviderList(size);
int localps = 5;
for (int i = 0; i < localps; i++) {
ProviderInfo localProvider = new ProviderInfo();
localProvider.setHost(SystemInfo.getLocalHost());
localProvider.setPort(22000 + i);
providers.add(localProvider);
cnt.put(22000 + i, 0);
}
long start = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
ProviderInfo provider = loadBalancer.doSelect(request, providers);
int port = provider.getPort();
cnt.put(port, cnt.get(port) + 1);
}
long end = System.currentTimeMillis();
LOGGER.info("elapsed" + (end - start) + "ms");
LOGGER.info("avg " + (end - start) * 1000 * 1000 / total + "ns");
for (int i = 0; i < size; i++) {
Assert.assertTrue(cnt.get(9000 + i) == 0);
}
int avg = total / localps;
for (int i = 0; i < localps; i++) {
Assert.assertTrue(avg * 0.9 < cnt.get(22000 + i)
&& avg * 1.1 > cnt.get(22000 + i)); // 随机偏差不会太大,应该不超过10%
}
}
{
for (int i = 0; i < size; i++) {
cnt.put(9000 + i, 0);
}
List<ProviderInfo> providers = buildDiffWeightProviderList(size);
int localps = 5;
for (int i = 0; i < localps; i++) {
ProviderInfo localProvider = new ProviderInfo();
localProvider.setHost(SystemInfo.getLocalHost());
localProvider.setPort(22000 + i);
localProvider.setWeight(i * 100);
providers.add(localProvider);
cnt.put(22000 + i, 0);
}
long start = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
ProviderInfo provider = loadBalancer.doSelect(request, providers);
int port = provider.getPort();
cnt.put(port, cnt.get(port) + 1);
}
long end = System.currentTimeMillis();
LOGGER.info("elapsed" + (end - start) + "ms");
LOGGER.info("avg " + (end - start) * 1000 * 1000 / total + "ns");
for (int i = 0; i < size; i++) {
Assert.assertTrue(cnt.get(9000 + i) == 0);
}
int count = 0;
for (int i = 0; i < localps; i++) {
count += i;
}
int per = total / count;
Assert.assertTrue(cnt.get(22000) == 0);
for (int i = 1; i < localps; i++) {
Assert.assertTrue(per * i * 0.9 < cnt.get(22000 + i)
&& per * i * 1.1 > cnt.get(22000 + i)); // 随机偏差不会太大,应该不超过10%
}
}
} |
public static String getKey(String dataId, String group) {
StringBuilder sb = new StringBuilder();
GroupKey.urlEncode(dataId, sb);
sb.append('+');
GroupKey.urlEncode(group, sb);
return sb.toString();
} | @Test
public void getKeyTenantIdentifyTest() {
String key = Md5ConfigUtil.getKey("DataId", "Group", "Tenant", "Identify");
Assert.isTrue(Objects.equals("DataId+Group+Tenant+Identify", key));
} |
public static void displayWelcomeMessage(
final int consoleWidth,
final PrintWriter writer
) {
final String[] lines = {
"",
"===========================================",
"= _ _ ____ ____ =",
"= | | _____ __ _| | _ \\| __ ) =",
"= | |/ / __|/ _` | | | | | _ \\ =",
"= | <\\__ \\ (_| | | |_| | |_) | =",
"= |_|\\_\\___/\\__, |_|____/|____/ =",
"= |_| =",
"= The Database purpose-built =",
"= for stream processing apps =",
"==========================================="
};
final String copyrightMsg = "Copyright 2017-2022 Confluent Inc.";
final Integer logoWidth = Arrays.stream(lines)
.map(String::length)
.reduce(0, Math::max);
// Don't want to display the logo if it'll just end up getting wrapped and looking hideous
if (consoleWidth < logoWidth) {
writer.println("ksqlDB, " + copyrightMsg);
} else {
final int paddingChars = (consoleWidth - logoWidth) / 2;
final String leftPadding = IntStream.range(0, paddingChars)
.mapToObj(idx -> " ")
.collect(Collectors.joining());
Arrays.stream(lines)
.forEach(line -> writer.println(leftPadding + line));
writer.println();
writer.println(copyrightMsg);
}
writer.println();
writer.flush();
} | @Test
public void shouldOutputShortWelcomeMessageIfConsoleNotWideEnough() {
// When:
WelcomeMsgUtils.displayWelcomeMessage(35, realPrintWriter);
// Then:
assertThat(stringWriter.toString(), is("ksqlDB, Copyright 2017-2022 Confluent Inc.\n\n"));
} |
@Path("/.well-known/openid-federation")
@GET
@Produces(MEDIA_TYPE_ENTITY_STATEMENT)
public Response get() {
var federationEntityJwks = federationConfig.entitySigningKeys().toPublicJWKSet();
var relyingPartyJwks = federationConfig.relyingPartyKeys().toPublicJWKSet();
var now = Instant.now();
var exp = now.plus(federationConfig.ttl());
var jws =
EntityStatement.create()
.iat(now)
.nbf(now)
.exp(exp)
.iss(federationConfig.iss().toString())
.sub(federationConfig.sub().toString())
.authorityHints(List.of(federationConfig.federationMaster().toString()))
.metadata(
Metadata.create()
.openIdRelyingParty(
OpenIdRelyingParty.create()
.clientName(federationConfig.appName())
.jwks(relyingPartyJwks)
.responseTypes(List.of("code"))
.grantTypes(List.of("authorization_code"))
.requirePushedAuthorizationRequests(true)
.idTokenSignedResponseAlg("ES256")
.idTokenEncryptedResponseAlg("ECDH-ES")
.idTokenEncryptedResponseEnc("A256GCM")
.scope(String.join(" ", federationConfig.scopes()))
.redirectUris(federationConfig.redirectUris())
.clientRegistrationTypes(List.of("automatic"))
.tokenEndpointAuthMethodsSupported(
List.of("self_signed_tls_client_auth"))
// according to the federation spec this is not required here, some
// sectoral IdPs require it though
.defaultAcrValues(List.of("gematik-ehealth-loa-high"))
// warn: this is a non-standard field, but needed by some sectoral IdPs
.tokenEndpointAuthMethod("self_signed_tls_client_auth")
.build())
.federationEntity(
FederationEntity.create().name(federationConfig.appName()).build())
.build())
.jwks(federationEntityJwks)
.build()
.sign(federationConfig.entitySigningKey());
return Response.ok(jws.serialize())
.header("x-kc-provider", "ovi")
.cacheControl(cacheForTtl(now))
.build();
} | @Test
void get() {
var res =
given()
.baseUri(server.configuration().baseUri().toString())
.get("/.well-known/openid-federation")
.getBody();
var body = res.asString();
var es = EntityStatementJWS.parse(body);
assertEquals(ISSUER.toString(), es.body().sub());
assertEquals(ISSUER.toString(), es.body().iss());
assertEquals(FEDMASTER.toString(), es.body().authorityHints().get(0));
} |
public List<ErasureCodingPolicy> loadPolicy(String policyFilePath) {
try {
File policyFile = getPolicyFile(policyFilePath);
if (!policyFile.exists()) {
LOG.warn("Not found any EC policy file");
return Collections.emptyList();
}
return loadECPolicies(policyFile);
} catch (ParserConfigurationException | IOException | SAXException e) {
throw new RuntimeException("Failed to load EC policy file: "
+ policyFilePath);
}
} | @Test
public void testBadECCellsize() throws Exception {
PrintWriter out = new PrintWriter(new FileWriter(POLICY_FILE));
out.println("<?xml version=\"1.0\"?>");
out.println("<configuration>");
out.println("<layoutversion>1</layoutversion>");
out.println("<schemas>");
out.println(" <schema id=\"RSk12m4\">");
out.println(" <codec>RS</codec>");
out.println(" <k>12</k>");
out.println(" <m>4</m>");
out.println(" </schema>");
out.println(" <schema id=\"RS-legacyk12m4\">");
out.println(" <codec>RS-legacy</codec>");
out.println(" <k>12</k>");
out.println(" <m>4</m>");
out.println(" </schema>");
out.println("</schemas>");
out.println("<policies>");
out.println(" <policy>");
out.println(" <schema>RSk12m4</schema>");
out.println(" <cellsize>free</cellsize>");
out.println(" </policy>");
out.println("</policies>");
out.println("</configuration>");
out.close();
ECPolicyLoader ecPolicyLoader = new ECPolicyLoader();
try {
ecPolicyLoader.loadPolicy(POLICY_FILE);
fail("IllegalArgumentException should be thrown for bad policy");
} catch (IllegalArgumentException e) {
assertExceptionContains("Bad EC policy cellsize value free is found."
+ " It should be an integer", e);
}
} |
public void logExecution(Execution execution, Logger logger, Level level, String message, Object... args) {
String finalMsg = tenantEnabled ? EXECUTION_PREFIX_WITH_TENANT + message : EXECUTION_PREFIX_NO_TENANT + message;
Object[] executionArgs = tenantEnabled ?
new Object[] { execution.getTenantId(), execution.getNamespace(), execution.getFlowId(), execution.getId() } :
new Object[] { execution.getNamespace(), execution.getFlowId(), execution.getId() };
Object[] finalArgs = ArrayUtils.addAll(executionArgs, args);
logger.atLevel(level).log(finalMsg, finalArgs);
} | @Test
void logExecution() {
var execution = Execution.builder().namespace("namespace").flowId("flow").id("execution").build();
logService.logExecution(execution, log, Level.INFO, "Some log");
logService.logExecution(execution, log, Level.INFO, "Some log with an {}", "attribute");
} |
@Override
public void invoke() throws Exception {
// --------------------------------------------------------------------
// Initialize
// --------------------------------------------------------------------
LOG.debug(getLogString("Start registering input and output"));
// initialize OutputFormat
initOutputFormat();
// initialize input readers
try {
initInputReaders();
} catch (Exception e) {
throw new RuntimeException(
"Initializing the input streams failed"
+ (e.getMessage() == null ? "." : ": " + e.getMessage()),
e);
}
LOG.debug(getLogString("Finished registering input and output"));
// --------------------------------------------------------------------
// Invoke
// --------------------------------------------------------------------
LOG.debug(getLogString("Starting data sink operator"));
RuntimeContext ctx = createRuntimeContext();
final Counter numRecordsIn;
{
Counter tmpNumRecordsIn;
try {
InternalOperatorIOMetricGroup ioMetricGroup =
((InternalOperatorMetricGroup) ctx.getMetricGroup()).getIOMetricGroup();
ioMetricGroup.reuseInputMetricsForTask();
ioMetricGroup.reuseOutputMetricsForTask();
tmpNumRecordsIn = ioMetricGroup.getNumRecordsInCounter();
} catch (Exception e) {
LOG.warn("An exception occurred during the metrics setup.", e);
tmpNumRecordsIn = new SimpleCounter();
}
numRecordsIn = tmpNumRecordsIn;
}
if (RichOutputFormat.class.isAssignableFrom(this.format.getClass())) {
((RichOutputFormat) this.format).setRuntimeContext(ctx);
LOG.debug(getLogString("Rich Sink detected. Initializing runtime context."));
}
ExecutionConfig executionConfig = getExecutionConfig();
boolean objectReuseEnabled = executionConfig.isObjectReuseEnabled();
try {
// initialize local strategies
MutableObjectIterator<IT> input1;
switch (this.config.getInputLocalStrategy(0)) {
case NONE:
// nothing to do
localStrategy = null;
input1 = reader;
break;
case SORT:
// initialize sort local strategy
try {
// get type comparator
TypeComparatorFactory<IT> compFact =
this.config.getInputComparator(0, getUserCodeClassLoader());
if (compFact == null) {
throw new Exception(
"Missing comparator factory for local strategy on input " + 0);
}
// initialize sorter
Sorter<IT> sorter =
ExternalSorter.newBuilder(
getEnvironment().getMemoryManager(),
this,
this.inputTypeSerializerFactory.getSerializer(),
compFact.createComparator())
.maxNumFileHandles(this.config.getFilehandlesInput(0))
.enableSpilling(
getEnvironment().getIOManager(),
this.config.getSpillingThresholdInput(0))
.memoryFraction(this.config.getRelativeMemoryInput(0))
.objectReuse(
this.getExecutionConfig().isObjectReuseEnabled())
.largeRecords(this.config.getUseLargeRecordHandler())
.build(this.reader);
this.localStrategy = sorter;
input1 = sorter.getIterator();
} catch (Exception e) {
throw new RuntimeException(
"Initializing the input processing failed"
+ (e.getMessage() == null ? "." : ": " + e.getMessage()),
e);
}
break;
default:
throw new RuntimeException("Invalid local strategy for DataSinkTask");
}
// read the reader and write it to the output
final TypeSerializer<IT> serializer = this.inputTypeSerializerFactory.getSerializer();
final MutableObjectIterator<IT> input = input1;
final OutputFormat<IT> format = this.format;
// check if task has been canceled
if (this.taskCanceled) {
return;
}
LOG.debug(getLogString("Starting to produce output"));
// open
format.open(
new InitializationContext() {
@Override
public int getNumTasks() {
return getEnvironment().getTaskInfo().getNumberOfParallelSubtasks();
}
@Override
public int getTaskNumber() {
return getEnvironment().getTaskInfo().getIndexOfThisSubtask();
}
@Override
public int getAttemptNumber() {
return getEnvironment().getTaskInfo().getAttemptNumber();
}
});
if (objectReuseEnabled) {
IT record = serializer.createInstance();
// work!
while (!this.taskCanceled && ((record = input.next(record)) != null)) {
numRecordsIn.inc();
format.writeRecord(record);
}
} else {
IT record;
// work!
while (!this.taskCanceled && ((record = input.next()) != null)) {
numRecordsIn.inc();
format.writeRecord(record);
}
}
// close. We close here such that a regular close throwing an exception marks a task as
// failed.
if (!this.taskCanceled) {
this.format.close();
this.format = null;
}
} catch (Exception ex) {
// make a best effort to clean up
try {
if (!cleanupCalled && format instanceof CleanupWhenUnsuccessful) {
cleanupCalled = true;
((CleanupWhenUnsuccessful) format).tryCleanupOnError();
}
} catch (Throwable t) {
LOG.error("Cleanup on error failed.", t);
}
ex = ExceptionInChainedStubException.exceptionUnwrap(ex);
if (ex instanceof CancelTaskException) {
// forward canceling exception
throw ex;
}
// drop, if the task was canceled
else if (!this.taskCanceled) {
if (LOG.isErrorEnabled()) {
LOG.error(getLogString("Error in user code: " + ex.getMessage()), ex);
}
throw ex;
}
} finally {
if (this.format != null) {
// close format, if it has not been closed, yet.
// This should only be the case if we had a previous error, or were canceled.
try {
this.format.close();
} catch (Throwable t) {
if (LOG.isWarnEnabled()) {
LOG.warn(getLogString("Error closing the output format"), t);
}
}
}
// close local strategy if necessary
if (localStrategy != null) {
try {
this.localStrategy.close();
} catch (Throwable t) {
LOG.error("Error closing local strategy", t);
}
}
BatchTask.clearReaders(new MutableReader<?>[] {inputReader});
}
if (!this.taskCanceled) {
LOG.debug(getLogString("Finished data sink operator"));
} else {
LOG.debug(getLogString("Data sink operator cancelled"));
}
} | @Test
@SuppressWarnings("unchecked")
void testSortingDataSinkTask() {
int keyCnt = 100;
int valCnt = 20;
double memoryFraction = 1.0;
super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE);
super.addInput(new UniformRecordGenerator(keyCnt, valCnt, true), 0);
DataSinkTask<Record> testTask = new DataSinkTask<>(this.mockEnv);
// set sorting
super.getTaskConfig().setInputLocalStrategy(0, LocalStrategy.SORT);
super.getTaskConfig()
.setInputComparator(
new RecordComparatorFactory(new int[] {1}, (new Class[] {IntValue.class})),
0);
super.getTaskConfig().setRelativeMemoryInput(0, memoryFraction);
super.getTaskConfig().setFilehandlesInput(0, 8);
super.getTaskConfig().setSpillingThresholdInput(0, 0.8f);
File tempTestFile = new File(tempFolder.toFile(), UUID.randomUUID().toString());
super.registerFileOutputTask(
MockOutputFormat.class, tempTestFile.toURI().toString(), new Configuration());
try {
testTask.invoke();
} catch (Exception e) {
LOG.debug("Exception while invoking the test task.", e);
fail("Invoke method caused exception.");
}
assertThat(tempTestFile).withFailMessage("Temp output file does not exist").exists();
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(tempTestFile);
br = new BufferedReader(fr);
Set<Integer> keys = new HashSet<>();
int curVal = -1;
while (br.ready()) {
String line = br.readLine();
Integer key = Integer.parseInt(line.substring(0, line.indexOf("_")));
Integer val =
Integer.parseInt(line.substring(line.indexOf("_") + 1, line.length()));
// check that values are in correct order
assertThat(val)
.withFailMessage("Values not in ascending order")
.isGreaterThanOrEqualTo(curVal);
// next value hit
if (val > curVal) {
if (curVal != -1) {
// check that we saw 100 distinct keys for this values
assertThat(keys).withFailMessage("Keys missing for value").hasSize(100);
}
// empty keys set
keys.clear();
// update current value
curVal = val;
}
assertThat(keys.add(key)).withFailMessage("Duplicate key for value").isTrue();
}
} catch (FileNotFoundException e) {
fail("Out file got lost...");
} catch (IOException ioe) {
fail("Caught IOE while reading out file");
} finally {
if (br != null) {
try {
br.close();
} catch (Throwable t) {
}
}
if (fr != null) {
try {
fr.close();
} catch (Throwable t) {
}
}
}
} |
@Override
public Object getInitialAggregatedValue(Object rawValue) {
CpcUnion cpcUnion = new CpcUnion(_lgK);
if (rawValue instanceof byte[]) { // Serialized Sketch
byte[] bytes = (byte[]) rawValue;
cpcUnion.update(deserializeAggregatedValue(bytes));
} else if (rawValue instanceof byte[][]) { // Multiple Serialized Sketches
byte[][] serializedSketches = (byte[][]) rawValue;
for (byte[] bytes : serializedSketches) {
cpcUnion.update(deserializeAggregatedValue(bytes));
}
} else {
CpcSketch pristineSketch = empty();
addObjectToSketch(rawValue, pristineSketch);
cpcUnion.update(pristineSketch);
}
return cpcUnion;
} | @Test
public void getInitialValueShouldSupportMultiValueTypes() {
DistinctCountCPCSketchValueAggregator agg = new DistinctCountCPCSketchValueAggregator(Collections.emptyList());
Integer[] ints = {12345};
assertEquals(toSketch(agg.getInitialAggregatedValue(ints)).getEstimate(), 1.0);
Long[] longs = {12345L};
assertEquals(toSketch(agg.getInitialAggregatedValue(longs)).getEstimate(), 1.0);
Float[] floats = {12.345f};
assertEquals(toSketch(agg.getInitialAggregatedValue(floats)).getEstimate(), 1.0);
Double[] doubles = {12.345d};
assertEquals(toSketch(agg.getInitialAggregatedValue(doubles)).getEstimate(), 1.0);
Object[] objects = {new Object()};
assertThrows(() -> agg.getInitialAggregatedValue(objects));
byte[][] zeroSketches = {};
assertEquals(toSketch(agg.getInitialAggregatedValue(zeroSketches)).getEstimate(), 0.0);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.