focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public KTableValueGetterSupplier<K, VOut> view() {
if (queryableName != null) {
return new KTableMaterializedValueGetterSupplier<>(queryableName);
}
return new KTableValueGetterSupplier<K, VOut>() {
final KTableValueGetterSupplier<K, V> parentValueGetterSupplier = parent.valueGetterSupplier();
public KTableValueGetter<K, VOut> get() {
return new KTableTransformValuesGetter(
parentValueGetterSupplier.get(),
transformerSupplier.get());
}
@Override
public String[] storeNames() {
return parentValueGetterSupplier.storeNames();
}
};
}
|
@Test
public void shouldGetStoreNamesFromParentIfNotMaterialized() {
final KTableTransformValues<String, String, String> transformValues =
new KTableTransformValues<>(parent, new ExclamationValueTransformerSupplier(), null);
when(parent.valueGetterSupplier()).thenReturn(parentGetterSupplier);
when(parentGetterSupplier.storeNames()).thenReturn(new String[]{"store1", "store2"});
final String[] storeNames = transformValues.view().storeNames();
assertThat(storeNames, is(new String[]{"store1", "store2"}));
}
|
@Override
public boolean eval(Object arg) {
return false;
}
|
@Test
public void testEval() {
assertFalse(multiMapEventFilter.eval(null));
}
|
@Override
public <K> URIMappingResult<K> mapUris(List<URIKeyPair<K>> uris) throws ServiceUnavailableException
{
return _uriMapper.mapUris(uris);
}
|
@Test
public void testMapUris() throws ServiceUnavailableException
{
URIMappingResult<Long> expectedMappingResult = new URIMappingResult<>(_mappedKeys, _unmappedKeys, _hostToPartitionId);
when(_uriMapper.mapUris(_batchToUris)).thenReturn(expectedMappingResult);
URIMappingResult<Long> mappingResult = _sgStrategy.mapUris(_batchToUris);
Assert.assertEquals(mappingResult, expectedMappingResult);
}
|
public static ForIteration getForIteration(EvaluationContext ctx, String name, Object start, Object end) {
validateValues(ctx, start, end);
if (start instanceof BigDecimal bigDecimal) {
return new ForIteration(name, bigDecimal, (BigDecimal) end);
}
if (start instanceof LocalDate localDate) {
return new ForIteration(name, localDate, (LocalDate) end);
}
ctx.notifyEvt(() -> new ASTEventBase(FEELEvent.Severity.ERROR,
Msg.createMessage(Msg.VALUE_X_NOT_A_VALID_ENDPOINT_FOR_RANGE_BECAUSE_NOT_A_NUMBER_NOT_A_DATE, start), null));
throw new EndpointOfRangeOfDifferentTypeException();
}
|
@Test
void getForIterationValidTest() {
ForIteration retrieved = getForIteration(ctx, "iteration", BigDecimal.valueOf(1), BigDecimal.valueOf(3));
assertNotNull(retrieved);
verify(listener, never()).onEvent(any(FEELEvent.class));
retrieved = getForIteration(ctx, "iteration", LocalDate.of(2021, 1, 1), LocalDate.of(2021, 1, 3));
assertNotNull(retrieved);
verify(listener, never()).onEvent(any(FEELEvent.class));
}
|
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestException.forError(HttpStatus.S_405_METHOD_NOT_ALLOWED.getCode(), "Invalid method"));
return;
}
// Disable server-side latency instrumentation for multiplexed requests
requestContext.putLocalAttr(TimingContextUtil.TIMINGS_DISABLED_KEY_NAME, true);
IndividualRequestMap individualRequests;
try
{
individualRequests = extractIndividualRequests(request);
if (_multiplexerSingletonFilter != null) {
individualRequests = _multiplexerSingletonFilter.filterRequests(individualRequests);
}
}
catch (RestException e)
{
_log.error("Invalid multiplexed request", e);
callback.onError(e);
return;
}
catch (Exception e)
{
_log.error("Invalid multiplexed request", e);
callback.onError(RestException.forError(HttpStatus.S_400_BAD_REQUEST.getCode(), e));
return;
}
// prepare the map of individual responses to be collected
final IndividualResponseMap individualResponses = new IndividualResponseMap(individualRequests.size());
final Map<String, HttpCookie> responseCookies = new HashMap<>();
// all tasks are Void and side effect based, that will be useful when we add streaming
Task<?> requestProcessingTask = createParallelRequestsTask(request, requestContext, individualRequests, individualResponses, responseCookies);
Task<Void> responseAggregationTask = Task.action("send aggregated response", () ->
{
RestResponse aggregatedResponse = aggregateResponses(individualResponses, responseCookies);
callback.onSuccess(aggregatedResponse);
}
);
_engine.run(requestProcessingTask.andThen(responseAggregationTask), MUX_PLAN_CLASS);
}
|
@Test(dataProvider = "multiplexerConfigurations")
public void testResponseCookiesAggregated(MultiplexerRunMode multiplexerRunMode) throws Exception
{
// Per security review: We should not make cookies for each individual responses visible to the client (especially if the cookie is HttpOnly).
// Therefore all cookies returned by individual responses will be aggregated at the envelope response level.
// Create a mockHandler. Make it return different cookies based on the request
SynchronousRequestHandler mockHandler = new SynchronousRequestHandler() {
@Override
public RestResponse handleRequestSync(RestRequest request, RequestContext requestContext)
{
try
{
URI uri = request.getURI();
RestResponseBuilder restResponseBuilder = new RestResponseBuilder();
restResponseBuilder.setStatus(HttpStatus.S_200_OK.getCode());
restResponseBuilder.setEntity(jsonBodyToByteString(fakeIndividualBody("don't care")));
List<HttpCookie> cookies = new ArrayList<>();
if (uri.getPath().contains("req1"))
{
HttpCookie cookie = new HttpCookie("cookie1", "cookie1Value");
cookie.setDomain(".www.linkedin.com");
cookie.setSecure(false);
cookies.add(cookie);
HttpCookie commonCookie = new HttpCookie("commonCookie", "commonCookieValue");
commonCookie.setDomain(".WWW.linkedin.com");
commonCookie.setPath("/foo");
commonCookie.setSecure(false);
cookies.add(commonCookie);
}
else if (uri.getPath().contains("req2"))
{
HttpCookie cookie = new HttpCookie("cookie2", "cookie2Value");
cookie.setDomain("www.linkedin.com");
cookie.setSecure(false);
cookies.add(cookie);
cookie = new HttpCookie("cookie3", "cookie3Value");
cookies.add(cookie);
HttpCookie commonCookie = new HttpCookie("commonCookie", "commonCookieValue");
commonCookie.setDomain(".www.linkedin.com");
commonCookie.setPath("/foo");
commonCookie.setSecure(true);
cookies.add(commonCookie);
}
else
{
HttpCookie cookie = new HttpCookie("cookie2", "newCookie2Value");
cookie.setDomain("www.linkedin.com");
cookie.setSecure(true);
cookies.add(cookie);
}
return restResponseBuilder.setCookies(CookieUtil.encodeSetCookies(cookies)).build();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
};
// Prepare request to mux handler
FutureCallback<RestResponse> callback = new FutureCallback<>();
RequestContext requestContext = new RequestContext();
Map<String, IndividualRequest> individualRequests = ImmutableMap.of(
"0", fakeIndRequest("/req1"),
"1", fakeIndRequest("/req2", ImmutableMap.of("2", fakeIndRequest("/req3"))));
// Create mux handler instance
MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(mockHandler, null, Collections.<String>emptySet(), 3, multiplexerRunMode);
try
{
multiplexer.handleRequest(fakeMuxRestRequest(individualRequests), requestContext, callback);
}
catch (Exception e)
{
fail("Multiplexer should not throw exception", e);
}
RestResponse muxRestResponse = callback.get();
// assert multiplexed request should return a 200 status code
assertEquals(muxRestResponse.getStatus(), 200, "Multiplexer should return 200");
MultiplexedResponseContent muxResponseContent = new MultiplexedResponseContent(DataMapConverter.bytesToDataMap(muxRestResponse.getHeaders(), muxRestResponse.getEntity()));
// individual response should not have set-cookie headers
IndividualResponseMap responses = muxResponseContent.getResponses();
for(IndividualResponse res : responses.values())
{
for(String headerName : res.getHeaders().keySet())
{
assertTrue(headerName.equalsIgnoreCase("set-cookie"), "Individual response header should not container set-cookie header: " + responses.toString());
}
}
// Ensure cookies are aggregated at envelope level
List<HttpCookie> cookies = CookieUtil.decodeSetCookies(muxRestResponse.getCookies());
assertEquals(cookies.size(), 4);
for(HttpCookie cookie: cookies)
{
if ("cookie1".equals(cookie.getName()))
{
assertEquals(cookie.getValue(), "cookie1Value");
assertEquals(cookie.getDomain(), ".www.linkedin.com");
assertEquals(cookie.getSecure(), false);
}
else if ("cookie2".equals(cookie.getName()))
{
assertEquals(cookie.getValue(), "newCookie2Value");
assertEquals(cookie.getDomain(), "www.linkedin.com");
assertEquals(cookie.getSecure(), true);
}
else if ("cookie3".equals(cookie.getName()))
{
assertEquals(cookie.getValue(), "cookie3Value");
}
else if ("commonCookie".equals(cookie.getName()))
{
assertEquals(cookie.getValue(), "commonCookieValue");
assertEquals(cookie.getDomain().toLowerCase(), ".www.linkedin.com");
assertEquals(cookie.getPath(), "/foo");
// Since request0 and request1 are executed in parallel, depending on which request is completed first,
// we don't know what will be its final 'secure' attribute value.
}
else
{
fail("Unknown cookie name: " + cookie.getName());
}
}
}
|
@Nullable
public String ensureBuiltinRole(String roleName, String description, Set<String> expectedPermissions) {
Role previousRole = null;
try {
previousRole = roleService.load(roleName);
if (!previousRole.isReadOnly() || !expectedPermissions.equals(previousRole.getPermissions())) {
final String msg = "Invalid role '" + roleName + "', fixing it.";
LOG.debug(msg);
throw new IllegalArgumentException(msg); // jump to fix code
}
} catch (NotFoundException | IllegalArgumentException | NoSuchElementException ignored) {
LOG.info("{} role is missing or invalid, re-adding it as a built-in role.", roleName);
final RoleImpl fixedRole = new RoleImpl();
// copy the mongodb id over, in order to update the role instead of reading it
if (previousRole != null) {
fixedRole._id = previousRole.getId();
}
fixedRole.setReadOnly(true);
fixedRole.setName(roleName);
fixedRole.setDescription(description);
fixedRole.setPermissions(expectedPermissions);
try {
final Role savedRole = roleService.save(fixedRole);
return savedRole.getId();
} catch (DuplicateKeyException | ValidationException e) {
LOG.error("Unable to save fixed '" + roleName + "' role, please restart Graylog to fix this.", e);
}
}
if (previousRole == null) {
LOG.error("Unable to access fixed '" + roleName + "' role, please restart Graylog to fix this.");
return null;
}
return previousRole.getId();
}
|
@Test
public void ensureBuiltinRoleExists() throws Exception {
final Role existingRole = mock(Role.class);
when(existingRole.getId()).thenReturn("new-id");
when(existingRole.isReadOnly()).thenReturn(true);
when(existingRole.getPermissions()).thenReturn(ImmutableSet.of("a", "b"));
when(roleService.load("test-role")).thenReturn(existingRole);
assertThat(migrationHelpers.ensureBuiltinRole("test-role", "description", ImmutableSet.of("a", "b")))
.isEqualTo("new-id");
verify(roleService, never()).save(any()); // The existing role is fine, so we don't expect it to be modified
}
|
@Udtf
public <T> List<List<T>> cube(final List<T> columns) {
if (columns == null) {
return Collections.emptyList();
}
return createAllCombinations(columns);
}
|
@Test
public void shouldCubeSingleColumn() {
// Given:
final Object[] args = {1};
// When:
final List<List<Object>> result = cubeUdtf.cube(Arrays.asList(args));
// Then:
assertThat(result.size(), is(2));
assertThat(result.get(0), is(Collections.singletonList(null)));
assertThat(result.get(1), is(Lists.newArrayList(1)));
}
|
public static List<Predicate> fromExpression(List<ResolvedExpression> resolvedExpressions) {
return resolvedExpressions.stream()
.map(e -> fromExpression((CallExpression) e))
.collect(Collectors.toList());
}
|
@Test
public void testFilterPredicateFromExpression() {
FieldReferenceExpression fieldReference = new FieldReferenceExpression("f_int", DataTypes.INT(), 0, 0);
ValueLiteralExpression valueLiteral = new ValueLiteralExpression(10);
List<ResolvedExpression> expressions = Arrays.asList(fieldReference, valueLiteral);
IntColumn intColumn = intColumn("f_int");
// equals
CallExpression equalsExpression = new CallExpression(
BuiltInFunctionDefinitions.EQUALS, expressions, DataTypes.BOOLEAN());
Predicate predicate1 = Equals.getInstance().bindValueLiteral(valueLiteral).bindFieldReference(fieldReference);
Eq<Integer> eq = eq(intColumn, 10);
Predicate predicate2 = fromExpression(equalsExpression);
assertEquals(predicate1.toString(), predicate2.toString());
assertEquals(eq, predicate2.filter());
// not equals
CallExpression notEqualsExpression = new CallExpression(
BuiltInFunctionDefinitions.NOT_EQUALS, expressions, DataTypes.BOOLEAN());
Predicate predicate3 = NotEquals.getInstance().bindValueLiteral(valueLiteral).bindFieldReference(fieldReference);
Predicate predicate4 = fromExpression(notEqualsExpression);
assertEquals(predicate3.toString(), predicate4.toString());
assertEquals(notEq(intColumn, 10), predicate4.filter());
// less than
CallExpression lessThanExpression = new CallExpression(
BuiltInFunctionDefinitions.LESS_THAN, expressions, DataTypes.BOOLEAN());
Predicate predicate5 = LessThan.getInstance().bindValueLiteral(valueLiteral).bindFieldReference(fieldReference);
Lt<Integer> lt = lt(intColumn, 10);
Predicate predicate6 = fromExpression(lessThanExpression);
assertEquals(predicate5.toString(), predicate6.toString());
assertEquals(lt, predicate6.filter());
// greater than
CallExpression greaterThanExpression = new CallExpression(
BuiltInFunctionDefinitions.GREATER_THAN, expressions, DataTypes.BOOLEAN());
Predicate predicate7 = GreaterThan.getInstance().bindValueLiteral(valueLiteral).bindFieldReference(fieldReference);
Gt<Integer> gt = gt(intColumn, 10);
Predicate predicate8 = fromExpression(greaterThanExpression);
assertEquals(predicate7.toString(), predicate8.toString());
assertEquals(gt, predicate8.filter());
// less than or equal
CallExpression lessThanOrEqualExpression = new CallExpression(
BuiltInFunctionDefinitions.LESS_THAN_OR_EQUAL, expressions, DataTypes.BOOLEAN());
Predicate predicate9 = LessThanOrEqual.getInstance().bindValueLiteral(valueLiteral).bindFieldReference(fieldReference);
Predicate predicate10 = fromExpression(lessThanOrEqualExpression);
assertEquals(predicate9.toString(), predicate10.toString());
assertEquals(ltEq(intColumn, 10), predicate10.filter());
// greater than or equal
CallExpression greaterThanOrEqualExpression = new CallExpression(
BuiltInFunctionDefinitions.GREATER_THAN_OR_EQUAL, expressions, DataTypes.BOOLEAN());
Predicate predicate11 = GreaterThanOrEqual.getInstance().bindValueLiteral(valueLiteral).bindFieldReference(fieldReference);
Predicate predicate12 = fromExpression(greaterThanOrEqualExpression);
assertEquals(predicate11.toString(), predicate12.toString());
assertEquals(gtEq(intColumn, 10), predicate12.filter());
// in
ValueLiteralExpression valueLiteral1 = new ValueLiteralExpression(11);
ValueLiteralExpression valueLiteral2 = new ValueLiteralExpression(12);
CallExpression inExpression = new CallExpression(
BuiltInFunctionDefinitions.IN,
Arrays.asList(fieldReference, valueLiteral1, valueLiteral2),
DataTypes.BOOLEAN());
Predicate predicate13 = In.getInstance().bindValueLiterals(Arrays.asList(valueLiteral1, valueLiteral2)).bindFieldReference(fieldReference);
Predicate predicate14 = fromExpression(inExpression);
assertEquals(predicate13.toString(), predicate14.toString());
assertEquals(or(eq(intColumn, 11), eq(intColumn, 12)), predicate14.filter());
// not
CallExpression notExpression = new CallExpression(
BuiltInFunctionDefinitions.NOT,
Collections.singletonList(equalsExpression),
DataTypes.BOOLEAN());
Predicate predicate15 = Not.getInstance().bindPredicate(predicate2);
Predicate predicate16 = fromExpression(notExpression);
assertEquals(predicate15.toString(), predicate16.toString());
assertEquals(not(eq), predicate16.filter());
// and
CallExpression andExpression = new CallExpression(
BuiltInFunctionDefinitions.AND,
Arrays.asList(lessThanExpression, greaterThanExpression),
DataTypes.BOOLEAN());
Predicate predicate17 = And.getInstance().bindPredicates(predicate6, predicate8);
Predicate predicate18 = fromExpression(andExpression);
assertEquals(predicate17.toString(), predicate18.toString());
assertEquals(and(lt, gt), predicate18.filter());
// or
CallExpression orExpression = new CallExpression(
BuiltInFunctionDefinitions.OR,
Arrays.asList(lessThanExpression, greaterThanExpression),
DataTypes.BOOLEAN());
Predicate predicate19 = Or.getInstance().bindPredicates(predicate6, predicate8);
Predicate predicate20 = fromExpression(orExpression);
assertEquals(predicate19.toString(), predicate20.toString());
assertEquals(or(lt, gt), predicate20.filter());
}
|
protected short sampleStoreTopicReplicationFactor(Map<String, ?> config, AdminClient adminClient) {
if (_sampleStoreTopicReplicationFactor != null) {
return _sampleStoreTopicReplicationFactor;
}
int maxRetryCount = Integer.parseInt(config.get(MonitorConfig.FETCH_METRIC_SAMPLES_MAX_RETRY_COUNT_CONFIG).toString());
AtomicInteger numberOfBrokersInCluster = new AtomicInteger(0);
AtomicReference<String> errorMsg = new AtomicReference<>("");
boolean success = CruiseControlMetricsUtils.retry(() -> {
try {
numberOfBrokersInCluster.set(adminClient.describeCluster().nodes().get(CLIENT_REQUEST_TIMEOUT_MS,
TimeUnit.MILLISECONDS).size());
} catch (InterruptedException | ExecutionException | TimeoutException e) {
errorMsg.set("Auto creation of sample store topics failed due to failure to describe cluster. " + e);
return true;
}
if (numberOfBrokersInCluster.get() <= 1) {
errorMsg.set(String.format("Kafka cluster has less than 2 brokers (brokers in cluster=%d)",
numberOfBrokersInCluster.get()));
return true;
}
numberOfBrokersInCluster.set(Math.min(DEFAULT_SAMPLE_STORE_TOPIC_REPLICATION_FACTOR, numberOfBrokersInCluster.get()));
return false;
}, maxRetryCount);
if (success) {
return (short) numberOfBrokersInCluster.get();
} else {
throw new IllegalStateException(errorMsg.get());
}
}
|
@Test
public void testSampleStoreTopicReplicationFactorWhenValueNotExistsAndDescribeOfClusterFails()
throws ExecutionException, InterruptedException, TimeoutException {
Map<String, Object> config = createFilledConfigMap();
AdminClient adminClient = EasyMock.mock(AdminClient.class);
KafkaFuture nodesFuture = getNodesKafkaFutureWithRequiredMocks(adminClient);
EasyMock.expect(nodesFuture.get(TimeUnit.SECONDS.toMillis(30), TimeUnit.MILLISECONDS))
.andThrow(new TimeoutException()).times(2);
EasyMock.replay(nodesFuture);
AbstractKafkaSampleStore kafkaSampleStore = EasyMock.partialMockBuilder(AbstractKafkaSampleStore.class).createMock();
EasyMock.replay(adminClient, kafkaSampleStore);
assertThrows(IllegalStateException.class,
() -> kafkaSampleStore.sampleStoreTopicReplicationFactor(config, adminClient));
EasyMock.verify(adminClient, kafkaSampleStore, nodesFuture);
}
|
static <T> Optional<T> lookupByNameAndType(CamelContext camelContext, String name, Class<T> type) {
return Optional.ofNullable(ObjectHelper.isEmpty(name) ? null : name)
.map(n -> EndpointHelper.isReferenceParameter(n)
? EndpointHelper.resolveReferenceParameter(camelContext, n, type, false)
: camelContext.getRegistry().lookupByNameAndType(n, type));
}
|
@Test
void testLookupByNameAndTypeWithExistingObject() {
String name = "ExistingObject";
Object existingObject = new Object();
when(camelContext.getRegistry()).thenReturn(mockRegistry);
when(camelContext.getRegistry().lookupByNameAndType(name, Object.class))
.thenReturn(existingObject);
Optional<Object> object = DynamicRouterRecipientListHelper.lookupByNameAndType(camelContext, name, Object.class);
Assertions.assertTrue(object.isPresent());
Assertions.assertEquals(existingObject, object.get());
}
|
public static TextPlainEntity parseTextPlainEntityBody(
AS2SessionInputBuffer inbuffer,
InputStream is,
String boundary,
String charsetName,
String contentTransferEncoding)
throws ParseException {
CharsetDecoder previousDecoder = inbuffer.getCharsetDecoder();
try {
if (charsetName == null) {
charsetName = StandardCharsets.US_ASCII.name();
}
Charset charset = Charset.forName(charsetName);
CharsetDecoder charsetDecoder = charset.newDecoder();
inbuffer.setCharsetDecoder(charsetDecoder);
String text = parseBodyPartText(inbuffer, is, boundary);
if (contentTransferEncoding != null) {
text = EntityUtils.decode(text, charset, contentTransferEncoding);
}
return new TextPlainEntity(text, charsetName, contentTransferEncoding, false);
} catch (Exception e) {
ParseException parseException = new ParseException("failed to parse text entity");
parseException.initCause(e);
throw parseException;
} finally {
inbuffer.setCharsetDecoder(previousDecoder);
}
}
|
@Test
public void parseTextPlainBodyTest() throws Exception {
InputStream is = new ByteArrayInputStream(TEXT_PLAIN_CONTENT.getBytes(TEXT_PLAIN_CONTENT_CHARSET_NAME));
AS2SessionInputBuffer inbuffer
= new AS2SessionInputBuffer(new BasicHttpTransportMetrics(), DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
TextPlainEntity textPlainEntity = EntityParser.parseTextPlainEntityBody(inbuffer, is, TEXT_PLAIN_CONTENT_BOUNDARY,
TEXT_PLAIN_CONTENT_CHARSET_NAME, TEXT_PLAIN_CONTENT_TRANSFER_ENCODING);
String text = textPlainEntity.getText();
assertEquals(EXPECTED_TEXT_PLAIN_CONTENT, text, "Unexpected text");
}
|
@Override
public Subject getSubject() {
Subject subject = securityContext.getSubject();
if (subject != null) {
return subject;
}
String msg = "There is no Subject available in the SecurityContext. Ensure " +
"that the SubjectPlugin is configured before all other Shiro-dependent broker filters.";
throw new IllegalStateException(msg);
}
|
@Test(expected = IllegalStateException.class)
public void testNullSubject() {
SubjectConnectionReference reference =
new SubjectConnectionReference(new ConnectionContext(), new ConnectionInfo(),
new DefaultEnvironment(), new SubjectAdapter());
reference.getConnectionContext().setSecurityContext(new SubjectSecurityContext(reference) {
@Override
public Subject getSubject() {
return null;
}
});
ConnectionSubjectResolver resolver = new ConnectionSubjectResolver(reference);
resolver.getSubject();
}
|
@Override
@Transactional(rollbackFor = Exception.class)
public Long createSpu(ProductSpuSaveReqVO createReqVO) {
// 校验分类、品牌
validateCategory(createReqVO.getCategoryId());
brandService.validateProductBrand(createReqVO.getBrandId());
// 校验 SKU
List<ProductSkuSaveReqVO> skuSaveReqList = createReqVO.getSkus();
productSkuService.validateSkuList(skuSaveReqList, createReqVO.getSpecType());
ProductSpuDO spu = BeanUtils.toBean(createReqVO, ProductSpuDO.class);
// 初始化 SPU 中 SKU 相关属性
initSpuFromSkus(spu, skuSaveReqList);
// 插入 SPU
productSpuMapper.insert(spu);
// 插入 SKU
productSkuService.createSkuList(spu.getId(), skuSaveReqList);
// 返回
return spu.getId();
}
|
@Test
public void testCreateSpu_success() {
// 准备参数
ProductSkuSaveReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuSaveReqVO.class, o->{
// 限制范围为正整数
o.setCostPrice(generaInt());
o.setPrice(generaInt());
o.setMarketPrice(generaInt());
o.setStock(generaInt());
o.setFirstBrokeragePrice(generaInt());
o.setSecondBrokeragePrice(generaInt());
// 限制分数为两位数
o.setWeight(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
o.setVolume(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
});
ProductSpuSaveReqVO createReqVO = randomPojo(ProductSpuSaveReqVO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setSkus(newArrayList(skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO));
});
when(categoryService.getCategoryLevel(eq(createReqVO.getCategoryId()))).thenReturn(2);
Long spu = productSpuService.createSpu(createReqVO);
ProductSpuDO productSpuDO = productSpuMapper.selectById(spu);
assertPojoEquals(createReqVO, productSpuDO);
}
|
public static DynamicVoter parse(String input) {
input = input.trim();
int atIndex = input.indexOf("@");
if (atIndex < 0) {
throw new IllegalArgumentException("No @ found in dynamic voter string.");
}
if (atIndex == 0) {
throw new IllegalArgumentException("Invalid @ at beginning of dynamic voter string.");
}
String idString = input.substring(0, atIndex);
int nodeId;
try {
nodeId = Integer.parseInt(idString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Failed to parse node id in dynamic voter string.", e);
}
if (nodeId < 0) {
throw new IllegalArgumentException("Invalid negative node id " + nodeId +
" in dynamic voter string.");
}
input = input.substring(atIndex + 1);
if (input.isEmpty()) {
throw new IllegalArgumentException("No hostname found after node id.");
}
String host;
if (input.startsWith("[")) {
int endBracketIndex = input.indexOf("]");
if (endBracketIndex < 0) {
throw new IllegalArgumentException("Hostname began with left bracket, but no right " +
"bracket was found.");
}
host = input.substring(1, endBracketIndex);
input = input.substring(endBracketIndex + 1);
} else {
int endColonIndex = input.indexOf(":");
if (endColonIndex < 0) {
throw new IllegalArgumentException("No colon following hostname could be found.");
}
host = input.substring(0, endColonIndex);
input = input.substring(endColonIndex);
}
if (!input.startsWith(":")) {
throw new IllegalArgumentException("Port section must start with a colon.");
}
input = input.substring(1);
int endColonIndex = input.indexOf(":");
if (endColonIndex < 0) {
throw new IllegalArgumentException("No colon following port could be found.");
}
String portString = input.substring(0, endColonIndex);
int port;
try {
port = Integer.parseInt(portString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Failed to parse port in dynamic voter string.", e);
}
if (port < 0 || port > 65535) {
throw new IllegalArgumentException("Invalid port " + port + " in dynamic voter string.");
}
String directoryIdString = input.substring(endColonIndex + 1);
Uuid directoryId;
try {
directoryId = Uuid.fromString(directoryIdString);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Failed to parse directory ID in dynamic voter string.", e);
}
return new DynamicVoter(directoryId, nodeId, host, port);
}
|
@Test
public void testParseDynamicVoterWithInvalidNegativeId() {
assertEquals("Invalid negative node id -1 in dynamic voter string.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("-1@localhost:8020:K90IZ-0DRNazJ49kCZ1EMQ")).
getMessage());
}
|
@CheckForNull
public static String formatMeasureValue(LiveMeasureDto measure, MetricDto metric) {
Double doubleValue = measure.getValue();
String stringValue = measure.getDataAsString();
return formatMeasureValue(doubleValue == null ? Double.NaN : doubleValue, stringValue, metric);
}
|
@Test
public void test_formatMeasureValue() {
assertThat(formatMeasureValue(newNumericMeasure(-1.0d), newMetric(BOOL))).isEqualTo("false");
assertThat(formatMeasureValue(newNumericMeasure(1.0d), newMetric(BOOL))).isEqualTo("true");
assertThat(formatMeasureValue(newNumericMeasure(1000.123d), newMetric(PERCENT))).isEqualTo("1000.123");
assertThat(formatMeasureValue(newNumericMeasure(1000.0d), newMetric(WORK_DUR))).isEqualTo("1000");
assertThat(formatMeasureValue(newNumericMeasure(6_000_000_000_000.0d), newMetric(MILLISEC))).isEqualTo("6000000000000");
assertThat(formatMeasureValue(newTextMeasure("text-value"), newMetric(DATA))).isEqualTo("text-value");
}
|
@Override
public V put(IpPrefix prefix, V value) {
String prefixString = getPrefixString(prefix);
if (prefix.isIp4()) {
return ipv4Tree.put(prefixString, value);
}
if (prefix.isIp6()) {
return ipv6Tree.put(prefixString, value);
}
return null;
}
|
@Test
public void testPut() {
radixTree.put(ipv4PrefixKey5, IPV4_PREFIX_VALUE_5);
assertThat("Incorrect size of radix tree for IPv4 maps",
radixTree.size(IpAddress.Version.INET), is(5));
assertThat("IPv4 prefix key has not been inserted correctly",
radixTree.getValueForExactAddress(ipv4PrefixKey5), is(5));
radixTree.put(ipv6PrefixKey7, IPV6_PREFIX_VALUE_7);
assertThat("Incorrect size of radix tree for IPv6 maps",
radixTree.size(IpAddress.Version.INET6), is(7));
assertThat("IPv6 prefix key has not been inserted correctly",
radixTree.getValueForExactAddress(ipv6PrefixKey7), is(17));
radixTree.put(ipv4PrefixKey1, 8801);
assertThat("Incorrect size of radix tree for IPv4 maps",
radixTree.size(IpAddress.Version.INET), is(5));
assertThat("IPv4 prefix key has not been inserted correctly",
radixTree.getValueForExactAddress(ipv4PrefixKey1), is(8801));
}
|
public static final String decryptPassword( String encrypted ) {
return encoder.decode( encrypted );
}
|
@Test
public void testDecryptPassword() throws KettleValueException {
String encryption;
String decryption;
encryption = Encr.encryptPassword( null );
decryption = Encr.decryptPassword( encryption );
assertTrue( "".equals( decryption ) );
encryption = Encr.encryptPassword( "" );
decryption = Encr.decryptPassword( encryption );
assertTrue( "".equals( decryption ) );
encryption = Encr.encryptPassword( " " );
decryption = Encr.decryptPassword( encryption );
assertTrue( " ".equals( decryption ) );
encryption = Encr.encryptPassword( "Test of different encryptions!!@#$%" );
decryption = Encr.decryptPassword( encryption );
assertTrue( "Test of different encryptions!!@#$%".equals( decryption ) );
encryption = Encr.encryptPassword( " Spaces left" );
decryption = Encr.decryptPassword( encryption );
assertTrue( " Spaces left".equals( decryption ) );
encryption = Encr.encryptPassword( "Spaces right" );
decryption = Encr.decryptPassword( encryption );
assertTrue( "Spaces right".equals( decryption ) );
encryption = Encr.encryptPassword( " Spaces " );
decryption = Encr.decryptPassword( encryption );
assertTrue( " Spaces ".equals( decryption ) );
encryption = Encr.encryptPassword( "1234567890" );
decryption = Encr.decryptPassword( encryption );
assertTrue( "1234567890".equals( decryption ) );
}
|
public static int getMaskBitByMask(String mask) {
Integer maskBit = MaskBit.getMaskBit(mask);
if (maskBit == null) {
throw new IllegalArgumentException("Invalid netmask " + mask);
}
return maskBit;
}
|
@Test
public void getMaskBitByMaskTest(){
final int maskBitByMask = Ipv4Util.getMaskBitByMask("255.255.255.0");
assertEquals(24, maskBitByMask);
}
|
@Override
public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException {
if (needUsingInternalAddr()) {
remoteInstance = new RemoteInstance(new Address(config.getInternalComHost(), config.getInternalComPort(), true));
}
this.selfAddress = remoteInstance.getAddress();
String host = remoteInstance.getAddress().getHost();
int port = remoteInstance.getAddress().getPort();
try {
namingService.registerInstance(config.getServiceName(), host, port);
healthChecker.health();
} catch (Throwable e) {
healthChecker.unHealth(e);
throw new ServiceRegisterException(e.getMessage());
}
}
|
@Test
public void registerSelfRemote() throws NacosException {
registerRemote(selfRemoteAddress);
}
|
@Override
public CompletableFuture<Void> updateOrCreateTopic(String address, CreateTopicRequestHeader requestHeader,
long timeoutMillis) {
CompletableFuture<Void> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_TOPIC, requestHeader);
remotingClient.invoke(address, request, timeoutMillis).thenAccept(response -> {
if (response.getCode() == ResponseCode.SUCCESS) {
future.complete(null);
} else {
log.warn("updateOrCreateTopic getResponseCommand failed, {} {}, header={}", response.getCode(), response.getRemark(), requestHeader);
future.completeExceptionally(new MQClientException(response.getCode(), response.getRemark()));
}
});
return future;
}
|
@Test
public void assertUpdateOrCreateTopicWithError() {
setResponseError();
CreateTopicRequestHeader requestHeader = mock(CreateTopicRequestHeader.class);
CompletableFuture<Void> actual = mqClientAdminImpl.updateOrCreateTopic(defaultBrokerAddr, requestHeader, defaultTimeout);
Throwable thrown = assertThrows(ExecutionException.class, actual::get);
assertTrue(thrown.getCause() instanceof MQClientException);
MQClientException mqException = (MQClientException) thrown.getCause();
assertEquals(ResponseCode.SYSTEM_ERROR, mqException.getResponseCode());
assertTrue(mqException.getMessage().contains("CODE: 1 DESC: null"));
}
|
@Override
public <T> T unwrap(Class<T> clazz) {
if (!clazz.isInstance(this)) {
throw new IllegalArgumentException("Class " + clazz + " is unknown to this implementation");
}
@SuppressWarnings("unchecked")
T castedEntry = (T) this;
return castedEntry;
}
|
@Test
public void unwrap_fail() {
assertThrows(IllegalArgumentException.class, () -> entry.unwrap(Map.Entry.class));
}
|
@Udf
public <T> List<T> distinct(
@UdfParameter(description = "Array of values to distinct") final List<T> input) {
if (input == null) {
return null;
}
final Set<T> distinctVals = Sets.newLinkedHashSetWithExpectedSize(input.size());
distinctVals.addAll(input);
return new ArrayList<>(distinctVals);
}
|
@Test
public void shouldNotChangeDistinctArray() {
final List<String> result = udf.distinct(Arrays.asList("foo", " ", "bar"));
assertThat(result, contains("foo", " ", "bar"));
}
|
public TimelineEvent unblock(String workflowId, User caller) {
TimelineActionEvent.TimelineActionEventBuilder eventBuilder =
TimelineActionEvent.builder().author(caller).reason("Unblock workflow [%s]", workflowId);
int totalUnblocked = 0;
int unblocked = Constants.UNBLOCK_BATCH_SIZE;
while (unblocked == Constants.UNBLOCK_BATCH_SIZE) {
unblocked =
instanceDao.tryUnblockFailedWorkflowInstances(
workflowId, Constants.UNBLOCK_BATCH_SIZE, eventBuilder.build());
totalUnblocked += unblocked;
}
workflowHelper.publishStartWorkflowEvent(workflowId, totalUnblocked > 0);
return eventBuilder
.message("Unblocked [%s] failed workflow instances.", totalUnblocked)
.build();
}
|
@Test
public void testUnblockReachingLimit() {
when(instanceDao.tryUnblockFailedWorkflowInstances(eq("sample-minimal-wf"), anyInt(), any()))
.thenReturn(Constants.UNBLOCK_BATCH_SIZE)
.thenReturn(10);
TimelineEvent event = actionHandler.unblock("sample-minimal-wf", tester);
assertEquals("Unblocked [110] failed workflow instances.", event.getMessage());
verify(maestroJobEventPublisher, times(1)).publishOrThrow(any(StartWorkflowJobEvent.class));
}
|
static Map<String, String> toMap(List<Settings.Setting> settingsList) {
Map<String, String> result = new LinkedHashMap<>();
for (Settings.Setting s : settingsList) {
// we need the "*.file.suffixes" and "*.file.patterns" properties for language detection
// see DefaultLanguagesRepository.populateFileSuffixesAndPatterns()
if (!s.getInherited() || s.getKey().endsWith(".file.suffixes") || s.getKey().endsWith(".file.patterns")) {
switch (s.getValueOneOfCase()) {
case VALUE:
result.put(s.getKey(), s.getValue());
break;
case VALUES:
result.put(s.getKey(), s.getValues().getValuesList().stream().map(StringEscapeUtils::escapeCsv).collect(Collectors.joining(",")));
break;
case FIELDVALUES:
convertPropertySetToProps(result, s);
break;
default:
if (!s.getKey().endsWith(".secured")) {
throw new IllegalStateException("Unknown property value for " + s.getKey());
}
}
}
}
return result;
}
|
@Test
public void should_filter_secured_settings_without_value() {
assertThat(AbstractSettingsLoader.toMap(singletonList(Setting.newBuilder()
.setKey("sonar.setting.secured").build())))
.isEmpty();
}
|
public Optional<KsMaterialization> create(
final String stateStoreName,
final KafkaStreams kafkaStreams,
final Topology topology,
final LogicalSchema schema,
final Serializer<GenericKey> keySerializer,
final Optional<WindowInfo> windowInfo,
final Map<String, ?> streamsProperties,
final KsqlConfig ksqlConfig,
final String applicationId,
final String queryId
) {
final Object appServer = streamsProperties.get(StreamsConfig.APPLICATION_SERVER_CONFIG);
if (appServer == null) {
return Optional.empty();
}
final URL localHost = buildLocalHost(appServer);
final KsLocator locator = locatorFactory.create(
stateStoreName,
kafkaStreams,
topology,
keySerializer,
localHost,
ksqlConfig.getBoolean(KsqlConfig.KSQL_SHARED_RUNTIME_ENABLED),
queryId
);
final KsStateStore stateStore = storeFactory.create(
stateStoreName,
kafkaStreams,
schema,
ksqlConfig,
queryId
);
final KsMaterialization materialization = materializationFactory.create(
windowInfo,
locator,
stateStore
);
return Optional.of(materialization);
}
|
@Test
public void shouldBuildLocatorWithCorrectParams() {
// When:
factory.create(STORE_NAME, kafkaStreams, topology, SCHEMA, keySerializer, Optional.empty(),
streamsProperties, ksqlConfig, APPLICATION_ID, "queryId");
// Then:
verify(locatorFactory).create(
STORE_NAME,
kafkaStreams,
topology,
keySerializer,
DEFAULT_APP_SERVER,
false,
"queryId"
);
}
|
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
}
|
@Test
public void sendVoice() {
Message message = bot.execute(new SendVoice(chatId, voiceFileId)).message();
MessageTest.checkMessage(message);
VoiceTest.check(message.voice(), false);
message = bot.execute(new SendVoice(chatId, audioFile)).message();
MessageTest.checkMessage(message);
VoiceTest.check(message.voice());
String caption = "caption <b>bold</b>";
int duration = 100;
message = bot.execute(new SendVoice(chatId, audioBytes).caption(caption).parseMode(ParseMode.HTML).duration(duration)).message();
MessageTest.checkMessage(message);
assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
VoiceTest.check(message.voice());
assertEquals(duration, message.voice().duration().intValue());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals(8, captionEntity.offset().intValue());
assertEquals(4, captionEntity.length().intValue());
}
|
public StainingRule getStainingRule() {
return stainingRule;
}
|
@Test
public void testEmptyRule() {
RuleStainingProperties ruleStainingProperties = new RuleStainingProperties();
ruleStainingProperties.setNamespace(testNamespace);
ruleStainingProperties.setGroup(testGroup);
ruleStainingProperties.setFileName(testFileName);
ConfigFile configFile = Mockito.mock(ConfigFile.class);
when(configFile.getContent()).thenReturn(null);
when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile);
StainingRuleManager stainingRuleManager = new StainingRuleManager(ruleStainingProperties, configFileService);
assertThat(stainingRuleManager.getStainingRule()).isNull();
}
|
@Override
public void onPartitionsDeleted(
List<TopicPartition> topicPartitions,
BufferSupplier bufferSupplier
) throws ExecutionException, InterruptedException {
throwIfNotActive();
CompletableFuture.allOf(
FutureUtils.mapExceptionally(
runtime.scheduleWriteAllOperation(
"on-partition-deleted",
Duration.ofMillis(config.offsetCommitTimeoutMs()),
coordinator -> coordinator.onPartitionsDeleted(topicPartitions)
),
exception -> {
log.error("Could not delete offsets for deleted partitions {} due to: {}.",
topicPartitions, exception.getMessage(), exception
);
return null;
}
).toArray(new CompletableFuture[0])
).get();
}
|
@Test
public void testOnPartitionsDeleted() {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
new GroupCoordinatorMetrics(),
createConfigManager()
);
service.startup(() -> 3);
when(runtime.scheduleWriteAllOperation(
ArgumentMatchers.eq("on-partition-deleted"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
)).thenReturn(Arrays.asList(
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null),
FutureUtils.failedFuture(Errors.COORDINATOR_LOAD_IN_PROGRESS.exception())
));
// The exception is logged and swallowed.
assertDoesNotThrow(() ->
service.onPartitionsDeleted(
Collections.singletonList(new TopicPartition("foo", 0)),
BufferSupplier.NO_CACHING
)
);
}
|
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
}
|
@Test
void should_show_help() {
// Given
String query = "HELP;";
final String expected = reformatHtml(readTestResource("/scalate/Help.html"));
// When
final InterpreterResult actual = interpreter.interpret(query, intrContext);
// Then
assertEquals(Code.SUCCESS, actual.code());
assertTrue(reformatHtml(actual.message().get(0).getData()).contains(expected),
reformatHtml(actual.message().get(0).getData()));
}
|
public Concept getRoot() {
return root;
}
|
@Test
public void testGetPathToRoot() {
System.out.println("getPathToRoot");
LinkedList<Concept> expResult = new LinkedList<>();
expResult.addFirst(taxonomy.getRoot());
expResult.addFirst(ad);
expResult.addFirst(a);
expResult.addFirst(c);
expResult.addFirst(f);
List<Concept> result = f.getPathToRoot();
assertEquals(expResult, result);
}
|
@Override
public List<Spell> findAllSpells() {
return spellDao.findAll();
}
|
@Test
void testFindAllSpells() {
final var wizardDao = mock(WizardDao.class);
final var spellbookDao = mock(SpellbookDao.class);
final var spellDao = mock(SpellDao.class);
final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);
verifyNoInteractions(wizardDao, spellbookDao, spellDao);
service.findAllSpells();
verify(spellDao).findAll();
verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao);
}
|
@Override
public void declareResourceRequirements(ResourceRequirements resourceRequirements) {
synchronized (lock) {
checkNotClosed();
if (isConnected()) {
currentResourceRequirements = resourceRequirements;
triggerResourceRequirementsSubmission(
Duration.ofMillis(1L),
Duration.ofMillis(10000L),
currentResourceRequirements);
}
}
}
|
@Test
void testRetryDeclareResourceRequirementsIfTransmissionFailed() throws InterruptedException {
final DeclareResourceRequirementServiceConnectionManager
declareResourceRequirementServiceConnectionManager =
createResourceManagerConnectionManager();
final FailingDeclareResourceRequirementsService failingDeclareResourceRequirementsService =
new FailingDeclareResourceRequirementsService(4);
declareResourceRequirementServiceConnectionManager.connect(
failingDeclareResourceRequirementsService);
final ResourceRequirements resourceRequirements = createResourceRequirements();
declareResourceRequirementServiceConnectionManager.declareResourceRequirements(
resourceRequirements);
scheduledExecutor.triggerNonPeriodicScheduledTasksWithRecursion();
assertThat(failingDeclareResourceRequirementsService.nextResourceRequirements())
.isEqualTo(resourceRequirements);
assertThat(failingDeclareResourceRequirementsService.hasResourceRequirements()).isFalse();
}
|
public B validation(String validation) {
this.validation = validation;
return getThis();
}
|
@Test
void validation() {
MethodBuilder builder = new MethodBuilder();
builder.validation("validation");
Assertions.assertEquals("validation", builder.build().getValidation());
}
|
OutputT apply(InputT input) throws UserCodeExecutionException {
Optional<UserCodeExecutionException> latestError = Optional.empty();
long waitFor = 0L;
while (waitFor != BackOff.STOP) {
try {
sleepIfNeeded(waitFor);
incIfPresent(getCallCounter());
return getThrowableFunction().apply(input);
} catch (UserCodeExecutionException e) {
if (!e.shouldRepeat()) {
throw e;
}
latestError = Optional.of(e);
} catch (InterruptedException ignored) {
}
try {
incIfPresent(getBackoffCounter());
waitFor = getBackOff().nextBackOffMillis();
} catch (IOException e) {
throw new UserCodeExecutionException(e);
}
}
throw latestError.orElse(
new UserCodeExecutionException("failed to process for input: " + input));
}
|
@Test
public void givenSetupNonRepeatableError_throws() {
pipeline
.apply(Create.of(1))
.apply(
ParDo.of(
new DoFnWithRepeaters(
new CallerImpl(0),
new SetupTeardownImpl(1, UserCodeExecutionException.class)))
.withOutputTags(OUTPUT_TAG, TupleTagList.of(FAILURE_TAG)));
UncheckedExecutionException thrown =
assertThrows(UncheckedExecutionException.class, pipeline::run);
assertThat(thrown.getCause(), allOf(notNullValue(), instanceOf(UserCodeException.class)));
assertThat(
thrown.getCause().getCause(),
allOf(notNullValue(), instanceOf(UserCodeExecutionException.class)));
}
|
private boolean exemptedByName(Name name) {
String nameString = name.toString();
String nameStringLower = Ascii.toLowerCase(nameString);
return exemptPrefixes.stream().anyMatch(nameStringLower::startsWith)
|| exemptNames.contains(nameString);
}
|
@Test
public void exemptedByName() {
helper
.addSourceLines(
"Unuseds.java",
"package unusedvars;",
"class ExemptedByName {",
" private int unused;",
" private int unusedInt;",
" private static final int UNUSED_CONSTANT = 5;",
" private int ignored;",
" private int customUnused1;",
" private int customUnused2;",
" private int prefixUnused1Field;",
" private int prefixUnused2Field;",
"}")
.setArgs(
"-XepOpt:Unused:exemptNames=customUnused1,customUnused2",
"-XepOpt:Unused:exemptPrefixes=prefixunused1,prefixunused2")
.doTest();
}
|
@Override
public boolean hasMoreTokens()
{
// Already found a token
if (_hasToken)
return true;
_lastStart = _i;
int state = 0;
boolean escape = false;
while (_i < _string.length())
{
char c = _string.charAt(_i++);
switch (state)
{
case 0: // Start
if (_delim.indexOf(c) >= 0)
{
if (_returnDelimiters)
{
_token.append(c);
return _hasToken = true;
}
}
else if (c == '\'' && _single)
{
if (_returnQuotes)
_token.append(c);
state = 2;
}
else if (c == '\"' && _double)
{
if (_returnQuotes)
_token.append(c);
state = 3;
}
else
{
_token.append(c);
_hasToken = true;
state = 1;
}
continue;
case 1: // Token
_hasToken = true;
if (escape)
{
escape = false;
if (ESCAPABLE_CHARS.indexOf(c) < 0)
_token.append('\\');
_token.append(c);
}
else if (_delim.indexOf(c) >= 0)
{
if (_returnDelimiters)
_i--;
return _hasToken;
}
else if (c == '\'' && _single)
{
if (_returnQuotes)
_token.append(c);
state = 2;
}
else if (c == '\"' && _double)
{
if (_returnQuotes)
_token.append(c);
state = 3;
}
else if (c == '\\')
{
escape = true;
}
else
_token.append(c);
continue;
case 2: // Single Quote
_hasToken = true;
if (escape)
{
escape = false;
if (ESCAPABLE_CHARS.indexOf(c) < 0)
_token.append('\\');
_token.append(c);
}
else if (c == '\'')
{
if (_returnQuotes)
_token.append(c);
state = 1;
}
else if (c == '\\')
{
if (_returnQuotes)
_token.append(c);
escape = true;
}
else
_token.append(c);
continue;
case 3: // Double Quote
_hasToken = true;
if (escape)
{
escape = false;
if (ESCAPABLE_CHARS.indexOf(c) < 0)
_token.append('\\');
_token.append(c);
}
else if (c == '\"')
{
if (_returnQuotes)
_token.append(c);
state = 1;
}
else if (c == '\\')
{
if (_returnQuotes)
_token.append(c);
escape = true;
}
else
_token.append(c);
continue;
default:
break;
}
}
return _hasToken;
}
|
@Test
public void testHasMoreToken() {
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer("");
assertFalse(tokenizer.hasMoreTokens());
tokenizer = new QuotedStringTokenizer("one");
assertTrue(tokenizer.hasMoreTokens());
}
|
@Override
public String getMessage() {
return message;
}
|
@Test
final void requireNoMessageIsOK() {
final Throwable t = new Throwable();
final ExceptionWrapper e = new ExceptionWrapper(t);
final String expected = "Throwable() at com.yahoo.jdisc.http.server.jetty.ExceptionWrapperTest(ExceptionWrapperTest.java:19)";
assertThat(e.getMessage(), equalTo(expected));
}
|
@Override
public Reiterator<ShuffleEntry> read(
@Nullable ShufflePosition startPosition, @Nullable ShufflePosition endPosition) {
return new ShuffleReadIterator(startPosition, endPosition);
}
|
@Test
public void readerIteratorCanBeCopied() throws Exception {
ShuffleEntry e1 = newShuffleEntry(KEY, SKEY, VALUE);
ShuffleEntry e2 = newShuffleEntry(KEY, SKEY, VALUE);
ArrayList<ShuffleEntry> entries = new ArrayList<>();
entries.add(e1);
entries.add(e2);
when(batchReader.read(START_POSITION, END_POSITION))
.thenReturn(new ShuffleBatchReader.Batch(entries, null));
Reiterator<ShuffleEntry> it = reader.read(START_POSITION, END_POSITION);
assertThat(it.hasNext(), equalTo(Boolean.TRUE));
assertThat(it.next(), equalTo(e1));
Reiterator<ShuffleEntry> copy = it.copy();
assertThat(it.hasNext(), equalTo(Boolean.TRUE));
assertThat(it.next(), equalTo(e2));
assertThat(it.hasNext(), equalTo(Boolean.FALSE));
assertThat(copy.hasNext(), equalTo(Boolean.TRUE));
assertThat(copy.next(), equalTo(e2));
assertThat(copy.hasNext(), equalTo(Boolean.FALSE));
}
|
@SuppressWarnings("unused") // Required for automatic type inference
public static <K> Builder0<K> forClass(final Class<K> type) {
return new Builder0<>();
}
|
@Test(expected = IllegalArgumentException.class)
public void shouldThrowOnDuplicateKey2() {
HandlerMaps.forClass(BaseType.class).withArgTypes(String.class, Integer.class)
.put(LeafTypeA.class, handler2_1)
.put(LeafTypeA.class, handler2_2);
}
|
@Override
public OAuth2AccessToken extract(Response response) throws IOException {
if (response.getCode() != 200) {
throw new OAuthException("Response code is not 200 but '" + response.getCode() + '\'');
}
final String body = response.getBody();
Preconditions.checkEmptyString(body,
"Response body is incorrect. Can't extract a token from an empty string");
final String accessToken = extractParameter(body, ACCESS_TOKEN_REGEX_PATTERN, true);
final String tokenType = extractParameter(body, TOKEN_TYPE_REGEX_PATTERN, false);
final String expiresInString = extractParameter(body, EXPIRES_IN_REGEX_PATTERN, false);
Integer expiresIn;
try {
expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString);
} catch (NumberFormatException nfe) {
expiresIn = null;
}
final String refreshToken = extractParameter(body, REFRESH_TOKEN_REGEX_PATTERN, false);
final String scope = extractParameter(body, SCOPE_REGEX_PATTERN, false);
return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, body);
}
|
@Test
public void shouldExtractTokenFromResponseWithExpiresParam() throws IOException {
final String responseBody = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159"
+ "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108";
final OAuth2AccessToken extracted;
try (Response response = ok(responseBody)) {
extracted = extractor.extract(response);
}
assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE",
extracted.getAccessToken());
assertEquals(Integer.valueOf(5108), extracted.getExpiresIn());
}
|
@Override
public boolean equals(final Object obj) {
return this == obj || null != obj && getClass() == obj.getClass() && equalsByProperties((DataSourcePoolProperties) obj);
}
|
@SuppressWarnings({"SimplifiableAssertion", "ConstantValue"})
@Test
void assertNotEqualsWithNullValue() {
assertFalse(new DataSourcePoolProperties(MockedDataSource.class.getName(), Collections.emptyMap()).equals(null));
}
|
@Override
public boolean test(Collection<V> buffer) {
if (buffer.size() >= this.batchSize) {
this.nextDate();
return true;
}
if (buffer.size() > 0 && this.next.isBefore(Instant.now())) {
this.nextDate();
return true;
}
return false;
}
|
@Test
public void testBySize() {
HashMap<String, String> map = generateHashMap(99);
assertFalse(trigger.test(map.values()));
map.put("test", "b");
assertTrue(trigger.test(map.values()));
}
|
public int read(final MessageHandler handler)
{
return read(handler, Integer.MAX_VALUE);
}
|
@Test
void shouldLimitReadOfMessages()
{
final int msgLength = 16;
final int recordLength = HEADER_LENGTH + msgLength;
final int alignedRecordLength = align(recordLength, ALIGNMENT);
final long head = 0L;
final int headIndex = (int)head;
when(buffer.getLong(HEAD_COUNTER_INDEX)).thenReturn(head);
when(buffer.getInt(typeOffset(headIndex))).thenReturn(MSG_TYPE_ID);
when(buffer.getIntVolatile(lengthOffset(headIndex))).thenReturn(recordLength);
final MutableInteger times = new MutableInteger();
final MessageHandler handler = (msgTypeId, buffer, index, length) -> times.increment();
final int limit = 1;
final int messagesRead = ringBuffer.read(handler, limit);
assertThat(messagesRead, is(1));
assertThat(times.get(), is(1));
final InOrder inOrder = inOrder(buffer);
inOrder.verify(buffer, times(1)).putLongOrdered(HEAD_COUNTER_INDEX, head + alignedRecordLength);
inOrder.verify(buffer, times(0)).setMemory(anyInt(), anyInt(), anyByte());
}
|
@Override
public DictTypeDO getDictType(Long id) {
return dictTypeMapper.selectById(id);
}
|
@Test
public void testGetDictType_id() {
// mock 数据
DictTypeDO dbDictType = randomDictTypeDO();
dictTypeMapper.insert(dbDictType);
// 准备参数
Long id = dbDictType.getId();
// 调用
DictTypeDO dictType = dictTypeService.getDictType(id);
// 断言
assertNotNull(dictType);
assertPojoEquals(dbDictType, dictType);
}
|
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = models.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = 0;
for (int i = 0; i < ntrees; i++) {
base = base + models[i].tree.predict(xj);
prediction[i][j] = base / (i+1);
}
}
return prediction;
}
|
@Test
public void testPuma8nh() {
test("puma8nh", Puma8NH.formula, Puma8NH.data, 3.3145);
}
|
public Set<Rule<?>> rules()
{
return ImmutableSet.of(
checkRulesAreFiredBeforeAddExchangesRule(),
pickTableLayoutForPredicate(),
pickTableLayoutWithoutPredicate());
}
|
@Test
public void doesNotFireIfNoTableScan()
{
for (Rule<?> rule : pickTableLayout.rules()) {
tester().assertThat(rule)
.on(p -> p.values(p.variable("a", BIGINT)))
.doesNotFire();
}
}
|
public ScalarOperator rewrite(ScalarOperator root, List<ScalarOperatorRewriteRule> ruleList) {
ScalarOperator result = root;
context.reset();
int changeNums;
do {
changeNums = context.changeNum();
for (ScalarOperatorRewriteRule rule : ruleList) {
result = rewriteByRule(result, rule);
}
if (changeNums > Config.max_planner_scalar_rewrite_num) {
throw new StarRocksPlannerException("Planner rewrite scalar operator over limit",
ErrorType.INTERNAL_ERROR);
}
} while (changeNums != context.changeNum());
return result;
}
|
@Test
public void testRewrite() {
ScalarOperator root = new CompoundPredicateOperator(CompoundPredicateOperator.CompoundType.OR,
new BetweenPredicateOperator(false, new ColumnRefOperator(3, Type.INT, "test3", true),
new ColumnRefOperator(4, Type.INT, "test4", true),
new ColumnRefOperator(5, Type.INT, "test5", true)),
new CompoundPredicateOperator(CompoundPredicateOperator.CompoundType.AND,
new BinaryPredicateOperator(BinaryType.EQ,
ConstantOperator.createInt(1),
new ColumnRefOperator(1, Type.INT, "test1", true)),
new BinaryPredicateOperator(BinaryType.EQ,
ConstantOperator.createInt(1),
new ColumnRefOperator(2, Type.INT, "test2", true))
));
ScalarOperatorRewriter operatorRewriter = new ScalarOperatorRewriter();
ScalarOperator result = operatorRewriter
.rewrite(root, Lists.newArrayList(new NormalizePredicateRule(), new SimplifiedPredicateRule()));
assertEquals(root, result);
assertEquals(OperatorType.COMPOUND, result.getChild(0).getOpType());
assertTrue(result.getChild(0) instanceof CompoundPredicateOperator);
assertEquals(CompoundPredicateOperator.CompoundType.AND,
((CompoundPredicateOperator) result.getChild(0)).getCompoundType());
assertEquals(OperatorType.BINARY, result.getChild(0).getChild(0).getOpType());
assertEquals(OperatorType.BINARY, result.getChild(0).getChild(1).getOpType());
assertEquals(OperatorType.COMPOUND, result.getChild(1).getOpType());
assertEquals(OperatorType.BINARY, result.getChild(1).getChild(0).getOpType());
assertEquals(OperatorType.VARIABLE, result.getChild(1).getChild(0).getChild(0).getOpType());
assertEquals(OperatorType.CONSTANT, result.getChild(1).getChild(0).getChild(1).getOpType());
assertEquals(OperatorType.BINARY, result.getChild(1).getChild(1).getOpType());
assertEquals(OperatorType.VARIABLE, result.getChild(1).getChild(1).getChild(0).getOpType());
assertEquals(OperatorType.CONSTANT, result.getChild(1).getChild(1).getChild(1).getOpType());
}
|
@Override
public Num calculate(BarSeries series, Position position) {
return isBreakEvenPosition(position) ? series.one() : series.zero();
}
|
@Test
public void calculateWithTwoShortPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(3, series),
Trade.sellAt(1, series), Trade.buyAt(5, series));
assertNumEquals(2, getCriterion().calculate(series, tradingRecord));
}
|
@VisibleForTesting
void updateQueues(String args, SchedConfUpdateInfo updateInfo) {
if (args == null) {
return;
}
ArrayList<QueueConfigInfo> queueConfigInfos = new ArrayList<>();
for (String arg : args.split(";")) {
queueConfigInfos.add(getQueueConfigInfo(arg));
}
updateInfo.setUpdateQueueInfo(queueConfigInfos);
}
|
@Test(timeout = 10000)
public void testUpdateQueues() {
SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo();
Map<String, String> paramValues = new HashMap<>();
cli.updateQueues("root.a:a1=aVal1,a2=aVal2,a3=", schedUpdateInfo);
List<QueueConfigInfo> updateQueueInfo = schedUpdateInfo
.getUpdateQueueInfo();
paramValues.put("a1", "aVal1");
paramValues.put("a2", "aVal2");
paramValues.put("a3", null);
validateQueueConfigInfo(updateQueueInfo, 0, "root.a", paramValues);
schedUpdateInfo = new SchedConfUpdateInfo();
cli.updateQueues("root.b:b1=bVal1;root.c:c1=cVal1", schedUpdateInfo);
updateQueueInfo = schedUpdateInfo.getUpdateQueueInfo();
assertEquals(2, updateQueueInfo.size());
paramValues.clear();
paramValues.put("b1", "bVal1");
validateQueueConfigInfo(updateQueueInfo, 0, "root.b", paramValues);
paramValues.clear();
paramValues.put("c1", "cVal1");
validateQueueConfigInfo(updateQueueInfo, 1, "root.c", paramValues);
}
|
public long readInt6() {
long result = 0L;
for (int i = 0; i < 6; i++) {
result |= ((long) (0xff & byteBuf.readByte())) << (8 * i);
}
return result;
}
|
@Test
void assertReadInt6() {
when(byteBuf.readByte()).thenReturn((byte) 0x01, (byte) 0x00);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt6(), is(1L));
when(byteBuf.readByte()).thenReturn((byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt6(), is(0x800000000000L));
}
|
public void syncFileResource(ResourceUri resourceUri, Consumer<String> resourceGenerator)
throws IOException {
Path targetPath = new Path(resourceUri.getUri());
String localPath;
boolean remote = isRemotePath(targetPath);
if (remote) {
localPath = getResourceLocalPath(targetPath).getPath();
} else {
localPath = getURLFromPath(targetPath).getPath();
}
resourceGenerator.accept(localPath);
if (remote) {
if (exists(targetPath)) {
// FileUtils#copy will not do copy if targetPath already exists
targetPath.getFileSystem().delete(targetPath, false);
}
FileUtils.copy(new Path(localPath), targetPath, false);
}
}
|
@Test
public void testSyncFileResource() throws Exception {
String targetUri = tempFolder.getAbsolutePath() + "foo/bar.txt";
ResourceUri resource = new ResourceUri(ResourceType.FILE, targetUri);
resourceManager.syncFileResource(
resource,
path -> {
try {
FileUtils.copy(new Path(file.getPath()), new Path(path), false);
} catch (IOException e) {
fail("Test failed.", e);
}
});
assertThat(FileUtils.readFileUtf8(new File(targetUri))).isEqualTo("Hello World");
// test overwrite
resourceManager.syncFileResource(
resource,
path -> {
try {
Files.write(
new File(targetUri).toPath(),
"Bye Bye".getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE);
} catch (IOException e) {
fail("Test failed.", e);
}
});
assertThat(FileUtils.readFileUtf8(new File(targetUri))).isEqualTo("Bye Bye");
}
|
public Map<String, Double> toNormalizedMap() {
Map<String, Double> ret = this.normalizedResources.toNormalizedMap();
ret.put(Constants.COMMON_OFFHEAP_MEMORY_RESOURCE_NAME, offHeap);
ret.put(Constants.COMMON_ONHEAP_MEMORY_RESOURCE_NAME, onHeap);
return ret;
}
|
@Test
public void testAckerCPUSetting() {
Map<String, Object> topoConf = new HashMap<>();
topoConf.put(Config.TOPOLOGY_ACKER_CPU_PCORE_PERCENT, 40);
topoConf.put(Config.TOPOLOGY_COMPONENT_CPU_PCORE_PERCENT, 50);
NormalizedResourceRequest request = new NormalizedResourceRequest(topoConf, Acker.ACKER_COMPONENT_ID);
Map<String, Double> normalizedMap = request.toNormalizedMap();
Double cpu = normalizedMap.get(Constants.COMMON_CPU_RESOURCE_NAME);
assertNotNull(cpu);
assertEquals(40, cpu, 0.001);
}
|
public static String trimComment(final String sql) {
String result = sql;
if (sql.startsWith(COMMENT_PREFIX)) {
result = result.substring(sql.indexOf(COMMENT_SUFFIX) + 2);
}
if (sql.endsWith(SQL_END)) {
result = result.substring(0, result.length() - 1);
}
return result.trim();
}
|
@Test
void assertTrimComment() {
assertThat(SQLUtils.trimComment("/* This is a comment */ SHOW DATABASES"), is("SHOW DATABASES"));
assertThat(SQLUtils.trimComment("/* This is a query with a semicolon */ SHOW DATABASES;"), is("SHOW DATABASES"));
assertThat(SQLUtils.trimComment("/* This is a query with spaces */ SHOW DATABASES "), is("SHOW DATABASES"));
}
|
public void startFunction(FunctionRuntimeInfo functionRuntimeInfo) {
try {
FunctionMetaData functionMetaData = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData();
FunctionDetails functionDetails = functionMetaData.getFunctionDetails();
int instanceId = functionRuntimeInfo.getFunctionInstance().getInstanceId();
log.info("{}/{}/{}-{} Starting function ...", functionDetails.getTenant(), functionDetails.getNamespace(),
functionDetails.getName(), instanceId);
String packageFile;
String transformFunctionPackageFile = null;
Function.PackageLocationMetaData pkgLocation = functionMetaData.getPackageLocation();
Function.PackageLocationMetaData transformFunctionPkgLocation =
functionMetaData.getTransformFunctionPackageLocation();
if (runtimeFactory.externallyManaged()) {
packageFile = pkgLocation.getPackagePath();
transformFunctionPackageFile = transformFunctionPkgLocation.getPackagePath();
} else {
packageFile = getPackageFile(functionMetaData, functionDetails, instanceId, pkgLocation,
InstanceUtils.calculateSubjectType(functionDetails));
if (!isEmpty(transformFunctionPkgLocation.getPackagePath())) {
transformFunctionPackageFile =
getPackageFile(functionMetaData, functionDetails, instanceId, transformFunctionPkgLocation,
FunctionDetails.ComponentType.FUNCTION);
}
}
// Setup for batch sources if necessary
setupBatchSource(functionDetails);
RuntimeSpawner runtimeSpawner = getRuntimeSpawner(functionRuntimeInfo.getFunctionInstance(),
packageFile, transformFunctionPackageFile);
functionRuntimeInfo.setRuntimeSpawner(runtimeSpawner);
runtimeSpawner.start();
} catch (Exception ex) {
FunctionDetails details = functionRuntimeInfo.getFunctionInstance()
.getFunctionMetaData().getFunctionDetails();
log.error("{}/{}/{} Error starting function", details.getTenant(), details.getNamespace(),
details.getName(), ex);
functionRuntimeInfo.setStartupException(ex);
}
}
|
@Test
public void testStartFunctionWithPkgUrl() throws Exception {
WorkerConfig workerConfig = new WorkerConfig();
workerConfig.setWorkerId("worker-1");
workerConfig.setFunctionRuntimeFactoryClassName(ThreadRuntimeFactory.class.getName());
workerConfig.setFunctionRuntimeFactoryConfigs(
ObjectMapperFactory.getMapper().getObjectMapper().convertValue(
new ThreadRuntimeFactoryConfig().setThreadGroupName("test"), Map.class));
workerConfig.setPulsarServiceUrl("pulsar://localhost:6650");
workerConfig.setStateStorageServiceUrl("foo");
workerConfig.setFunctionAssignmentTopicName("assignments");
workerConfig.setAdditionalEnabledFunctionsUrlPatterns(List.of("file:///user/.*", "http://invalid/.*"));
workerConfig.setAdditionalEnabledConnectorUrlPatterns(List.of("file:///user/.*", "http://invalid/.*"));
String downloadDir = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
workerConfig.setDownloadDirectory(downloadDir);
RuntimeFactory factory = mock(RuntimeFactory.class);
Runtime runtime = mock(Runtime.class);
doReturn(runtime).when(factory).createContainer(any(), any(), any(), any(), any(), any());
doNothing().when(runtime).start();
Namespace dlogNamespace = mock(Namespace.class);
final String exceptionMsg = "dl namespace not-found";
doThrow(new IllegalArgumentException(exceptionMsg)).when(dlogNamespace).openLog(any());
@SuppressWarnings("resource")
FunctionActioner actioner = new FunctionActioner(workerConfig, factory, dlogNamespace,
new ConnectorsManager(workerConfig), new FunctionsManager(workerConfig), mock(PulsarAdmin.class),
new PackageUrlValidator(workerConfig));
// (1) test with file url. functionActioner should be able to consider file-url and it should be able to call
// RuntimeSpawner
String pkgPathLocation = FILE + ":///user/my-file.jar";
startFunction(actioner, pkgPathLocation, pkgPathLocation);
verify(runtime, times(1)).start();
// (2) test with http-url, downloading file from http should fail with UnknownHostException due to invalid url
String invalidPkgPathLocation = "http://invalid/my-file.jar";
try {
startFunction(actioner, invalidPkgPathLocation, pkgPathLocation);
fail();
} catch (IllegalStateException ex) {
assertEquals(ex.getMessage(), "StartupException");
}
try {
startFunction(actioner, pkgPathLocation, invalidPkgPathLocation);
fail();
} catch (IllegalStateException ex) {
assertEquals(ex.getMessage(), "StartupException");
}
}
|
@Override
public Option<IndexedRecord> getInsertValue(Schema schema, Properties properties) throws IOException {
return getInsertValue(schema);
}
|
@Test
public void testInsert() {
Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING);
GenericRecord record = new GenericData.Record(avroSchema);
Properties properties = new Properties();
record.put("field1", 0);
record.put("Op", "I");
AWSDmsAvroPayload payload = new AWSDmsAvroPayload(Option.of(record));
try {
Option<IndexedRecord> outputPayload = payload.getInsertValue(avroSchema, properties);
assertTrue((int) outputPayload.get().get(0) == 0);
assertTrue(outputPayload.get().get(1).toString().equals("I"));
} catch (Exception e) {
fail("Unexpected exception");
}
}
|
@Override
public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
left = mark;
}
|
@Test(expected = IOException.class)
public void testResetWithoutMark() throws IOException {
try (LimitInputStream limitInputStream =
new LimitInputStream(new RandomInputStream(), 128)) {
limitInputStream.reset();
}
}
|
Object getCellValue(Cell cell, Schema.FieldType type) {
ByteString cellValue = cell.getValue();
int valueSize = cellValue.size();
switch (type.getTypeName()) {
case BOOLEAN:
checkArgument(valueSize == 1, message("Boolean", 1));
return cellValue.toByteArray()[0] != 0;
case BYTE:
checkArgument(valueSize == 1, message("Byte", 1));
return cellValue.toByteArray()[0];
case INT16:
checkArgument(valueSize == 2, message("Int16", 2));
return Shorts.fromByteArray(cellValue.toByteArray());
case INT32:
checkArgument(valueSize == 4, message("Int32", 4));
return Ints.fromByteArray(cellValue.toByteArray());
case INT64:
checkArgument(valueSize == 8, message("Int64", 8));
return Longs.fromByteArray(cellValue.toByteArray());
case FLOAT:
checkArgument(valueSize == 4, message("Float", 4));
return Float.intBitsToFloat(Ints.fromByteArray(cellValue.toByteArray()));
case DOUBLE:
checkArgument(valueSize == 8, message("Double", 8));
return Double.longBitsToDouble(Longs.fromByteArray(cellValue.toByteArray()));
case DATETIME:
return DateTime.parse(cellValue.toStringUtf8());
case STRING:
return cellValue.toStringUtf8();
case BYTES:
return cellValue.toByteArray();
case LOGICAL_TYPE:
String identifier = checkArgumentNotNull(type.getLogicalType()).getIdentifier();
throw new IllegalStateException("Unsupported logical type: " + identifier);
default:
throw new IllegalArgumentException(
String.format("Unsupported cell value type '%s'.", type.getTypeName()));
}
}
|
@Test
public void shouldFailParseInt64TypeTooLong() {
byte[] value = new byte[10];
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> PARSER.getCellValue(cell(value), INT64));
checkMessage(exception.getMessage(), "Int64 has to be 8-bytes long bytearray");
}
|
@PostConstruct
public void applyPluginMetadata() {
if (taskPreference() != null) {
for (ConfigurationProperty configurationProperty : configuration) {
if (isValidPluginConfiguration(configurationProperty.getConfigKeyName())) {
Boolean isSecure = pluginConfigurationFor(configurationProperty.getConfigKeyName()).getOption(Property.SECURE);
configurationProperty.handleSecureValueConfiguration(isSecure);
}
}
}
}
|
@Test
public void postConstructShouldHandleSecureConfigurationForConfigurationProperties() throws Exception {
TaskPreference taskPreference = mock(TaskPreference.class);
ConfigurationProperty configurationProperty = ConfigurationPropertyMother.create("KEY1");
Configuration configuration = new Configuration(configurationProperty);
PluggableTaskConfigStore.store().setPreferenceFor("abc.def", taskPreference);
TaskConfig taskConfig = new TaskConfig();
taskConfig.addProperty("KEY1").with(Property.SECURE, true);
when(taskPreference.getConfig()).thenReturn(taskConfig);
PluggableTask task = new PluggableTask(new PluginConfiguration("abc.def", "1"), configuration);
assertFalse(configurationProperty.isSecure());
task.applyPluginMetadata();
assertTrue(configurationProperty.isSecure());
}
|
@Override
public boolean noServicesOutsideGroupIsDown() throws HostStateChangeDeniedException {
return servicesDownAndNotInGroup().size() + missingServices == 0;
}
|
@Test
public void testUnknownServiceStatusInGroup() throws HostStateChangeDeniedException {
ClusterApi clusterApi = makeClusterApiWithUnknownStatus(ServiceStatus.UNKNOWN, ServiceStatus.UP, ServiceStatus.UP);
clusterApi.noServicesOutsideGroupIsDown();
}
|
public void registerStrategy(BatchingStrategy<?, ?, ?> strategy) {
_strategies.add(strategy);
}
|
@Test
public void testDeduplication() {
RecordingStrategy<Integer, Integer, String> strategy =
new RecordingStrategy<>((key, promise) -> promise.done(String.valueOf(key)), key -> key % 2);
_batchingSupport.registerStrategy(strategy);
Task<String> task = Task.par(strategy.batchable(0), strategy.batchable(1), strategy.batchable(2),
strategy.batchable(0), strategy.batchable(1), strategy.batchable(2))
.map("concat", (s0, s1, s2, s3, s4, s5) -> s0 + s1 + s2 + s3 + s4 + s5);
String result = runAndWait("TestBatchingSupport.testDeduplication", task);
assertEquals(result, "012012");
assertTrue(strategy.getClassifiedKeys().contains(0));
assertTrue(strategy.getClassifiedKeys().contains(1));
assertTrue(strategy.getClassifiedKeys().contains(2));
assertEquals(strategy.getExecutedBatches().size(), 1);
assertEquals(strategy.getExecutedSingletons().size(), 1);
}
|
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
if (transactionManager.hasFatalError()) {
if (lastError != null)
maybeAbortBatches(lastError);
client.poll(retryBackoffMs, time.milliseconds());
return;
}
if (transactionManager.hasAbortableError() && shouldHandleAuthorizationError(lastError)) {
return;
}
// Check whether we need a new producerId. If so, we will enqueue an InitProducerId
// request which will be sent below
transactionManager.bumpIdempotentEpochAndResetIdIfNeeded();
if (maybeSendAndPollTransactionalRequest()) {
return;
}
} catch (AuthenticationException e) {
// This is already logged as error, but propagated here to perform any clean ups.
log.trace("Authentication exception while processing transactional request", e);
transactionManager.authenticationFailed(e);
}
}
long currentTimeMs = time.milliseconds();
long pollTimeout = sendProducerData(currentTimeMs);
client.poll(pollTimeout, currentTimeMs);
}
|
@Test
public void testNodeLatencyStats() throws Exception {
try (Metrics m = new Metrics()) {
// Create a new record accumulator with non-0 partitionAvailabilityTimeoutMs
// otherwise it wouldn't update the stats.
RecordAccumulator.PartitionerConfig config = new RecordAccumulator.PartitionerConfig(false, 42);
long totalSize = 1024 * 1024;
accumulator = new RecordAccumulator(logContext, batchSize, Compression.NONE, 0, 0L, 0L,
DELIVERY_TIMEOUT_MS, config, m, "producer-metrics", time, apiVersions, null,
new BufferPool(totalSize, batchSize, m, time, "producer-internal-metrics"));
SenderMetricsRegistry senderMetrics = new SenderMetricsRegistry(m);
Sender sender = new Sender(logContext, client, metadata, this.accumulator, false, MAX_REQUEST_SIZE, ACKS_ALL, 1,
senderMetrics, time, REQUEST_TIMEOUT, 1000L, null, new ApiVersions());
// Produce and send batch.
long time1 = time.milliseconds();
appendToAccumulator(tp0, 0L, "key", "value");
sender.runOnce();
assertEquals(1, client.inFlightRequestCount(), "We should have a single produce request in flight.");
// We were able to send the batch out, so both the ready and drain values should be the same.
RecordAccumulator.NodeLatencyStats stats = accumulator.getNodeLatencyStats(0);
assertEquals(time1, stats.drainTimeMs);
assertEquals(time1, stats.readyTimeMs);
// Make the node 1 not ready.
client.throttle(metadata.fetch().nodeById(0), 100);
// Time passes, but we don't have anything to send.
time.sleep(10);
sender.runOnce();
assertEquals(1, client.inFlightRequestCount(), "We should have a single produce request in flight.");
// Stats shouldn't change as we didn't have anything ready.
assertEquals(time1, stats.drainTimeMs);
assertEquals(time1, stats.readyTimeMs);
// Produce a new batch, but we won't be able to send it because node is not ready.
long time2 = time.milliseconds();
appendToAccumulator(tp0, 0L, "key", "value");
sender.runOnce();
assertEquals(1, client.inFlightRequestCount(), "We should have a single produce request in flight.");
// The ready time should move forward, but drain time shouldn't change.
assertEquals(time1, stats.drainTimeMs);
assertEquals(time2, stats.readyTimeMs);
// Time passes, we keep trying to send, but the node is not ready.
time.sleep(10);
time2 = time.milliseconds();
sender.runOnce();
assertEquals(1, client.inFlightRequestCount(), "We should have a single produce request in flight.");
// The ready time should move forward, but drain time shouldn't change.
assertEquals(time1, stats.drainTimeMs);
assertEquals(time2, stats.readyTimeMs);
// Finally, time passes beyond the throttle and the node is ready.
time.sleep(100);
time2 = time.milliseconds();
sender.runOnce();
assertEquals(2, client.inFlightRequestCount(), "We should have 2 produce requests in flight.");
// Both times should move forward
assertEquals(time2, stats.drainTimeMs);
assertEquals(time2, stats.readyTimeMs);
}
}
|
public static <T> RestResult<T> success() {
return RestResult.<T>builder().withCode(200).build();
}
|
@Test
void testSuccessWithData() {
RestResult<String> restResult = RestResultUtils.success("content");
assertRestResult(restResult, 200, null, "content", true);
}
|
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed = parser.parse(query);
final ParsedQuery.Builder builder = ParsedQuery.builder().query(query);
builder.tokensBuilder().addAll(parser.getTokens());
final TermCollectingQueryVisitor visitor = new TermCollectingQueryVisitor(ANALYZER, parser.getTokenLookup());
parsed.visit(visitor);
builder.termsBuilder().addAll(visitor.getParsedTerms());
return builder.build();
}
|
@Test
void testSuperSimpleQuery() throws ParseException {
final ParsedQuery fields = parser.parse("foo:bar");
assertThat(fields.allFieldNames()).contains("foo");
}
|
public static Builder builder() {
return new Builder();
}
|
@Test(expectedExceptions = NullPointerException.class)
public void testBuilderNoNullProducerThrowExceptions() {
PinotSourceDataGenerator generator = Mockito.mock(PinotSourceDataGenerator.class);
PinotRealtimeSource realtimeSource =
PinotRealtimeSource.builder().setTopic("mytopic").setGenerator(generator).build();
}
|
@Override
public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria)
{
Map<String, String> variables = new HashMap<>();
if (userRegex.isPresent()) {
Matcher userMatcher = userRegex.get().matcher(criteria.getUser());
if (!userMatcher.matches()) {
return Optional.empty();
}
addVariableValues(userRegex.get(), criteria.getUser(), variables);
}
if (sourceRegex.isPresent()) {
String source = criteria.getSource().orElse("");
if (!sourceRegex.get().matcher(source).matches()) {
return Optional.empty();
}
addVariableValues(sourceRegex.get(), source, variables);
}
if (principalRegex.isPresent()) {
String principal = criteria.getPrincipal().orElse("");
if (!principalRegex.get().matcher(principal).matches()) {
return Optional.empty();
}
addVariableValues(principalRegex.get(), principal, variables);
}
if (!clientTags.isEmpty() && !criteria.getTags().containsAll(clientTags)) {
return Optional.empty();
}
if (clientInfoRegex.isPresent() && !clientInfoRegex.get().matcher(criteria.getClientInfo().orElse(EMPTY_CRITERIA_STRING)).matches()) {
return Optional.empty();
}
if (selectorResourceEstimate.isPresent() && !selectorResourceEstimate.get().match(criteria.getResourceEstimates())) {
return Optional.empty();
}
if (queryType.isPresent()) {
String contextQueryType = criteria.getQueryType().orElse(EMPTY_CRITERIA_STRING);
if (!queryType.get().equalsIgnoreCase(contextQueryType)) {
return Optional.empty();
}
}
if (schema.isPresent() && criteria.getSchema().isPresent()) {
if (criteria.getSchema().get().compareToIgnoreCase(schema.get()) != 0) {
return Optional.empty();
}
}
variables.putIfAbsent(USER_VARIABLE, criteria.getUser());
// Special handling for source, which is an optional field that is part of the standard variables
variables.putIfAbsent(SOURCE_VARIABLE, criteria.getSource().orElse(""));
variables.putIfAbsent(SCHEMA_VARIABLE, criteria.getSchema().orElse(""));
VariableMap map = new VariableMap(variables);
ResourceGroupId id = group.expandTemplate(map);
OptionalInt firstDynamicSegment = group.getFirstDynamicSegment();
return Optional.of(new SelectionContext<>(id, map, firstDynamicSegment));
}
|
@Test
public void testClientTags()
{
ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "foo");
StaticSelector selector = new StaticSelector(
Optional.empty(),
Optional.empty(),
Optional.of(ImmutableList.of("tag1", "tag2")),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
new ResourceGroupIdTemplate("global.foo"));
assertEquals(selector.match(newSelectionCriteria("userA", null, ImmutableSet.of("tag1", "tag2"), EMPTY_RESOURCE_ESTIMATES)).map(SelectionContext::getResourceGroupId), Optional.of(resourceGroupId));
assertEquals(selector.match(newSelectionCriteria("userB", "source", ImmutableSet.of(), EMPTY_RESOURCE_ESTIMATES)), Optional.empty());
assertEquals(selector.match(newSelectionCriteria("A.user", "a source b", ImmutableSet.of("tag1"), EMPTY_RESOURCE_ESTIMATES)), Optional.empty());
assertEquals(selector.match(newSelectionCriteria("A.user", "a source b", ImmutableSet.of("tag1", "tag2", "tag3"), EMPTY_RESOURCE_ESTIMATES)).map(SelectionContext::getResourceGroupId), Optional.of(resourceGroupId));
}
|
@VisibleForTesting
ClientConfiguration createBkClientConfiguration(MetadataStoreExtended store, ServiceConfiguration conf) {
ClientConfiguration bkConf = new ClientConfiguration();
if (conf.getBookkeeperClientAuthenticationPlugin() != null
&& conf.getBookkeeperClientAuthenticationPlugin().trim().length() > 0) {
bkConf.setClientAuthProviderFactoryClass(conf.getBookkeeperClientAuthenticationPlugin());
bkConf.setProperty(conf.getBookkeeperClientAuthenticationParametersName(),
conf.getBookkeeperClientAuthenticationParameters());
}
if (conf.isBookkeeperTLSClientAuthentication()) {
bkConf.setTLSClientAuthentication(true);
bkConf.setTLSCertificatePath(conf.getBookkeeperTLSCertificateFilePath());
bkConf.setTLSKeyStore(conf.getBookkeeperTLSKeyFilePath());
bkConf.setTLSKeyStoreType(conf.getBookkeeperTLSKeyFileType());
bkConf.setTLSKeyStorePasswordPath(conf.getBookkeeperTLSKeyStorePasswordPath());
bkConf.setTLSProviderFactoryClass(conf.getBookkeeperTLSProviderFactoryClass());
bkConf.setTLSTrustStore(conf.getBookkeeperTLSTrustCertsFilePath());
bkConf.setTLSTrustStoreType(conf.getBookkeeperTLSTrustCertTypes());
bkConf.setTLSTrustStorePasswordPath(conf.getBookkeeperTLSTrustStorePasswordPath());
bkConf.setTLSCertFilesRefreshDurationSeconds(conf.getBookkeeperTlsCertFilesRefreshDurationSeconds());
}
bkConf.setBusyWaitEnabled(conf.isEnableBusyWait());
bkConf.setNumWorkerThreads(conf.getBookkeeperClientNumWorkerThreads());
bkConf.setThrottleValue(conf.getBookkeeperClientThrottleValue());
bkConf.setAddEntryTimeout((int) conf.getBookkeeperClientTimeoutInSeconds());
bkConf.setReadEntryTimeout((int) conf.getBookkeeperClientTimeoutInSeconds());
bkConf.setSpeculativeReadTimeout(conf.getBookkeeperClientSpeculativeReadTimeoutInMillis());
bkConf.setNumChannelsPerBookie(conf.getBookkeeperNumberOfChannelsPerBookie());
bkConf.setUseV2WireProtocol(conf.isBookkeeperUseV2WireProtocol());
bkConf.setEnableDigestTypeAutodetection(true);
bkConf.setStickyReadsEnabled(conf.isBookkeeperEnableStickyReads());
bkConf.setNettyMaxFrameSizeBytes(conf.getMaxMessageSize() + Commands.MESSAGE_SIZE_FRAME_PADDING);
bkConf.setDiskWeightBasedPlacementEnabled(conf.isBookkeeperDiskWeightBasedPlacementEnabled());
bkConf.setMetadataServiceUri(conf.getBookkeeperMetadataStoreUrl());
bkConf.setLimitStatsLogging(conf.isBookkeeperClientLimitStatsLogging());
if (!conf.isBookkeeperMetadataStoreSeparated()) {
// If we're connecting to the same metadata service, with same config, then
// let's share the MetadataStore instance
bkConf.setProperty(AbstractMetadataDriver.METADATA_STORE_INSTANCE, store);
}
if (conf.isBookkeeperClientHealthCheckEnabled()) {
bkConf.enableBookieHealthCheck();
bkConf.setBookieHealthCheckInterval((int) conf.getBookkeeperClientHealthCheckIntervalSeconds(),
TimeUnit.SECONDS);
bkConf.setBookieErrorThresholdPerInterval(conf.getBookkeeperClientHealthCheckErrorThresholdPerInterval());
bkConf.setBookieQuarantineTime((int) conf.getBookkeeperClientHealthCheckQuarantineTimeInSeconds(),
TimeUnit.SECONDS);
bkConf.setBookieQuarantineRatio(conf.getBookkeeperClientQuarantineRatio());
}
bkConf.setReorderReadSequenceEnabled(conf.isBookkeeperClientReorderReadSequenceEnabled());
bkConf.setExplictLacInterval(conf.getBookkeeperExplicitLacIntervalInMills());
bkConf.setGetBookieInfoIntervalSeconds(
conf.getBookkeeperClientGetBookieInfoIntervalSeconds(), TimeUnit.SECONDS);
bkConf.setGetBookieInfoRetryIntervalSeconds(
conf.getBookkeeperClientGetBookieInfoRetryIntervalSeconds(), TimeUnit.SECONDS);
bkConf.setNumIOThreads(conf.getBookkeeperClientNumIoThreads());
PropertiesUtils.filterAndMapProperties(conf.getProperties(), "bookkeeper_")
.forEach((key, value) -> {
log.info("Applying BookKeeper client configuration setting {}={}", key, value);
bkConf.setProperty(key, value);
});
return bkConf;
}
|
@Test
public void testSetMetadataServiceUriZookkeeperServers() {
BookKeeperClientFactoryImpl factory = new BookKeeperClientFactoryImpl();
ServiceConfiguration conf = new ServiceConfiguration();
conf.setMetadataStoreUrl("zk:localhost:2181");
try {
{
final String expectedUri = "metadata-store:zk:localhost:2181/ledgers";
assertEquals(factory.createBkClientConfiguration(mock(MetadataStoreExtended.class), conf)
.getMetadataServiceUri(), expectedUri);
}
} catch (ConfigurationException e) {
e.printStackTrace();
fail("Get metadata service uri should be successful", e);
}
}
|
@Override
public MapperResult findConfigInfoBaseLikeFetchRows(MapperContext context) {
final String tenant = (String) context.getWhereParameter(FieldConstant.TENANT);
final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID);
final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID);
List<Object> paramList = new ArrayList<>();
final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE ";
String where = " 1=1 AND tenant_id='" + NamespaceUtil.getNamespaceDefaultId() + "' ";
if (!StringUtils.isBlank(dataId)) {
where += " AND data_id LIKE ? ";
paramList.add(dataId);
}
if (!StringUtils.isBlank(group)) {
where += " AND group_id LIKE ? ";
paramList.add(group);
}
if (!StringUtils.isBlank(tenant)) {
where += " AND content LIKE ? ";
paramList.add(tenant);
}
return new MapperResult(
sqlFetchRows + where + " OFFSET " + context.getStartRow() + " ROWS FETCH NEXT " + context.getPageSize()
+ " ROWS ONLY", paramList);
}
|
@Test
void testFindConfigInfoBaseLikeFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeFetchRows(context);
assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' " + "OFFSET " + startRow
+ " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
}
|
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);
checkKRaftControllerCount(warnings);
checkKafkaMetadataVersion(warnings);
checkInterBrokerProtocolVersionInKRaft(warnings);
checkLogMessageFormatVersionInKRaft(warnings);
} else {
// Additional checks done for ZooKeeper-based clusters
checkKafkaLogMessageFormatVersion(warnings);
checkKafkaInterBrokerProtocolVersion(warnings);
checkKRaftMetadataStorageConfiguredForZooBasedCLuster(warnings);
}
return warnings;
}
|
@Test
public void testMetadataVersionMatchesKafkaVersion() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withVersion(KafkaVersionTestUtils.LATEST_KAFKA_VERSION)
.withMetadataVersion(KafkaVersionTestUtils.LATEST_METADATA_VERSION)
.endKafka()
.endSpec()
.build();
KafkaSpecChecker checker = generateChecker(kafka, List.of(CONTROLLERS, POOL_A), new KafkaVersionChange(VERSIONS.defaultVersion(), VERSIONS.defaultVersion(), null, null, KafkaVersionTestUtils.LATEST_METADATA_VERSION));
List<Condition> warnings = checker.run(true);
assertThat(warnings, hasSize(0));
}
|
public RegistryBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
|
@Test
void isDefault() {
RegistryBuilder builder = new RegistryBuilder();
builder.isDefault(true);
Assertions.assertTrue(builder.build().isDefault());
}
|
@Override
public void beforeRejectedExecution(Runnable r, ThreadPoolExecutor executor) {
rejectCount.incrementAndGet();
}
|
@Test
public void testBeforeRejectedExecution() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
1, 1, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
TaskRejectCountRecordPlugin plugin = new TaskRejectCountRecordPlugin();
executor.register(plugin);
executor.submit(() -> ThreadUtil.sleep(500L));
executor.submit(() -> ThreadUtil.sleep(500L));
executor.submit(() -> ThreadUtil.sleep(500L));
ThreadUtil.sleep(500L);
Assert.assertEquals((Long) 1L, plugin.getRejectCountNum());
}
|
public String create(final String secret, final String bucket, String region, final String key, final String method, final long expiry) {
if(StringUtils.isBlank(region)) {
// Only for AWS
switch(session.getSignatureVersion()) {
case AWS4HMACSHA256:
// Region is required for AWS4-HMAC-SHA256 signature
region = S3LocationFeature.DEFAULT_REGION.getIdentifier();
}
}
final Host bookmark = session.getHost();
return new RestS3Service(new AWSCredentials(StringUtils.strip(bookmark.getCredentials().getUsername()), StringUtils.strip(secret))) {
@Override
public String getEndpoint() {
if(S3Session.isAwsHostname(bookmark.getHostname())) {
return bookmark.getProtocol().getDefaultHostname();
}
return bookmark.getHostname();
}
@Override
protected void initializeProxy(final HttpClientBuilder httpClientBuilder) {
//
}
}.createSignedUrlUsingSignatureVersion(
session.getSignatureVersion().toString(),
region, method, bucket, key, null, null, expiry / 1000, false, true,
new HostPreferences(bookmark).getBoolean("s3.bucket.virtualhost.disable"));
}
|
@Test
public void testCustomHostname() {
final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
expiry.add(Calendar.MILLISECOND, (int) TimeUnit.DAYS.toMillis(7));
final Host host = new Host(new S3Protocol(), "h");
final S3Session session = new S3Session(host);
final String url = new S3PresignedUrlProvider(session).create(PROPERTIES.get("s3.secret"),
"test-us-east-1-cyberduck", null, "f", "GET", expiry.getTimeInMillis());
assertNotNull(url);
assertEquals("test-us-east-1-cyberduck.h", URI.create(url).getHost());
}
|
@Override
@SuppressWarnings("NullAway")
public @Nullable V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction,
@Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad,
boolean recordLoadFailure) {
requireNonNull(key);
requireNonNull(remappingFunction);
long[] now = { expirationTicker().read() };
Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
BiFunction<? super K, ? super V, ? extends V> statsAwareRemappingFunction =
statsAware(remappingFunction, recordLoad, recordLoadFailure);
return remap(key, keyRef, statsAwareRemappingFunction,
expiry, now, /* computeIfAbsent */ true);
}
|
@Test
public void policy_unsupported() {
Policy<Int, Int> policy = Mockito.mock(CALLS_REAL_METHODS);
Eviction<Int, Int> eviction = Mockito.mock(CALLS_REAL_METHODS);
VarExpiration<Int, Int> varExpiration = Mockito.mock(CALLS_REAL_METHODS);
FixedExpiration<Int, Int> fixedExpiration = Mockito.mock(CALLS_REAL_METHODS);
var type = UnsupportedOperationException.class;
assertThrows(type, () -> policy.getEntryIfPresentQuietly(Int.MAX_VALUE));
assertThrows(type, () -> eviction.coldestWeighted(1L));
assertThrows(type, () -> eviction.coldest(identity()));
assertThrows(type, () -> eviction.hottestWeighted(1L));
assertThrows(type, () -> eviction.hottest(identity()));
assertThrows(type, () -> fixedExpiration.oldest(identity()));
assertThrows(type, () -> fixedExpiration.youngest(identity()));
assertThrows(type, () -> varExpiration.oldest(identity()));
assertThrows(type, () -> varExpiration.youngest(identity()));
assertThrows(type, () -> varExpiration.compute(Int.MAX_VALUE, (k, v) -> v, Duration.ZERO));
}
|
public synchronized void cleanUp(Set<Long> activeTableIds)
{
// We have to remember that there might be some race conditions when there are two tables created at once.
// That can lead to a situation when MemoryPagesStore already knows about a newer second table on some worker
// but cleanUp is triggered by insert from older first table, which MemoryTableHandle was created before
// second table creation. Thus activeTableIds can have missing latest ids and we can only clean up tables
// that:
// - have smaller value then max(activeTableIds).
// - are missing from activeTableIds set
if (activeTableIds.isEmpty()) {
// if activeTableIds is empty, we can not determine latestTableId...
return;
}
long latestTableId = Collections.max(activeTableIds);
for (Iterator<Map.Entry<Long, TableData>> tableDataIterator = tables.entrySet().iterator(); tableDataIterator.hasNext(); ) {
Map.Entry<Long, TableData> tablePagesEntry = tableDataIterator.next();
Long tableId = tablePagesEntry.getKey();
if (tableId < latestTableId && !activeTableIds.contains(tableId)) {
for (Page removedPage : tablePagesEntry.getValue().getPages()) {
currentBytes -= removedPage.getRetainedSizeInBytes();
}
tableDataIterator.remove();
}
}
}
|
@Test
public void testCleanUp()
{
createTable(0L, 0L);
createTable(1L, 0L, 1L);
createTable(2L, 0L, 1L, 2L);
assertTrue(pagesStore.contains(0L));
assertTrue(pagesStore.contains(1L));
assertTrue(pagesStore.contains(2L));
insertToTable(1L, 0L, 1L);
assertTrue(pagesStore.contains(0L));
assertTrue(pagesStore.contains(1L));
assertTrue(pagesStore.contains(2L));
insertToTable(2L, 0L, 2L);
assertTrue(pagesStore.contains(0L));
assertFalse(pagesStore.contains(1L));
assertTrue(pagesStore.contains(2L));
}
|
public static boolean isOnList(@Nonnull final Set<String> list, @Nonnull final String ipAddress) {
Ipv4 remoteIpv4;
try {
remoteIpv4 = Ipv4.of(ipAddress);
} catch (IllegalArgumentException e) {
Log.trace("Address '{}' is not an IPv4 address.", ipAddress);
remoteIpv4 = null;
}
Ipv6 remoteIpv6;
try {
remoteIpv6 = Ipv6.of(ipAddress);
} catch (IllegalArgumentException e) {
Log.trace("Address '{}' is not an IPv6 address.", ipAddress);
remoteIpv6 = null;
}
if (remoteIpv4 == null && remoteIpv6 == null) {
Log.warn("Unable to parse '{}' as an IPv4 or IPv6 address!", ipAddress);
}
for (final String item : list) {
// Check if the remote address is an exact match on the list.
if (item.equals(ipAddress)) {
return true;
}
// Check if the remote address is a match for an address range on the list.
if (remoteIpv4 != null) {
Ipv4Range range;
try {
range = Ipv4Range.parse(item);
} catch (IllegalArgumentException e) {
Log.trace("List entry '{}' is not an IPv4 range.", item);
range = null;
}
if (range != null && range.contains(remoteIpv4)) {
return true;
}
}
if (remoteIpv6 != null) {
Ipv6Range range;
try {
range = Ipv6Range.parse(item);
} catch (IllegalArgumentException e) {
Log.trace("List entry '{}' is not an IPv6 range.", item);
range = null;
}
if (range != null && range.contains(remoteIpv6)) {
return true;
}
}
}
return false;
}
|
@Test
public void ipOnList() throws Exception {
// Setup test fixture.
final String input = "203.0.113.251";
final Set<String> list = new HashSet<>();
list.add(input);
// Execute system under test.
final boolean result = AuthCheckFilter.isOnList(list, input);
// Verify result.
assertTrue(result);
}
|
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean isCheckpointingEnabled) {
checkNotNull(jobRestartStrategyConfiguration);
checkNotNull(jobConfiguration);
checkNotNull(clusterConfiguration);
return getJobRestartStrategyFactory(jobRestartStrategyConfiguration)
.orElse(
getRestartStrategyFactoryFromConfig(jobConfiguration)
.orElse(
(getRestartStrategyFactoryFromConfig(clusterConfiguration)
.orElse(
getDefaultRestartStrategyFactory(
isCheckpointingEnabled)))));
}
|
@Test
void testNoRestartStrategySpecifiedInClusterConfig() {
final Configuration conf = new Configuration();
conf.set(RestartStrategyOptions.RESTART_STRATEGY, NO_RESTART_STRATEGY.getMainValue());
final RestartBackoffTimeStrategy.Factory factory =
RestartBackoffTimeStrategyFactoryLoader.createRestartBackoffTimeStrategyFactory(
DEFAULT_JOB_LEVEL_RESTART_CONFIGURATION, new Configuration(), conf, false);
assertThat(NoRestartBackoffTimeStrategy.NoRestartBackoffTimeStrategyFactory.INSTANCE)
.isEqualTo(factory);
}
|
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
final double pos = quantile * (values.length + 1);
final int index = (int) pos;
if (index < 1) {
return values[0];
}
if (index >= values.length) {
return values[values.length - 1];
}
final double lower = values[index - 1];
final double upper = values[index];
return lower + (pos - floor(pos)) * (upper - lower);
}
|
@Test
public void bigQuantilesAreTheLastValue() {
assertThat(snapshot.getValue(1.0))
.isEqualTo(5, offset(0.1));
}
|
public int getPort() {
return inetSocketAddress.getPort();
}
|
@Test
public void testGetPort() throws Exception {
final InetSocketAddress inetSocketAddress = new InetSocketAddress(Inet4Address.getLoopbackAddress(), 12345);
final ResolvableInetSocketAddress address = new ResolvableInetSocketAddress(inetSocketAddress);
assertThat(address.getPort()).isEqualTo(inetSocketAddress.getPort());
}
|
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}
// We know we are comparing to another SampleSaveConfiguration
SampleSaveConfiguration s = (SampleSaveConfiguration)obj;
boolean primitiveValues = s.time == time &&
s.latency == latency &&
s.connectTime == connectTime &&
s.timestamp == timestamp &&
s.success == success &&
s.label == label &&
s.code == code &&
s.message == message &&
s.threadName == threadName &&
s.dataType == dataType &&
s.encoding == encoding &&
s.assertions == assertions &&
s.subresults == subresults &&
s.responseData == responseData &&
s.samplerData == samplerData &&
s.xml == xml &&
s.fieldNames == fieldNames &&
s.responseHeaders == responseHeaders &&
s.requestHeaders == requestHeaders &&
s.assertionsResultsToSave == assertionsResultsToSave &&
s.saveAssertionResultsFailureMessage == saveAssertionResultsFailureMessage &&
s.printMilliseconds == printMilliseconds &&
s.responseDataOnError == responseDataOnError &&
s.url == url &&
s.bytes == bytes &&
s.sentBytes == sentBytes &&
s.fileName == fileName &&
s.hostname == hostname &&
s.sampleCount == sampleCount &&
s.idleTime == idleTime &&
s.threadCounts == threadCounts;
boolean stringValues = false;
if(primitiveValues) {
stringValues = Objects.equals(delimiter, s.delimiter);
}
boolean complexValues = false;
if(primitiveValues && stringValues) {
complexValues = Objects.equals(dateFormat, s.dateFormat);
}
return primitiveValues && stringValues && complexValues;
}
|
@Test
// Checks that all the saveXX() and setXXX(boolean) methods are in the list
public void testSaveConfigNames() throws Exception {
List<String> getMethodNames = new ArrayList<>();
List<String> setMethodNames = new ArrayList<>();
Method[] methods = SampleSaveConfiguration.class.getMethods();
for(Method method : methods) {
String name = method.getName();
if (name.startsWith(SampleSaveConfiguration.CONFIG_GETTER_PREFIX) && method.getParameterTypes().length == 0) {
name = name.substring(SampleSaveConfiguration.CONFIG_GETTER_PREFIX.length());
getMethodNames.add(name);
assertTrue(SampleSaveConfiguration.SAVE_CONFIG_NAMES.contains(name), "SAVE_CONFIG_NAMES should contain save" + name);
}
if (name.startsWith(SampleSaveConfiguration.CONFIG_SETTER_PREFIX)
&& method.getParameterTypes().length == 1
&& boolean.class.equals(method.getParameterTypes()[0])) {
name = name.substring(
SampleSaveConfiguration.CONFIG_SETTER_PREFIX.length());
setMethodNames.add(name);
assertTrue(SampleSaveConfiguration.SAVE_CONFIG_NAMES
.contains(name), "SAVE_CONFIG_NAMES should contain set" + name);
}
}
for (String name : SampleSaveConfiguration.SAVE_CONFIG_NAMES) {
assertTrue(getMethodNames.contains(name), "SAVE_CONFIG_NAMES should NOT contain save" + name);
assertTrue(setMethodNames.contains(name), "SAVE_CONFIG_NAMES should NOT contain set" + name);
}
}
|
public KeyManagerFactory createKeyManagerFactory()
throws NoSuchProviderException, NoSuchAlgorithmException {
return getProvider() != null ?
KeyManagerFactory.getInstance(getAlgorithm(), getProvider())
: KeyManagerFactory.getInstance(getAlgorithm());
}
|
@Test
public void testDefaults() throws Exception {
assertNotNull(factoryBean.createKeyManagerFactory());
}
|
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
}
|
@Test
public void answerInline() {
// inlineQuery sent by client after typing "@bot query" in message field
InlineQuery inlineQuery = BotUtils.parseUpdate(testInlineQuery).inlineQuery();
String inlineQueryId = inlineQuery.id();
assertFalse(inlineQueryId.isEmpty());
UserTest.checkUser(inlineQuery.from(), true);
assertEquals(Long.valueOf(12345), inlineQuery.from().id());
assertEquals("if", inlineQuery.query());
assertEquals("offset", inlineQuery.offset());
assertNull(inlineQuery.location());
InlineKeyboardMarkup keyboardMarkup = new InlineKeyboardMarkup(
new InlineKeyboardButton("inline game").callbackGame("pengrad test game description"),
new InlineKeyboardButton("inline ok").callbackData("callback ok"),
new InlineKeyboardButton("cancel").callbackData("callback cancel"),
new InlineKeyboardButton("url").url(someUrl),
new InlineKeyboardButton("switch inline").switchInlineQuery("query"),
new InlineKeyboardButton("switch inline current").switchInlineQueryCurrentChat("query"));
InlineQueryResult<?>[] results = new InlineQueryResult[]{
new InlineQueryResultArticle("1", "title",
new InputTextMessageContent("message")
.entities(new MessageEntity(MessageEntity.Type.bold, 0, 2))
.disableWebPagePreview(false).parseMode(ParseMode.HTML))
.url(someUrl).hideUrl(true).description("desc")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultArticle("2", "title",
new InputContactMessageContent("123123123", "na,e").lastName("lastName").vcard("qr vcard")),
new InlineQueryResultArticle("3", "title", new InputLocationMessageContent(50f, 50f)
.livePeriod(60).heading(100).horizontalAccuracy(10f).proximityAlertRadius(500)),
new InlineQueryResultArticle("4", "title",
new InputVenueMessageContent(50f, 50f, "title", "address")
.googlePlaceId("ggId").googlePlaceType("gType")
.foursquareId("sqrId").foursquareType("frType")),
new InlineQueryResultArticle("4b", "title",
new InputInvoiceMessageContent("title", "desc", "payload", "token", "USD",
new LabeledPrice[]{new LabeledPrice("delivery", 100)})
.maxTipAmount(0).suggestedTipAmount(new Integer[]{0}).providerData("provider_data")
.photoUrl(someUrl).photoSize(100).photoWidth(100).photoHeight(100)
.needName(false).needPhoneNumber(false).needEmail(false).needShippingAddress(false)
.sendPhoneNumberToProvider(false).sendEmailToProvider(false)
.isFlexible(false)),
new InlineQueryResultArticle("5", "title", "message"),
new InlineQueryResultAudio("6", someUrl, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).performer("perf").audioDuration(100),
new InlineQueryResultContact("7", "123123123", "name").lastName("lastName").vcard("tt vcard")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultDocument("8", someUrl, "title", "application/pdf").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultGame("9", "pengrad_test_game").replyMarkup(keyboardMarkup),
new InlineQueryResultGif("10", someUrl, someUrl).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title")
.thumbMimeType("image/gif")
.gifHeight(100).gifWidth(100).gifDuration(100),
new InlineQueryResultLocation("11", 50f, 50f, "title").livePeriod(60)
.heading(100).horizontalAccuracy(10f).proximityAlertRadius(500)
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultMpeg4Gif("12", someUrl, someUrl).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title")
.thumbMimeType("image/gif")
.mpeg4Height(100).mpeg4Width(100).mpeg4Duration(100),
new InlineQueryResultPhoto("13", someUrl, someUrl).photoWidth(100).photoHeight(100).title("title")
.description("desc").caption("cap <b>bold</b>").parseMode(ParseMode.HTML),
new InlineQueryResultPhoto("131", someUrl, someUrl).photoWidth(100).photoHeight(100).title("title")
.description("desc").caption("bold").captionEntities(new MessageEntity(MessageEntity.Type.bold, 0, 2)),
new InlineQueryResultVenue("14", 54f, 55f, "title", "address")
.foursquareId("frsqrId").foursquareType("frType")
.googlePlaceId("ggId").googlePlaceType("gType")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100)
.thumbnailUrl(someUrl).thumbnailHeight(100).thumbnailWidth(100),
new InlineQueryResultVideo("15", someUrl, VIDEO_MIME_TYPE, "text", someUrl, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML)
.videoWidth(100).videoHeight(100).videoDuration(100).description("desc"),
new InlineQueryResultVoice("16", someUrl, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).voiceDuration(100),
new InlineQueryResultCachedAudio("17", audioFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML),
new InlineQueryResultCachedDocument("18", stickerId, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc"),
new InlineQueryResultCachedGif("19", gifFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title"),
new InlineQueryResultCachedMpeg4Gif("21", gifFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title"),
new InlineQueryResultCachedPhoto("22", photoFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc").title("title"),
new InlineQueryResultCachedSticker("23", stickerId),
new InlineQueryResultCachedVideo("24", videoFileId, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc"),
new InlineQueryResultCachedVoice("25", voiceFileId, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML),
};
BaseResponse response = bot.execute(new AnswerInlineQuery(inlineQueryId, results)
.cacheTime(100)
.isPersonal(true)
.nextOffset("offset")
.switchPmText("go pm")
.switchPmParameter("my_pm_parameter")
);
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: query is too old and response timeout expired or query ID is invalid", response.description());
}
}
|
public static Optional<Credential> getImageCredential(
Consumer<LogEvent> logger,
String usernameProperty,
String passwordProperty,
AuthProperty auth,
RawConfiguration rawConfiguration) {
// System property takes priority over build configuration
String commandlineUsername = rawConfiguration.getProperty(usernameProperty).orElse("");
String commandlinePassword = rawConfiguration.getProperty(passwordProperty).orElse("");
if (!commandlineUsername.isEmpty() && !commandlinePassword.isEmpty()) {
return Optional.of(Credential.from(commandlineUsername, commandlinePassword));
}
// Warn if a system property is missing
String missingProperty =
"%s system property is set, but %s is not; attempting other authentication methods.";
if (!commandlinePassword.isEmpty()) {
logger.accept(
LogEvent.warn(String.format(missingProperty, passwordProperty, usernameProperty)));
}
if (!commandlineUsername.isEmpty()) {
logger.accept(
LogEvent.warn(String.format(missingProperty, usernameProperty, passwordProperty)));
}
// Check auth configuration next; warn if they aren't both set
if (!Strings.isNullOrEmpty(auth.getUsername()) && !Strings.isNullOrEmpty(auth.getPassword())) {
return Optional.of(Credential.from(auth.getUsername(), auth.getPassword()));
}
String missingConfig = "%s is missing from build configuration; ignoring auth section.";
if (!Strings.isNullOrEmpty(auth.getPassword())) {
logger.accept(LogEvent.warn(String.format(missingConfig, auth.getUsernameDescriptor())));
}
if (!Strings.isNullOrEmpty(auth.getUsername())) {
logger.accept(LogEvent.warn(String.format(missingConfig, auth.getPasswordDescriptor())));
}
return Optional.empty();
}
|
@Test
public void testGetImageAuth() {
when(mockAuth.getUsernameDescriptor()).thenReturn("user");
when(mockAuth.getPasswordDescriptor()).thenReturn("pass");
when(mockAuth.getUsername()).thenReturn("vwxyz");
when(mockAuth.getPassword()).thenReturn("98765");
// System properties set
when(mockConfiguration.getProperty("jib.test.auth.user")).thenReturn(Optional.of("abcde"));
when(mockConfiguration.getProperty("jib.test.auth.pass")).thenReturn(Optional.of("12345"));
Credential expected = Credential.from("abcde", "12345");
Optional<Credential> actual =
ConfigurationPropertyValidator.getImageCredential(
mockLogger, "jib.test.auth.user", "jib.test.auth.pass", mockAuth, mockConfiguration);
assertThat(actual).hasValue(expected);
// Auth set in configuration
when(mockConfiguration.getProperty("jib.test.auth.user")).thenReturn(Optional.empty());
when(mockConfiguration.getProperty("jib.test.auth.pass")).thenReturn(Optional.empty());
expected = Credential.from("vwxyz", "98765");
actual =
ConfigurationPropertyValidator.getImageCredential(
mockLogger, "jib.test.auth.user", "jib.test.auth.pass", mockAuth, mockConfiguration);
assertThat(actual).hasValue(expected);
verify(mockLogger, never()).accept(LogEvent.warn(any()));
// Auth completely missing
when(mockAuth.getUsername()).thenReturn(null);
when(mockAuth.getPassword()).thenReturn(null);
actual =
ConfigurationPropertyValidator.getImageCredential(
mockLogger, "jib.test.auth.user", "jib.test.auth.pass", mockAuth, mockConfiguration);
assertThat(actual).isEmpty();
// Password missing
when(mockAuth.getUsername()).thenReturn("vwxyz");
when(mockAuth.getPassword()).thenReturn(null);
actual =
ConfigurationPropertyValidator.getImageCredential(
mockLogger, "jib.test.auth.user", "jib.test.auth.pass", mockAuth, mockConfiguration);
assertThat(actual).isEmpty();
verify(mockLogger)
.accept(LogEvent.warn("pass is missing from build configuration; ignoring auth section."));
// Username missing
when(mockAuth.getUsername()).thenReturn(null);
when(mockAuth.getPassword()).thenReturn("98765");
actual =
ConfigurationPropertyValidator.getImageCredential(
mockLogger, "jib.test.auth.user", "jib.test.auth.pass", mockAuth, mockConfiguration);
assertThat(actual).isEmpty();
verify(mockLogger)
.accept(LogEvent.warn("user is missing from build configuration; ignoring auth section."));
}
|
@Override
public Object get(PropertyKey key) {
return get(key, ConfigurationValueOptions.defaults());
}
|
@Test
public void sitePropertiesLoadedNotInTest() throws Exception {
Properties props = new Properties();
props.setProperty(PropertyKey.LOGGER_TYPE.toString(), "TEST_LOGGER");
File propsFile = mFolder.newFile(Constants.SITE_PROPERTIES);
props.store(new FileOutputStream(propsFile), "ignored header");
// Avoid interference from system properties. Reset SITE_CONF_DIR to include the temp
// site-properties file
HashMap<String, String> sysProps = new HashMap<>();
sysProps.put(PropertyKey.LOGGER_TYPE.toString(), null);
sysProps.put(PropertyKey.SITE_CONF_DIR.toString(), mFolder.getRoot().getAbsolutePath());
sysProps.put(PropertyKey.TEST_MODE.toString(), "false");
try (Closeable p = new SystemPropertyRule(sysProps).toResource()) {
resetConf();
assertEquals("TEST_LOGGER", mConfiguration.get(PropertyKey.LOGGER_TYPE));
}
}
|
public void updatePartitionStatistics(String dbName, String tableName, String partitionName,
Function<HivePartitionStats, HivePartitionStats> update) {
try {
metastore.updatePartitionStatistics(dbName, tableName, partitionName, update);
} finally {
if (!(metastore instanceof CachingHiveMetastore)) {
refreshPartition(Lists.newArrayList(HivePartitionName.of(dbName, tableName, partitionName)));
}
}
}
|
@Test
public void testUpdatePartitionStats() {
CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore(
metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false);
HivePartitionStats partitionStats = HivePartitionStats.empty();
cachingHiveMetastore.updatePartitionStatistics("db", "table", "p1=1", ignore -> partitionStats);
}
|
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer)
{
return read(buffer, consumer, 0);
}
|
@Test
void shouldNotExceedEndOfBufferWhenReadinErrorMessage()
{
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[64]);
buffer.setMemory(0, buffer.capacity(), (byte)'?');
final long lastTimestamp = 347923749327L;
final long firstTimestamp = -8530458948593L;
final int count = 999;
buffer.putInt(LENGTH_OFFSET, Integer.MAX_VALUE);
buffer.putLong(LAST_OBSERVATION_TIMESTAMP_OFFSET, lastTimestamp);
buffer.putLong(FIRST_OBSERVATION_TIMESTAMP_OFFSET, firstTimestamp);
buffer.putInt(OBSERVATION_COUNT_OFFSET, count);
buffer.putStringWithoutLengthAscii(ENCODED_ERROR_OFFSET, "test");
final String expectedErrorString =
buffer.getStringWithoutLengthAscii(ENCODED_ERROR_OFFSET, buffer.capacity() - ENCODED_ERROR_OFFSET);
final ErrorConsumer errorConsumer = mock(ErrorConsumer.class);
assertEquals(1, ErrorLogReader.read(buffer, errorConsumer, 0));
verify(errorConsumer).accept(count, firstTimestamp, lastTimestamp, expectedErrorString);
}
|
@Override
public void rollback() {
}
|
@Test
void assertRollback() {
assertDoesNotThrow(() -> connection.rollback());
}
|
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) {
in.markReaderIndex();
MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get());
checkPayload(payload);
MySQLBinlogEventHeader binlogEventHeader = new MySQLBinlogEventHeader(payload, binlogContext.getChecksumLength());
if (!checkEventIntegrity(in, binlogEventHeader)) {
return;
}
Optional<MySQLBaseBinlogEvent> binlogEvent = decodeEvent(binlogEventHeader, payload);
if (!binlogEvent.isPresent()) {
skipChecksum(binlogEventHeader.getEventType(), in);
return;
}
if (binlogEvent.get() instanceof PlaceholderBinlogEvent) {
out.add(binlogEvent.get());
skipChecksum(binlogEventHeader.getEventType(), in);
return;
}
if (decodeWithTX) {
processEventWithTX(binlogEvent.get(), out);
} else {
processEventIgnoreTX(binlogEvent.get(), out);
}
skipChecksum(binlogEventHeader.getEventType(), in);
}
}
|
@Test
void assertDecodeDeleteRowEvent() {
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
// delete from t_order where order_id = 1;
byteBuf.writeBytes(StringUtil.decodeHexDump("002a80a862200100000038000000c569000000007400000000000100020004ff0801000000000000000100000007535543434553531c9580c5"));
byteBuf.writeBytes(StringUtil.decodeHexDump("006acb656410010000001f000000fa29000000001643000000000000b13f8340"));
binlogContext.getTableMap().put(116L, tableMapEventPacket);
when(tableMapEventPacket.getColumnDefs()).thenReturn(columnDefs);
List<Object> decodedEvents = new LinkedList<>();
binlogEventPacketDecoder.decode(channelHandlerContext, byteBuf, decodedEvents);
assertThat(decodedEvents.size(), is(1));
LinkedList<?> actualEventList = (LinkedList<?>) decodedEvents.get(0);
assertThat(actualEventList.get(0), instanceOf(MySQLDeleteRowsBinlogEvent.class));
assertThat(actualEventList.get(1), instanceOf(MySQLXidBinlogEvent.class));
MySQLDeleteRowsBinlogEvent actual = (MySQLDeleteRowsBinlogEvent) actualEventList.get(0);
assertThat(actual.getBeforeRows().get(0), is(new Serializable[]{1L, 1, new MySQLBinaryString("SUCCESS".getBytes()), null}));
}
|
public static String resolveUrl(String genericUrl, MessageParameters parameters) {
Preconditions.checkState(
parameters.isResolved(), "Not all mandatory message parameters were resolved.");
StringBuilder path = new StringBuilder(genericUrl);
StringBuilder queryParameters = new StringBuilder();
for (MessageParameter<?> pathParameter : parameters.getPathParameters()) {
if (pathParameter.isResolved()) {
int start = path.indexOf(':' + pathParameter.getKey());
final String pathValue =
Preconditions.checkNotNull(pathParameter.getValueAsString());
// only replace path parameters if they are present
if (start != -1) {
path.replace(start, start + pathParameter.getKey().length() + 1, pathValue);
}
}
}
boolean isFirstQueryParameter = true;
for (MessageQueryParameter<?> queryParameter : parameters.getQueryParameters()) {
if (queryParameter.isResolved()) {
if (isFirstQueryParameter) {
queryParameters.append('?');
isFirstQueryParameter = false;
} else {
queryParameters.append('&');
}
queryParameters.append(queryParameter.getKey());
queryParameters.append('=');
queryParameters.append(queryParameter.getValueAsString());
}
}
path.append(queryParameters);
return path.toString();
}
|
@Test
void testResolveUrl() {
String genericUrl = "/jobs/:jobid/state";
TestMessageParameters parameters = new TestMessageParameters();
JobID pathJobID = new JobID();
JobID queryJobID = new JobID();
parameters.pathParameter.resolve(pathJobID);
parameters.queryParameter.resolve(Collections.singletonList(queryJobID));
String resolvedUrl = MessageParameters.resolveUrl(genericUrl, parameters);
assertThat("/jobs/" + pathJobID + "/state?jobid=" + queryJobID).isEqualTo(resolvedUrl);
}
|
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
}
|
@Test
public void testTime() {
RedisClusterNode master = getFirstMaster();
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
}
|
static Callback create(@Nullable Callback delegate, Span span, CurrentTraceContext current) {
if (delegate == null) return new FinishSpan(span);
return new DelegateAndFinishSpan(delegate, span, current);
}
|
@Test void on_completion_should_forward_then_finish_span() {
Span span = tracing.tracer().nextSpan().start();
Callback delegate = mock(Callback.class);
Callback tracingCallback = TracingCallback.create(delegate, span, currentTraceContext);
RecordMetadata md = createRecordMetadata();
tracingCallback.onCompletion(md, null);
verify(delegate).onCompletion(md, null);
assertThat(spans.get(0).finishTimestamp()).isNotZero();
}
|
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewKey(), "New name must not be null!");
byte[] keyBuf = toByteArray(command.getKey());
byte[] newKeyBuf = toByteArray(command.getNewKey());
if (executorService.getConnectionManager().calcSlot(keyBuf) == executorService.getConnectionManager().calcSlot(newKeyBuf)) {
return super.rename(commands);
}
return read(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.DUMP, keyBuf)
.filter(Objects::nonNull)
.zipWith(
Mono.defer(() -> pTtl(command.getKey())
.filter(Objects::nonNull)
.map(ttl -> Math.max(0, ttl))
.switchIfEmpty(Mono.just(0L))
)
)
.flatMap(valueAndTtl -> {
return write(newKeyBuf, StringCodec.INSTANCE, RedisCommands.RESTORE, newKeyBuf, valueAndTtl.getT2(), valueAndTtl.getT1());
})
.thenReturn(new BooleanResponse<>(command, true))
.doOnSuccess((ignored) -> del(command.getKey()));
});
}
|
@Test
public void testRename() {
testInClusterReactive(connection -> {
connection.stringCommands().set(originalKey, value).block();
if (hasTtl) {
connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block();
}
Integer originalSlot = getSlotForKey(originalKey, (RedissonReactiveRedisClusterConnection) connection);
newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot), connection);
Boolean response = connection.keyCommands().rename(originalKey, newKey).block();
assertThat(response).isTrue();
final ByteBuffer newKeyValue = connection.stringCommands().get(newKey).block();
assertThat(newKeyValue).isEqualTo(value);
if (hasTtl) {
assertThat(connection.keyCommands().ttl(newKey).block()).isGreaterThan(0);
} else {
assertThat(connection.keyCommands().ttl(newKey).block()).isEqualTo(-1);
}
});
}
|
public static boolean isJCacheAvailable(ClassLoader classLoader) {
return isJCacheAvailable((className) -> ClassLoaderUtil.isClassAvailable(classLoader, className));
}
|
@Test
public void testIsJCacheAvailable_withWrongJCacheVersion_withLogger() {
JCacheDetector.ClassAvailabilityChecker classAvailabilityChecker = className -> className.equals("javax.cache.Caching");
assertFalse(isJCacheAvailable(logger, classAvailabilityChecker));
}
|
public void expectLogMessageWithThrowableMatcher(
int level, String tag, String message, Matcher<Throwable> throwableMatcher) {
expectLogMessageWithThrowable(level, tag, MsgEq.of(message), throwableMatcher);
}
|
@Test
public void testExpectLogMessageWithThrowableMatcher() {
final IllegalArgumentException exception = new IllegalArgumentException("lorem ipsum");
Log.e("Mytag", "What's up", exception);
rule.expectLogMessageWithThrowableMatcher(
Log.ERROR, "Mytag", "What's up", instanceOf(IllegalArgumentException.class));
}
|
public static Optional<SingleRouteEngine> newInstance(final Collection<QualifiedTable> singleTables, final SQLStatement sqlStatement) {
if (!singleTables.isEmpty()) {
return Optional.of(new SingleStandardRouteEngine(singleTables, sqlStatement));
}
// TODO move this logic to common route logic
if (isSchemaDDLStatement(sqlStatement)) {
return Optional.of(new SingleDatabaseBroadcastRouteEngine());
}
return Optional.empty();
}
|
@Test
void assertNewInstanceWithEmptySingleTableNameAndAlterSchemaStatement() {
assertTrue(SingleRouteEngineFactory.newInstance(Collections.emptyList(), mock(AlterSchemaStatement.class)).isPresent());
}
|
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execute(plan.getPlan(), restoreInProgress);
return result;
} catch (final KsqlStatementException e) {
throw e;
} catch (final KsqlException e) {
// add the statement text to the KsqlException
throw new KsqlStatementException(
e.getMessage(),
e.getMessage(),
plan.getPlan().getStatementText(),
e.getCause()
);
}
}
|
@Test(expected = ParseFailedException.class)
public void shouldFailWhenSyntaxIsInvalid() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"blah;",
ksqlConfig,
Collections.emptyMap()
);
}
|
@Override
public KeyValueIterator<Windowed<K>, V> backwardFetchAll(final Instant timeFrom,
final Instant timeTo) throws IllegalArgumentException {
final NextIteratorFunction<Windowed<K>, V, ReadOnlyWindowStore<K, V>> nextIteratorFunction =
store -> store.backwardFetchAll(timeFrom, timeTo);
return new DelegatingPeekingKeyValueIterator<>(
storeName,
new CompositeKeyValueIterator<>(
provider.stores(storeName, windowStoreType).iterator(),
nextIteratorFunction));
}
|
@Test
public void shouldBackwardFetchAllAcrossStores() {
final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new
ReadOnlyWindowStoreStub<>(WINDOW_SIZE);
stubProviderTwo.addStore(storeName, secondUnderlying);
underlyingWindowStore.put("a", "a", 0L);
secondUnderlying.put("b", "b", 10L);
final List<KeyValue<Windowed<String>, String>> results =
StreamsTestUtils.toList(windowStore.backwardFetchAll(ofEpochMilli(0), ofEpochMilli(10)));
assertThat(results, equalTo(Arrays.asList(
KeyValue.pair(new Windowed<>("a", new TimeWindow(0, WINDOW_SIZE)), "a"),
KeyValue.pair(new Windowed<>("b", new TimeWindow(10, 10 + WINDOW_SIZE)), "b"))));
}
|
@Override
public SparseArray apply(String text) {
TreeMap<Integer, Integer> bag = new TreeMap<>();
for (String word : tokenizer.apply(text)) {
int h = MurmurHash3.hash32(word, 0);
// abs(-2 * * 31)is undefined behavior
int index = h == -2147483648 ? (2147483647 - (numFeatures - 1)) % numFeatures : Math.abs(h) % numFeatures;
// improve inner product preservation in the hashed space
int value = alternateSign && h < 0 ? -1 : 1;
bag.merge(index, value, Integer::sum);
}
SparseArray features = new SparseArray();
bag.forEach(features::append);
return features;
}
|
@Test
public void testFeature() throws IOException {
System.out.println("feature");
String[][] text = smile.util.Paths.getTestDataLines("text/movie.txt")
.map(String::trim)
.filter(line -> !line.isEmpty())
.map(line -> line.split("\\s+", 2))
.toArray(String[][]::new);
HashEncoder hashing = new HashEncoder(tokenizer, 1000);
SparseArray[] x = new SparseArray[text.length];
for (int i = 0; i < text.length; i++) {
x[i] = hashing.apply(text[i][1]);
}
System.out.println(x[0]);
assertEquals(289, x[0].size());
System.out.println(x[1999]);
assertEquals(345, x[1999].size());
}
|
public static Optional<String> urlEncode(String raw) {
try {
return Optional.of(URLEncoder.encode(raw, UTF_8.toString()));
} catch (UnsupportedEncodingException e) {
return Optional.empty();
}
}
|
@Test
public void urlEncode_whenNotEncoded_returnsEncoded() {
assertThat(urlEncode(" ")).hasValue("+");
assertThat(urlEncode("()[]{}<>")).hasValue("%28%29%5B%5D%7B%7D%3C%3E");
assertThat(urlEncode("?!@#$%^&=+,;:'\"`/\\|~"))
.hasValue("%3F%21%40%23%24%25%5E%26%3D%2B%2C%3B%3A%27%22%60%2F%5C%7C%7E");
}
|
@Description("converts an angle in degrees to radians")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double radians(@SqlType(StandardTypes.DOUBLE) double degrees)
{
return Math.toRadians(degrees);
}
|
@Test
public void testRadians()
{
for (double doubleValue : DOUBLE_VALUES) {
assertFunction(String.format("radians(%s)", doubleValue), DOUBLE, Math.toRadians(doubleValue));
assertFunction(String.format("radians(REAL '%s')", (float) doubleValue), DOUBLE, Math.toRadians((float) doubleValue));
}
assertFunction("radians(NULL)", DOUBLE, null);
}
|
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates)
{
List<String> perColumnExpressions = new ArrayList<>();
int expressionLength = 0;
for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) {
String columnName = partitionPredicate.getKey().getName();
if (JSQL_PARSER_RESERVED_KEYWORDS.contains(columnName.toUpperCase(ENGLISH))) {
// The column name is a reserved keyword in the grammar of the SQL parser used internally by Glue API
continue;
}
Domain domain = partitionPredicate.getValue();
if (domain != null && !domain.isAll()) {
Optional<String> columnExpression = buildGlueExpressionForSingleDomain(columnName, domain);
if (columnExpression.isPresent()) {
int newExpressionLength = expressionLength + columnExpression.get().length();
if (expressionLength > 0) {
newExpressionLength += CONJUNCT_SEPARATOR.length();
}
if (newExpressionLength > GLUE_EXPRESSION_CHAR_LIMIT) {
continue;
}
perColumnExpressions.add((columnExpression.get()));
expressionLength = newExpressionLength;
}
}
}
return Joiner.on(CONJUNCT_SEPARATOR).join(perColumnExpressions);
}
|
@Test
public void testBuildGlueExpressionMaxLengthNone()
{
Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR)
.addStringValues("col1", Strings.repeat("x", GLUE_EXPRESSION_CHAR_LIMIT))
.build();
String expression = buildGlueExpression(predicates);
assertEquals(expression, "");
}
|
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
try {
return getRoutingForInner(aci, clientAddress, instanceLimit);
} catch(Exception e) {
logger.error("Failed to perform routing", e);
return new TurnServerOptions(this.configTurnRouter.getHostname(), null, this.configTurnRouter.randomUrls());
}
}
|
@Test
public void testPrioritizesTargetedUrls() throws UnknownHostException {
List<String> targetedUrls = List.of(
"targeted1.example.com",
"targeted.example.com"
);
when(configTurnRouter.targetedUrls(any()))
.thenReturn(targetedUrls);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
null,
targetedUrls
));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.