focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object firstExpected,
@Nullable Object secondExpected,
@Nullable Object @Nullable ... restOfExpected) {
return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected));
}
|
@Test
public void iterableContainsAtLeastWithDuplicatesFailure() {
expectFailureWhenTestingThat(asList(1, 2, 3)).containsAtLeast(1, 2, 2, 2, 3, 4);
assertFailureValue("missing (3)", "2 [2 copies], 4");
}
|
public static boolean isTimeoutException(Throwable exception) {
if (exception == null) return false;
if (exception instanceof ExecutionException) {
exception = exception.getCause();
if (exception == null) return false;
}
return exception instanceof TimeoutException;
}
|
@Test
public void testWrappedRuntimeExceptionIsNotTimeoutException() {
assertFalse(isTimeoutException(new ExecutionException(new RuntimeException())));
}
|
@VisibleForTesting
void validateRoleDuplicate(String name, String code, Long id) {
// 0. 超级管理员,不允许创建
if (RoleCodeEnum.isSuperAdmin(code)) {
throw exception(ROLE_ADMIN_CODE_ERROR, code);
}
// 1. 该 name 名字被其它角色所使用
RoleDO role = roleMapper.selectByName(name);
if (role != null && !role.getId().equals(id)) {
throw exception(ROLE_NAME_DUPLICATE, name);
}
// 2. 是否存在相同编码的角色
if (!StringUtils.hasText(code)) {
return;
}
// 该 code 编码被其它角色所使用
role = roleMapper.selectByCode(code);
if (role != null && !role.getId().equals(id)) {
throw exception(ROLE_CODE_DUPLICATE, code);
}
}
|
@Test
public void testValidateRoleDuplicate_success() {
// 调用,不会抛异常
roleService.validateRoleDuplicate(randomString(), randomString(), null);
}
|
@Override
public int run(String[] args) throws Exception {
YarnConfiguration yarnConf =
getConf() == null ? new YarnConfiguration() : new YarnConfiguration(
getConf());
boolean isHAEnabled =
yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED,
YarnConfiguration.DEFAULT_RM_HA_ENABLED);
if (args.length < 1) {
printUsage("", isHAEnabled);
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = args[i++];
exitCode = 0;
if ("-help".equals(cmd)) {
if (i < args.length) {
printUsage(args[i], isHAEnabled);
} else {
printHelp("", isHAEnabled);
}
return exitCode;
}
if (USAGE.containsKey(cmd)) {
if (isHAEnabled) {
return super.run(args);
}
System.out.println("Cannot run " + cmd
+ " when ResourceManager HA is not enabled");
return -1;
}
//
// verify that we have enough command line parameters
//
String subClusterId = StringUtils.EMPTY;
if ("-refreshAdminAcls".equals(cmd) || "-refreshQueues".equals(cmd) ||
"-refreshNodesResources".equals(cmd) ||
"-refreshServiceAcl".equals(cmd) ||
"-refreshUserToGroupsMappings".equals(cmd) ||
"-refreshSuperUserGroupsConfiguration".equals(cmd) ||
"-refreshClusterMaxPriority".equals(cmd)) {
subClusterId = parseSubClusterId(args, isHAEnabled);
// If we enable Federation mode, the number of args may be either one or three.
// Example: -refreshQueues or -refreshQueues -subClusterId SC-1
if (isYarnFederationEnabled(getConf()) && args.length != 1 && args.length != 3) {
printUsage(cmd, isHAEnabled);
return exitCode;
} else if (!isYarnFederationEnabled(getConf()) && args.length != 1) {
// If Federation mode is not enabled, then the number of args can only be one.
// Example: -refreshQueues
printUsage(cmd, isHAEnabled);
return exitCode;
}
}
// If it is federation mode, we will print federation mode information
if (isYarnFederationEnabled(getConf())) {
System.out.println("Using YARN Federation mode.");
}
try {
if ("-refreshQueues".equals(cmd)) {
exitCode = refreshQueues(subClusterId);
} else if ("-refreshNodes".equals(cmd)) {
exitCode = handleRefreshNodes(args, cmd, isHAEnabled);
} else if ("-refreshNodesResources".equals(cmd)) {
exitCode = refreshNodesResources(subClusterId);
} else if ("-refreshUserToGroupsMappings".equals(cmd)) {
exitCode = refreshUserToGroupsMappings(subClusterId);
} else if ("-refreshSuperUserGroupsConfiguration".equals(cmd)) {
exitCode = refreshSuperUserGroupsConfiguration(subClusterId);
} else if ("-refreshAdminAcls".equals(cmd)) {
exitCode = refreshAdminAcls(subClusterId);
} else if ("-refreshServiceAcl".equals(cmd)) {
exitCode = refreshServiceAcls(subClusterId);
} else if ("-refreshClusterMaxPriority".equals(cmd)) {
exitCode = refreshClusterMaxPriority(subClusterId);
} else if ("-getGroups".equals(cmd)) {
String[] usernames = Arrays.copyOfRange(args, i, args.length);
exitCode = getGroups(usernames);
} else if ("-updateNodeResource".equals(cmd)) {
exitCode = handleUpdateNodeResource(args, cmd, isHAEnabled, subClusterId);
} else if ("-addToClusterNodeLabels".equals(cmd)) {
exitCode = handleAddToClusterNodeLabels(args, cmd, isHAEnabled);
} else if ("-removeFromClusterNodeLabels".equals(cmd)) {
exitCode = handleRemoveFromClusterNodeLabels(args, cmd, isHAEnabled);
} else if ("-replaceLabelsOnNode".equals(cmd)) {
exitCode = handleReplaceLabelsOnNodes(args, cmd, isHAEnabled);
} else {
exitCode = -1;
System.err.println(cmd.substring(1) + ": Unknown command");
printUsage("", isHAEnabled);
}
} catch (IllegalArgumentException arge) {
exitCode = -1;
System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage());
printUsage(cmd, isHAEnabled);
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error message, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
System.err.println(cmd.substring(1) + ": "
+ content[0]);
} catch (Exception ex) {
System.err.println(cmd.substring(1) + ": "
+ ex.getLocalizedMessage());
}
} catch (Exception e) {
exitCode = -1;
System.err.println(cmd.substring(1) + ": "
+ e.getLocalizedMessage());
}
if (null != localNodeLabelsManager) {
localNodeLabelsManager.stop();
}
return exitCode;
}
|
@Test
public void testRemoveFromClusterNodeLabels() throws Exception {
// Successfully remove labels
dummyNodeLabelsManager.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y"));
String[] args =
{ "-removeFromClusterNodeLabels", "x,,y",
"-directlyAccessNodeLabelStore" };
assertEquals(0, rmAdminCLI.run(args));
assertTrue(dummyNodeLabelsManager.getClusterNodeLabelNames().isEmpty());
// no labels, should fail
args = new String[] { "-removeFromClusterNodeLabels" };
assertTrue(0 != rmAdminCLI.run(args));
// no labels, should fail
args =
new String[] { "-removeFromClusterNodeLabels",
"-directlyAccessNodeLabelStore" };
assertTrue(0 != rmAdminCLI.run(args));
// no labels, should fail at client validation
args = new String[] { "-removeFromClusterNodeLabels", " " };
assertTrue(0 != rmAdminCLI.run(args));
// no labels, should fail at client validation
args = new String[] { "-removeFromClusterNodeLabels", ", " };
assertTrue(0 != rmAdminCLI.run(args));
}
|
@Override
public Long createDiyPage(DiyPageCreateReqVO createReqVO) {
// 校验名称唯一
validateNameUnique(null, createReqVO.getTemplateId(), createReqVO.getName());
// 插入
DiyPageDO diyPage = DiyPageConvert.INSTANCE.convert(createReqVO);
diyPage.setProperty("{}");
diyPageMapper.insert(diyPage);
return diyPage.getId();
}
|
@Test
public void testCreateDiyPage_success() {
// 准备参数
DiyPageCreateReqVO reqVO = randomPojo(DiyPageCreateReqVO.class);
// 调用
Long diyPageId = diyPageService.createDiyPage(reqVO);
// 断言
assertNotNull(diyPageId);
// 校验记录的属性是否正确
DiyPageDO diyPage = diyPageMapper.selectById(diyPageId);
assertPojoEquals(reqVO, diyPage);
}
|
@Override
public boolean isInstanceOf(String jobInstanceName, boolean ignoreCase, String jobConfigName) {
String jobConfigNameWithMarker = translatedJobName(jobInstanceName, jobConfigName);
return ignoreCase ? jobInstanceName.equalsIgnoreCase(jobConfigNameWithMarker) : jobInstanceName.equals(jobConfigNameWithMarker);
}
|
@Test
public void shouldTellIsInstanceOfCorrectly() throws Exception {
assertThat(jobConfig.isInstanceOf("job-runInstance-1", false), is(true));
assertThat(jobConfig.isInstanceOf("Job-runInstance-1", true), is(true));
assertThat(jobConfig.isInstanceOf("Job-runInstance-1", false), is(false));
}
|
public static Iterator<String> splitOnCharacterAsIterator(String value, char needle, int count) {
// skip leading and trailing needles
int end = value.length() - 1;
boolean skipStart = value.charAt(0) == needle;
boolean skipEnd = value.charAt(end) == needle;
if (skipStart && skipEnd) {
value = value.substring(1, end);
count = count - 2;
} else if (skipStart) {
value = value.substring(1);
count = count - 1;
} else if (skipEnd) {
value = value.substring(0, end);
count = count - 1;
}
final int size = count;
final String text = value;
return new Iterator<>() {
int i;
int pos;
@Override
public boolean hasNext() {
return i < size;
}
@Override
public String next() {
if (i == size) {
throw new NoSuchElementException();
}
String answer;
int end = text.indexOf(needle, pos);
if (end != -1) {
answer = text.substring(pos, end);
pos = end + 1;
} else {
answer = text.substring(pos);
// no more data
i = size;
}
return answer;
}
};
}
|
@Test
public void testSplitOnCharacterAsIterator() {
Iterator<String> it = splitOnCharacterAsIterator("foo", ',', 1);
assertEquals("foo", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator("foo,bar", ',', 2);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator("foo,bar,", ',', 3);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator(",foo,bar", ',', 3);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator(",foo,bar,", ',', 4);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
sb.append(",");
}
String value = sb.toString();
int count = StringHelper.countChar(value, ',') + 1;
it = splitOnCharacterAsIterator(value, ',', count);
for (int i = 0; i < 100; i++) {
assertEquals(Integer.toString(i), it.next());
}
assertFalse(it.hasNext());
}
|
@Override
public double[] dijkstra(int s) {
int n = graph.length;
double[] wt = new double[n];
Arrays.fill(wt, Double.POSITIVE_INFINITY);
PriorityQueue queue = new PriorityQueue(wt);
for (int v = 0; v < n; v++) {
queue.insert(v);
}
wt[s] = 0.0;
queue.lower(s);
while (!queue.isEmpty()) {
int v = queue.poll();
if (!Double.isInfinite(wt[v])) {
for (Edge edge : graph[v]) {
int w = edge.v2;
if (!digraph && w == v) {
w = edge.v1;
}
double p = wt[v] + edge.weight;
if (p < wt[w]) {
wt[w] = p;
queue.lower(w);
}
}
}
}
return wt;
}
|
@Test
public void testDijkstra() {
System.out.println("Dijkstra");
double[][] wt = {
{0.00, 0.41, 0.82, 0.86, 0.50, 0.29},
{1.13, 0.00, 0.51, 0.68, 0.32, 1.06},
{0.95, 1.17, 0.00, 0.50, 1.09, 0.88},
{0.45, 0.67, 0.91, 0.00, 0.59, 0.38},
{0.81, 1.03, 0.32, 0.36, 0.00, 0.74},
{1.02, 0.29, 0.53, 0.57, 0.21, 0.00},
};
Graph graph = new AdjacencyList(6, true);
graph.addEdge(0, 1, 0.41);
graph.addEdge(1, 2, 0.51);
graph.addEdge(2, 3, 0.50);
graph.addEdge(4, 3, 0.36);
graph.addEdge(3, 5, 0.38);
graph.addEdge(3, 0, 0.45);
graph.addEdge(0, 5, 0.29);
graph.addEdge(5, 4, 0.21);
graph.addEdge(1, 4, 0.32);
graph.addEdge(4, 2, 0.32);
graph.addEdge(5, 1, 0.29);
double[][] wt2 = graph.dijkstra();
assertTrue(MathEx.equals(wt, wt2));
}
|
@Override
public ObjectNode encode(MappingInstruction instruction, CodecContext context) {
checkNotNull(instruction, "Mapping instruction cannot be null");
return new EncodeMappingInstructionCodecHelper(instruction, context).encode();
}
|
@Test
public void multicastPriorityInstructionTest() {
final MulticastMappingInstruction.PriorityMappingInstruction instruction =
(MulticastMappingInstruction.PriorityMappingInstruction)
MappingInstructions.multicastPriority(MULTICAST_PRIORITY);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
|
public String convertUnicodeCharacterRepresentation(String input) {
final char[] chars = input.toCharArray();
int nonAsciiCharCount = countNonAsciiCharacters(chars);
if(! (input.contains("\\u") || input.contains("\\U")) && nonAsciiCharCount == 0)
return input;
int replacedNonAsciiCharacterCount = 0;
final char[] result = nonAsciiCharCount == 0 ? chars : new char[chars.length + 5 * nonAsciiCharCount];
for (int offset = 0; offset < chars.length; offset++) {
int resultOffset = offset + 5 * replacedNonAsciiCharacterCount;
final char c = chars[offset];
if (c == '\\' && (chars[offset+1] == 'u' || chars[offset+1] == 'U')) {
putFormattedUnicodeRepresentation(chars, offset, result, resultOffset);
offset+=5;
} else if(c <= 127) {
if(resultOffset >= result.length ) {
throw new AssertionError(input + "//" + new String(result));
}
result[resultOffset] = c;
} else {
putEncodedNonAsciiCharacter(c, result, resultOffset);
replacedNonAsciiCharacterCount++;
}
}
return new String(result);
}
|
@Test
public void convertsLatin1toUnicode() {
final FormatTranslation formatTranslation = new FormatTranslation();
assertThat(formatTranslation.convertUnicodeCharacterRepresentation("ä"),
CoreMatchers.equalTo("\\u00E4"));
assertThat(formatTranslation.convertUnicodeCharacterRepresentation("ä1"),
CoreMatchers.equalTo("\\u00E41"));
}
|
@Override
public UserDetails loadUserByUsername(String userId)
throws UsernameNotFoundException {
User user = null;
try {
user = this.identityService.createUserQuery()
.userId(userId)
.singleResult();
} catch (FlowableException ex) {
// don't care
}
if (null == user) {
throw new UsernameNotFoundException(
String.format("user (%s) could not be found", userId));
}
return createFlowableUser(user);
}
|
@Test
public void testLoadingByNullUserShouldIgnoreFlowableException() {
assertThatThrownBy(() -> userDetailsService.loadUserByUsername(null))
.isInstanceOf(UsernameNotFoundException.class)
.hasMessage("user (null) could not be found");
}
|
@Override
public String toString() {
return toString(null);
}
|
@Test
public void toStringTest() {
Condition conditionNull = new Condition("user", null);
assertEquals("user IS NULL", conditionNull.toString());
Condition conditionNotNull = new Condition("user", "!= null");
assertEquals("user IS NOT NULL", conditionNotNull.toString());
Condition condition2 = new Condition("user", "= zhangsan");
assertEquals("user = ?", condition2.toString());
Condition conditionLike = new Condition("user", "like %aaa");
assertEquals("user LIKE ?", conditionLike.toString());
Condition conditionIn = new Condition("user", "in 1,2,3");
assertEquals("user IN (?,?,?)", conditionIn.toString());
Condition conditionBetween = new Condition("user", "between 12 and 13");
assertEquals("user BETWEEN ? AND ?", conditionBetween.toString());
}
|
public int maxRetries() {
return maxRetries;
}
|
@Test(expectedExceptions = CacheConfigurationException.class,
expectedExceptionsMessageRegExp = "ISPN(\\d)*: Invalid max_retries \\(value=-1\\). " +
"Value should be greater or equal than zero.")
public void testNegativeRetriesPerServer() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.maxRetries(-1);
builder.build();
}
|
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SnapshotDto that = (SnapshotDto) o;
return Objects.equals(uuid, that.uuid) &&
Objects.equals(rootComponentUuid, that.rootComponentUuid) &&
Objects.equals(createdAt, that.createdAt) &&
Objects.equals(analysisDate, that.analysisDate) &&
Objects.equals(status, that.status) &&
Objects.equals(last, that.last) &&
Objects.equals(projectVersion, that.projectVersion) &&
Objects.equals(buildString, that.buildString) &&
Objects.equals(periodMode, that.periodMode) &&
Objects.equals(periodParam, that.periodParam) &&
Objects.equals(periodDate, that.periodDate);
}
|
@Test
void equals_whenComparedToDifferentInstanceWithSameValues_shouldReturnTrue() {
SnapshotDto snapshotDto1 = create();
SnapshotDto snapshotDto2 = create();
assertThat(snapshotDto1.equals(snapshotDto2)).isTrue();
assertThat(snapshotDto2.equals(snapshotDto1)).isTrue();
}
|
private Function<KsqlConfig, Kudf> getUdfFactory(
final Method method,
final UdfDescription udfDescriptionAnnotation,
final String functionName,
final FunctionInvoker invoker,
final String sensorName
) {
return ksqlConfig -> {
final Object actualUdf = FunctionLoaderUtils.instantiateFunctionInstance(
method.getDeclaringClass(), udfDescriptionAnnotation.name());
if (actualUdf instanceof Configurable) {
ExtensionSecurityManager.INSTANCE.pushInUdf();
try {
((Configurable) actualUdf)
.configure(ksqlConfig.getKsqlFunctionsConfigProps(functionName));
} finally {
ExtensionSecurityManager.INSTANCE.popOutUdf();
}
}
final PluggableUdf theUdf = new PluggableUdf(invoker, actualUdf);
return metrics.<Kudf>map(m -> new UdfMetricProducer(
m.getSensor(sensorName),
theUdf,
Time.SYSTEM
)).orElse(theUdf);
};
}
|
@Test
public void shouldUseConfigForExtDir() {
final InternalFunctionRegistry functionRegistry = new InternalFunctionRegistry();
// The tostring function is in the udf-example.jar that is found in src/test/resources
final ImmutableMap<Object, Object> configMap
= ImmutableMap.builder().put(KsqlConfig.KSQL_EXT_DIR, "src/test/resources")
.put(KsqlConfig.KSQL_UDF_SECURITY_MANAGER_ENABLED, false)
.build();
final KsqlConfig config
= new KsqlConfig(configMap);
UserFunctionLoader.newInstance(
config,
functionRegistry,
"",
new Metrics()
).load();
// will throw if it doesn't exist
functionRegistry.getUdfFactory(FunctionName.of("tostring"));
}
|
@Override
public byte[] echo(byte[] message) {
return read(null, ByteArrayCodec.INSTANCE, ECHO, message);
}
|
@Test
public void testEcho() {
assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes());
}
|
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
}
|
@Test
public void test31RefSiblings() {
SwaggerConfiguration config = new SwaggerConfiguration().openAPI31(true).openAPI(new OpenAPI());
Reader reader = new Reader(config);
OpenAPI openAPI = reader.read(TagResource.class);
String yaml = "openapi: 3.1.0\n" +
"paths:\n" +
" /tag/tag:\n" +
" get:\n" +
" operationId: getTag\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/SimpleTag'\n" +
"components:\n" +
" schemas:\n" +
" Foo:\n" +
" deprecated: true\n" +
" description: Foo\n" +
" properties:\n" +
" foo:\n" +
" type: string\n" +
" const: foo\n" +
" bar:\n" +
" type: integer\n" +
" format: int32\n" +
" exclusiveMaximum: 2\n" +
" foobar:\n" +
" type:\n" +
" - integer\n" +
" - string\n" +
" - object\n" +
" format: int32\n" +
" SimpleTag:\n" +
" properties:\n" +
" annotated:\n" +
" $ref: '#/components/schemas/SimpleCategory'\n" +
" description: child description\n" +
" properties:\n" +
" foo:\n" +
" $ref: '#/components/schemas/Foo'\n" +
" SimpleCategory: {}\n";
SerializationMatchers.assertEqualsToYaml31(openAPI, yaml);
}
|
public void onError(Throwable cause) {
if (cause instanceof StatusRuntimeException
&& ((StatusRuntimeException) cause).getStatus().getCode() == Status.Code.CANCELLED) {
// Cancellation is already handled.
return;
}
mSerializingExecutor.execute(() -> {
LogUtils.warnWithException(LOG, "Exception thrown while handling write request {}",
mContext == null ? "unknown" : mContext.getRequest(), cause);
abort(new Error(AlluxioStatusException.fromThrowable(cause), false));
});
}
|
@Test
public void ErrorReceived() throws Exception {
mWriteHandler.onError(new IOException("test exception"));
}
|
@Override
public void run() {
if (!redoService.isConnected()) {
LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task");
return;
}
try {
redoForInstances();
redoForSubscribes();
} catch (Exception e) {
LogUtils.NAMING_LOGGER.warn("Redo task run with unexpected exception: ", e);
}
}
|
@Test
void testRunRedoRemoveInstanceRedoData() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(false, true, false);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(redoService).removeInstanceForRedo(SERVICE, GROUP);
}
|
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final String adjacentSplit = splitChar + splitChar;
final int adjacentSplitLength = adjacentSplit.length();
if (truncate) {
while ((spot = splittee.indexOf(adjacentSplit)) != -1) {
splittee = splittee.substring(0, spot + splitLength)
+ splittee.substring(spot + adjacentSplitLength, splittee.length());
}
if (splittee.startsWith(splitChar)) {
splittee = splittee.substring(splitLength);
}
if (splittee.endsWith(splitChar)) { // Remove trailing splitter
splittee = splittee.substring(0, splittee.length() - splitLength);
}
}
List<String> returns = new ArrayList<>();
final int length = splittee.length(); // This is the new length
int start = 0;
spot = 0;
while (start < length && (spot = splittee.indexOf(splitChar, start)) > -1) {
if (spot > 0) {
returns.add(splittee.substring(start, spot));
} else {
returns.add(EMPTY_ELEMENT);
}
start = spot + splitLength;
}
if (start < length) {
returns.add(splittee.substring(start));
} else if (spot == length - splitLength) {// Found splitChar at end of line
returns.add(EMPTY_ELEMENT);
}
return returns.toArray(new String[returns.size()]);
}
|
@Test
public void testSplitNullStringString() {
Assertions.assertThrows(
NullPointerException.class,
() -> JOrphanUtils.split(null, ",", "?"));
}
|
public BootstrapMetadata read() throws Exception {
Path path = Paths.get(directoryPath);
if (!Files.isDirectory(path)) {
if (Files.exists(path)) {
throw new RuntimeException("Path " + directoryPath + " exists, but is not " +
"a directory.");
} else {
throw new RuntimeException("No such directory as " + directoryPath);
}
}
Path binaryBootstrapPath = Paths.get(directoryPath, BINARY_BOOTSTRAP_FILENAME);
if (!Files.exists(binaryBootstrapPath)) {
return readFromConfiguration();
} else {
return readFromBinaryFile(binaryBootstrapPath.toString());
}
}
|
@Test
public void testMissingDirectory() {
assertEquals("No such directory as ./non/existent/directory",
assertThrows(RuntimeException.class, () ->
new BootstrapDirectory("./non/existent/directory", Optional.empty()).read()).getMessage());
}
|
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchingFunctionException(arguments);
}
// if none were found (candidate isn't present) try again with implicit casting
candidate = findMatchingCandidate(arguments, true);
if (candidate.isPresent()) {
return candidate.get();
}
throw createNoMatchingFunctionException(arguments);
}
|
@Test
public void shouldChooseSpecificOverVarArgsAtEnd() {
// Given:
givenFunctions(
function(EXPECTED, -1, INT, INT, STRING),
function(OTHER, 2, INT, INT, STRING_VARARGS)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(
SqlArgument.of(SqlTypes.INTEGER), SqlArgument.of(SqlTypes.INTEGER),
SqlArgument.of(SqlTypes.STRING)
));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
}
|
public static String removeTags(String text, List<Tag> tagsToRemove) {
if (StringUtils.isBlank(text)) {
return text;
}
var textCopy = new AtomicReference<>(text);
tagsToRemove.forEach(tagToRemove -> textCopy.set(removeTag(textCopy.get(), tagToRemove)));
return textCopy.get();
}
|
@Test
public void removeTags_mixedCarriageReturns () {
var text = "some text\n" + TAG1.getText() + " other following text ending with " + TAG2.getText();
var expected = "some text\n other following text ending with " + TAG2.getText();
var result = TagsHelper.removeTags(text, singletonList(TAG1));
assertEquals(expected, result);
}
|
boolean isWriteShareGroupStateSuccessful(List<PersisterStateBatch> stateBatches) {
WriteShareGroupStateResult response;
try {
response = persister.writeState(new WriteShareGroupStateParameters.Builder()
.setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<PartitionStateBatchData>()
.setGroupId(this.groupId)
.setTopicsData(Collections.singletonList(new TopicData<>(topicIdPartition.topicId(),
Collections.singletonList(PartitionFactory.newPartitionStateBatchData(
topicIdPartition.partition(), stateEpoch, startOffset, 0, stateBatches))))
).build()).build()).get();
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to write the share group state for share partition: {}-{}", groupId, topicIdPartition, e);
throw new IllegalStateException(String.format("Failed to write the share group state for share partition %s-%s",
groupId, topicIdPartition), e);
}
if (response == null || response.topicsData() == null || response.topicsData().size() != 1) {
log.error("Failed to write the share group state for share partition: {}-{}. Invalid state found: {}",
groupId, topicIdPartition, response);
throw new IllegalStateException(String.format("Failed to write the share group state for share partition %s-%s",
groupId, topicIdPartition));
}
TopicData<PartitionErrorData> state = response.topicsData().get(0);
if (state.topicId() != topicIdPartition.topicId() || state.partitions().size() != 1
|| state.partitions().get(0).partition() != topicIdPartition.partition()) {
log.error("Failed to write the share group state for share partition: {}-{}. Invalid topic partition response: {}",
groupId, topicIdPartition, response);
throw new IllegalStateException(String.format("Failed to write the share group state for share partition %s-%s",
groupId, topicIdPartition));
}
PartitionErrorData partitionData = state.partitions().get(0);
if (partitionData.errorCode() != Errors.NONE.code()) {
Exception exception = Errors.forCode(partitionData.errorCode()).exception(partitionData.errorMessage());
log.error("Failed to write the share group state for share partition: {}-{} due to exception",
groupId, topicIdPartition, exception);
return false;
}
return true;
}
|
@Test
public void testWriteShareGroupStateWithNullTopicsData() {
Persister persister = Mockito.mock(Persister.class);
mockPersisterReadStateMethod(persister);
SharePartition sharePartition = SharePartitionBuilder.builder().withPersister(persister).build();
WriteShareGroupStateResult writeShareGroupStateResult = Mockito.mock(WriteShareGroupStateResult.class);
Mockito.when(writeShareGroupStateResult.topicsData()).thenReturn(null);
Mockito.when(persister.writeState(Mockito.any())).thenReturn(CompletableFuture.completedFuture(writeShareGroupStateResult));
assertThrows(IllegalStateException.class, () -> sharePartition.isWriteShareGroupStateSuccessful(Mockito.anyList()));
}
|
public static <T> boolean contains(T[] array, T item) {
for (T o : array) {
if (o == null) {
if (item == null) {
return true;
}
} else {
if (o.equals(item)) {
return true;
}
}
}
return false;
}
|
@Test
public void contains() {
Object[] array = new Object[1];
Object object = new Object();
array[0] = object;
assertTrue(ArrayUtils.contains(array, object));
}
|
protected int computeCount() {
int c = 0;
for (byte b : map) {
c += Integer.bitCount(b & 0xFF);
}
return length - c;
}
|
@Test
public void testComputeCount() {
LinearCounting lc = new LinearCounting(4);
lc.offer(0);
lc.offer(1);
lc.offer(2);
lc.offer(3);
lc.offer(16);
lc.offer(17);
lc.offer(18);
lc.offer(19);
assertEquals(27, lc.computeCount());
}
|
public static Builder builder() {
return new Builder();
}
|
@Test
// Test cases that cannot be built with our builder, but that are accepted when parsed
public void testCanDeserializeWithoutDefaultValues() throws JsonProcessingException {
ConfigResponse noOverrides = ConfigResponse.builder().withDefaults(DEFAULTS).build();
String jsonMissingOverrides = "{\"defaults\":{\"warehouse\":\"s3://bucket/warehouse\"}}";
assertEquals(deserialize(jsonMissingOverrides), noOverrides);
String jsonNullOverrides =
"{\"defaults\":{\"warehouse\":\"s3://bucket/warehouse\"},\"overrides\":null}";
assertEquals(deserialize(jsonNullOverrides), noOverrides);
ConfigResponse noDefaults = ConfigResponse.builder().withOverrides(OVERRIDES).build();
String jsonMissingDefaults = "{\"overrides\":{\"clients\":\"5\"}}";
assertEquals(deserialize(jsonMissingDefaults), noDefaults);
String jsonNullDefaults = "{\"defaults\":null,\"overrides\":{\"clients\":\"5\"}}";
assertEquals(deserialize(jsonNullDefaults), noDefaults);
ConfigResponse noValues = ConfigResponse.builder().build();
String jsonEmptyObject = "{}";
assertEquals(deserialize(jsonEmptyObject), noValues);
String jsonNullForAllFields = "{\"defaults\":null,\"overrides\":null}";
assertEquals(deserialize(jsonNullForAllFields), noValues);
}
|
@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 assertDecodeFormatDescriptionEvent() {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(StringUtil.decodeHexDump("00513aa8620f01000000790000000000000000000400382e302e323700000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ "000000000013000d0008000000000400040000006100041a08000000080808020000000a0a0a2a2a001234000a280140081396"));
List<Object> decodedEvents = new LinkedList<>();
binlogEventPacketDecoder.decode(channelHandlerContext, byteBuf, decodedEvents);
assertTrue(decodedEvents.isEmpty());
assertThat(binlogContext.getChecksumLength(), is(4));
}
|
static void checkValidTableId(String idToCheck) {
if (idToCheck.length() < MIN_TABLE_ID_LENGTH) {
throw new IllegalArgumentException("Table ID " + idToCheck + " cannot be empty.");
}
if (idToCheck.length() > MAX_TABLE_ID_LENGTH) {
throw new IllegalArgumentException(
"Table ID "
+ idToCheck
+ " cannot be longer than "
+ MAX_TABLE_ID_LENGTH
+ " characters.");
}
if (ILLEGAL_TABLE_CHARS.matcher(idToCheck).find()) {
throw new IllegalArgumentException(
"Table ID "
+ idToCheck
+ " is not a valid ID. Only letters, numbers, hyphens, underscores and exclamation points are allowed.");
}
}
|
@Test
public void testCheckValidTableIdWhenIdIsValid() {
checkValidTableId("table-id_valid.Test1");
}
|
public int size() {
return data.size();
}
|
@Test
public void testLibSVMLoading() throws IOException {
MockOutputFactory factory = new MockOutputFactory();
URL dataFile = LibSVMDataSourceTest.class.getResource("/org/tribuo/datasource/test-1.libsvm");
LibSVMDataSource<MockOutput> source = new LibSVMDataSource<>(dataFile,factory);
MutableDataset<MockOutput> dataset = new MutableDataset<>(source);
FeatureMap fmap = dataset.getFeatureMap();
assertEquals(7,fmap.size());
OutputInfo<MockOutput> info = dataset.getOutputInfo();
assertEquals(2,info.size());
}
|
public void optimize(PinotQuery pinotQuery, @Nullable Schema schema) {
optimize(pinotQuery, null, schema);
}
|
@Test
public void testMergeEqInFilter() {
String query =
"SELECT * FROM testTable WHERE int IN (1, 1) AND (long IN (2, 3) OR long IN (3, 4) OR long = 2) AND (float = "
+ "3.5 OR double IN (1.1, 1.2) OR float = 4.5 OR float > 5.5 OR double = 1.3)";
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
OPTIMIZER.optimize(pinotQuery, SCHEMA);
Function filterFunction = pinotQuery.getFilterExpression().getFunctionCall();
assertEquals(filterFunction.getOperator(), FilterKind.AND.name());
List<Expression> children = filterFunction.getOperands();
assertEquals(children.size(), 3);
assertEquals(children.get(0), getEqFilterExpression("int", 1));
checkInFilterFunction(children.get(1).getFunctionCall(), "long", Arrays.asList(2, 3, 4));
Function thirdChildFunction = children.get(2).getFunctionCall();
assertEquals(thirdChildFunction.getOperator(), FilterKind.OR.name());
List<Expression> thirdChildChildren = thirdChildFunction.getOperands();
assertEquals(thirdChildChildren.size(), 3);
assertEquals(thirdChildChildren.get(0).getFunctionCall().getOperator(), FilterKind.GREATER_THAN.name());
// Order of second and third child is not deterministic
Function secondGrandChildFunction = thirdChildChildren.get(1).getFunctionCall();
assertEquals(secondGrandChildFunction.getOperator(), FilterKind.IN.name());
Function thirdGrandChildFunction = thirdChildChildren.get(2).getFunctionCall();
assertEquals(thirdGrandChildFunction.getOperator(), FilterKind.IN.name());
if (secondGrandChildFunction.getOperands().get(0).getIdentifier().getName().equals("float")) {
checkInFilterFunction(secondGrandChildFunction, "float", Arrays.asList(3.5, 4.5));
checkInFilterFunction(thirdGrandChildFunction, "double", Arrays.asList(1.1, 1.2, 1.3));
} else {
checkInFilterFunction(secondGrandChildFunction, "double", Arrays.asList(1.1, 1.2, 1.3));
checkInFilterFunction(thirdGrandChildFunction, "float", Arrays.asList(3.5, 4.5));
}
}
|
@GetMapping(params = "search=accurate")
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ)
public Object getRoles(@RequestParam int pageNo, @RequestParam int pageSize,
@RequestParam(name = "username", defaultValue = "") String username,
@RequestParam(name = "role", defaultValue = "") String role) {
return roleService.getRolesFromDatabase(username, role, pageNo, pageSize);
}
|
@Test
void testGetRoles() {
Page<RoleInfo> rolesTest = new Page<RoleInfo>();
when(roleService.getRolesFromDatabase(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest);
Object roles = roleController.getRoles(1, 10, "nacos", "test");
assertEquals(rolesTest, roles);
}
|
@Override
public Collection<RedisServer> slaves(NamedNode master) {
List<Map<String, String>> slaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, master.getName());
return toRedisServersList(slaves);
}
|
@Test
public void testSlaves() {
Collection<RedisServer> masters = connection.masters();
Collection<RedisServer> slaves = connection.slaves(masters.iterator().next());
assertThat(slaves).hasSize(2);
}
|
public String getFingerprint() {
return fingerprint;
}
|
@Test
public void testWithEmptyStreamList() throws Exception {
final StreamListFingerprint fingerprint = new StreamListFingerprint(Lists.<Stream>newArrayList());
assertEquals(expectedEmptyFingerprint, fingerprint.getFingerprint());
}
|
public int compareTo(int left, int right)
{
int leftSegment = segment(left);
int leftSegmentOffset = offset(left);
int rightSegment = segment(right);
int rightSegmentOffset = offset(right);
Slice leftRawSlice = getSegmentRawSlice(leftSegment);
int leftOffset = offsets[leftSegment][leftSegmentOffset];
int leftLen = offsets[leftSegment][leftSegmentOffset + 1] - leftOffset;
Slice rightRawSlice = getSegmentRawSlice(rightSegment);
int rightOffset = offsets[rightSegment][rightSegmentOffset];
int rightLen = offsets[rightSegment][rightSegmentOffset + 1] - rightOffset;
return leftRawSlice.compareTo(leftOffset, leftLen, rightRawSlice, rightOffset, rightLen);
}
|
@Test
public void testCompareTo()
{
SegmentedSliceBlockBuilder blockBuilder = new SegmentedSliceBlockBuilder(10, 10);
for (int i = 0; i < SLICE.length(); i++) {
blockBuilder.writeBytes(SLICE, i, 1);
blockBuilder.closeEntry();
}
for (int i = 0; i < SLICE.length() - 1; i++) {
assertLessThan(blockBuilder.compareTo(i, i + 1), 0);
assertEquals(blockBuilder.compareTo(i, i), 0);
assertGreaterThan(blockBuilder.compareTo(i + 1, i), 0);
}
}
|
public static boolean canDrop(
FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) {
Objects.requireNonNull(pred, "pred cannnot be null");
Objects.requireNonNull(columns, "columns cannnot be null");
return pred.accept(new DictionaryFilter(columns, dictionaries));
}
|
@Test
public void testLtEqLong() throws Exception {
LongColumn i64 = longColumn("int64_field");
long lowest = Long.MAX_VALUE;
for (long value : longValues) {
lowest = Math.min(lowest, value);
}
assertTrue("Should drop: <= lowest - 1", canDrop(ltEq(i64, lowest - 1), ccmd, dictionaries));
assertFalse("Should not drop: <= lowest", canDrop(ltEq(i64, lowest), ccmd, dictionaries));
assertFalse(
"Should not drop: contains matching values", canDrop(ltEq(i64, Long.MAX_VALUE), ccmd, dictionaries));
}
|
@Operation(summary = "start new activation session with username/password", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.REQUEST_ACCOUNT_AND_APP, SwaggerConfig.ACTIVATE_SMS, SwaggerConfig.ACTIVATE_LETTER, SwaggerConfig.ACTIVATE_RDA, SwaggerConfig.ACTIVATE_WITH_APP}, operationId = "session_data",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")})
@PostMapping(value = "session", produces = "application/json")
@ResponseBody
public AppResponse sessionData(@Valid @RequestBody SessionDataRequest request) throws FlowNotDefinedException, NoSuchAlgorithmException, FlowStateNotDefinedException, IOException, SharedServiceClientException {
return service.processAction(ActivationFlowFactory.TYPE, Action.CONFIRM_SESSION, request);
}
|
@Test
void validateIfCorrectProcessesAreCalledSessionData() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
SessionDataRequest request = new SessionDataRequest();
activationController.sessionData(request);
verify(flowService, times(1)).processAction(anyString(), any(Action.class), any(SessionDataRequest.class));
}
|
@Override
public List<byte[]> mGet(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key : keys) {
read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key);
}
return null;
}
CommandBatchService es = new CommandBatchService(executorService);
for (byte[] key: keys) {
es.readAsync(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key);
}
BatchResult<byte[]> r = (BatchResult<byte[]>) es.execute();
return r.getResponses();
}
|
@Test
public void testMGet() {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(("test" + i).getBytes(), ("test" + i*100).getBytes());
}
connection.mSet(map);
List<byte[]> r = connection.mGet(map.keySet().toArray(new byte[0][]));
assertThat(r).containsExactly(map.values().toArray(new byte[0][]));
}
|
@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException {
return new Checksum(HashAlgorithm.sha512, this.digest("SHA-512",
this.normalize(in, status), status));
}
|
@Test
public void testNormalize() throws Exception {
assertEquals("dc6d6c30f2be9c976d6318c9a534d85e9a1c3f3608321a04b4678ef408124d45d7164f3e562e68c6c0b6c077340a785824017032fddfa924f4cf400e6cbb6adc",
new SHA512ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()),
new TransferStatus()).hash);
assertEquals("dc6d6c30f2be9c976d6318c9a534d85e9a1c3f3608321a04b4678ef408124d45d7164f3e562e68c6c0b6c077340a785824017032fddfa924f4cf400e6cbb6adc",
new SHA512ChecksumCompute().compute(IOUtils.toInputStream("_input", Charset.defaultCharset()),
new TransferStatus().withOffset(1)).hash);
assertEquals("dc6d6c30f2be9c976d6318c9a534d85e9a1c3f3608321a04b4678ef408124d45d7164f3e562e68c6c0b6c077340a785824017032fddfa924f4cf400e6cbb6adc",
new SHA512ChecksumCompute().compute(IOUtils.toInputStream("_input_", Charset.defaultCharset()),
new TransferStatus().withOffset(1).withLength(5)).hash);
}
|
@Override
public void start() {
if (taskExecutorThread == null) {
taskExecutorThread = new TaskExecutorThread(name);
taskExecutorThread.start();
shutdownGate = new CountDownLatch(1);
}
}
|
@Test
public void shouldPunctuateStreamTime() {
when(taskExecutionMetadata.canProcessTask(eq(task), anyLong())).thenReturn(false);
when(taskExecutionMetadata.canPunctuateTask(task)).thenReturn(true);
when(task.maybePunctuateStreamTime()).thenReturn(true);
taskExecutor.start();
verify(task, timeout(VERIFICATION_TIMEOUT).atLeast(2)).maybePunctuateStreamTime();
}
|
public void writeLong(long value) throws IOException {
writeInt((int)value);
writeInt((int)(value >> 32));
}
|
@Test
public void testWriteLong() throws IOException {
writer.writeLong(0x1122334455667788L);
writer.writeLong(-0x1122334455667788L);
expectData(0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11,
0x78, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE);
}
|
@Override
public String version() {
return AppInfoParser.getVersion();
}
|
@Test
public void testVersionRetrievedFromAppInfoParser() {
assertEquals(AppInfoParser.getVersion(), converter.version());
}
|
public static boolean delete(File path)
{
if (!path.exists()) {
return false;
}
boolean ret = true;
if (path.isDirectory()) {
File[] files = path.listFiles();
if (files != null) {
for (File f : files) {
ret = ret && delete(f);
}
}
}
return ret && path.delete();
}
|
@Test
public void testDeleteFile() throws IOException
{
File dir = new File(TemporaryFolderFinder.resolve("testfile"));
dir.mkdirs();
File path = File.createTempFile("test", "suffix", dir);
assertThat(path.exists(), is(true));
Utils.delete(dir);
assertThat(path.exists(), is(false));
}
|
@Override
public KTable<K, V> toTable() {
return toTable(NamedInternal.empty(), Materialized.with(keySerde, valueSerde));
}
|
@Test
public void shouldNotAllowNullNamedOnToTable() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.toTable((Named) null));
assertThat(exception.getMessage(), equalTo("named can't be null"));
}
|
public T getDataByIndex(int index) {
return scesimData.get(index);
}
|
@Test
public void getDataByIndex() {
final Scenario dataByIndex = model.getDataByIndex(3);
assertThat(dataByIndex).isNotNull();
assertThat(model.scesimData).contains(dataByIndex);
}
|
@Udf
public String uuid() {
return java.util.UUID.randomUUID().toString();
}
|
@Test
public void invalidCapacityShouldReturnNullValue() {
final ByteBuffer bytes = ByteBuffer.wrap(new byte[17]);
final String uuid = udf.uuid(bytes);
assertThat(uuid, is(nullValue()));
}
|
@Override
public FeatureRange clone() throws CloneNotSupportedException {
return (FeatureRange)super.clone();
}
|
@Test
void requireThatCloneIsImplemented() throws CloneNotSupportedException {
FeatureRange node1 = new FeatureRange("foo", 6L, 9L);
FeatureRange node2 = node1.clone();
assertEquals(node1, node2);
assertNotSame(node1, node2);
}
|
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) {
if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) {
return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(),
schemaDefinition.getSchemaWriterOpt().get(), parseSchemaInfo(schemaDefinition, SchemaType.AVRO));
}
ClassLoader pojoClassLoader = null;
if (schemaDefinition.getClassLoader() != null) {
pojoClassLoader = schemaDefinition.getClassLoader();
} else if (schemaDefinition.getPojo() != null) {
pojoClassLoader = schemaDefinition.getPojo().getClassLoader();
}
return new AvroSchema<>(parseSchemaInfo(schemaDefinition, SchemaType.AVRO), pojoClassLoader);
}
|
@Test
public void testLocalDateTime() {
SchemaDefinition<LocalDateTimePojo> schemaDefinition =
SchemaDefinition.<LocalDateTimePojo>builder().withPojo(LocalDateTimePojo.class)
.withJSR310ConversionEnabled(true).build();
AvroSchema<LocalDateTimePojo> avroSchema = AvroSchema.of(schemaDefinition);
LocalDateTime now = LocalDateTime.now();
byte[] bytes = avroSchema.encode(new LocalDateTimePojo(now));
LocalDateTimePojo pojo = avroSchema.decode(bytes);
assertEquals(pojo.getValue().truncatedTo(ChronoUnit.MILLIS), now.truncatedTo(ChronoUnit.MILLIS));
}
|
public Long getNextUniqueId() {
return withMetricLogError(
() ->
withRetryableQuery(
GET_UNIQUE_ROWID,
stmt -> {},
result -> {
if (result.next()) {
return result.getLong(ID_COLUMN);
}
throw new MaestroNotFoundException("crdb unique_rowid() does not return an id");
}),
"getNextUniqueId",
"Failed to get the next unique id");
}
|
@Test
public void testGetNextUniqueId() {
assertNotNull(stepDao.getNextUniqueId());
}
|
@Override
public TimelineDomains getDomains(String owner) throws IOException {
try (DBIterator iterator = ownerdb.iterator()) {
byte[] prefix = KeyBuilder.newInstance().add(owner).getBytesForLookup();
iterator.seek(prefix);
List<TimelineDomain> domains = new ArrayList<TimelineDomain>();
while (iterator.hasNext()) {
byte[] key = iterator.peekNext().getKey();
if (!prefixMatches(prefix, prefix.length, key)) {
break;
}
// Iterator to parse the rows of an individual domain
KeyParser kp = new KeyParser(key, prefix.length);
String domainId = kp.getNextString();
byte[] prefixExt = KeyBuilder.newInstance().add(owner).add(domainId)
.getBytesForLookup();
TimelineDomain domainToReturn = getTimelineDomain(iterator, domainId,
prefixExt);
if (domainToReturn != null) {
domains.add(domainToReturn);
}
}
// Sort the domains to return
Collections.sort(domains, new Comparator<TimelineDomain>() {
@Override
public int compare(TimelineDomain domain1, TimelineDomain domain2) {
int result = domain2.getCreatedTime().compareTo(
domain1.getCreatedTime());
if (result == 0) {
return domain2.getModifiedTime().compareTo(
domain1.getModifiedTime());
} else {
return result;
}
}
});
TimelineDomains domainsToReturn = new TimelineDomains();
domainsToReturn.addDomains(domains);
return domainsToReturn;
}
}
|
@Test
public void testGetDomains() throws IOException {
super.testGetDomains();
}
|
public IntArrayList getEdgesWithDifferentHeading(int baseNode, double heading) {
double xAxisAngle = AngleCalc.ANGLE_CALC.convertAzimuth2xaxisAngle(heading);
IntArrayList edges = new IntArrayList(1);
EdgeIterator iter = edgeExplorer.setBaseNode(baseNode);
while (iter.next()) {
PointList points = iter.fetchWayGeometry(FetchMode.ALL);
double orientation = AngleCalc.ANGLE_CALC.calcOrientation(
points.getLat(0), points.getLon(0),
points.getLat(1), points.getLon(1)
);
orientation = AngleCalc.ANGLE_CALC.alignOrientation(xAxisAngle, orientation);
double diff = Math.abs(orientation - xAxisAngle);
if (diff > toleranceRad)
edges.add(iter.getEdge());
}
return edges;
}
|
@Test
public void withQueryGraph() {
// 2
// 0 -x- 1
BooleanEncodedValue accessEnc = new SimpleBooleanEncodedValue("access", true);
DecimalEncodedValue speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false);
EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).build();
BaseGraph graph = new BaseGraph.Builder(em).create();
NodeAccess na = graph.getNodeAccess();
na.setNode(0, 48.8611, 1.2194);
na.setNode(1, 48.8538, 2.3950);
EdgeIteratorState edge = GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(0, 1).setDistance(10));
Snap snap = createSnap(edge, 48.859, 2.00, 0);
QueryGraph queryGraph = QueryGraph.create(graph, snap);
HeadingResolver resolver = new HeadingResolver(queryGraph);
// if the heading points East we get the Western edge 0->2
assertEquals("0->2", queryGraph.getEdgeIteratorState(1, Integer.MIN_VALUE).toString());
assertEquals(IntArrayList.from(1), resolver.getEdgesWithDifferentHeading(2, 90));
// if the heading points West we get the Eastern edge 2->1
assertEquals("2->1", queryGraph.getEdgeIteratorState(2, Integer.MIN_VALUE).toString());
assertEquals(IntArrayList.from(2), resolver.getEdgesWithDifferentHeading(2, 270));
}
|
public void setProtectThreshold(float protectThreshold) {
this.protectThreshold = protectThreshold;
}
|
@Test
void testSetProtectThreshold() {
serviceMetadata.setProtectThreshold(1.0F);
assertEquals(1.0F, serviceMetadata.getProtectThreshold(), 0);
}
|
static ParseResult parse(String expression, NameValidator validator, ClassHelper helper) {
ParseResult result = new ParseResult();
try {
Parser parser = new Parser(new Scanner("ignore", new StringReader(expression)));
Java.Atom atom = parser.parseConditionalExpression();
// after parsing the expression the input should end (otherwise it is not "simple")
if (parser.peek().type == TokenType.END_OF_INPUT) {
result.guessedVariables = new LinkedHashSet<>();
ConditionalExpressionVisitor visitor = new ConditionalExpressionVisitor(result, validator, helper);
result.ok = atom.accept(visitor);
result.invalidMessage = visitor.invalidMessage;
if (result.ok) {
result.converted = new StringBuilder(expression.length());
int start = 0;
for (Replacement replace : visitor.replacements.values()) {
result.converted.append(expression, start, replace.start).append(replace.newString);
start = replace.start + replace.oldLength;
}
result.converted.append(expression.substring(start));
}
}
} catch (Exception ex) {
}
return result;
}
|
@Test
public void testNegativeConstant() {
ParseResult result = parse("average_slope < -0.5", "average_slope"::equals, k -> "");
assertTrue(result.ok);
assertEquals("[average_slope]", result.guessedVariables.toString());
result = parse("-average_slope > -0.5", "average_slope"::equals, k -> "");
assertTrue(result.ok);
assertEquals("[average_slope]", result.guessedVariables.toString());
result = parse("Math.sqrt(-2)", (var) -> false, k -> "");
assertTrue(result.ok);
assertTrue(result.guessedVariables.isEmpty());
}
|
public void allocationQuantum(int allocationQuantum) {
checkPositive(allocationQuantum, "allocationQuantum");
this.allocationQuantum = allocationQuantum;
}
|
@Test
public void writeShouldPreferHighestWeight() throws Http2Exception {
// Root the streams at the connection and assign weights.
setPriority(STREAM_A, 0, (short) 50, false);
setPriority(STREAM_B, 0, (short) 200, false);
setPriority(STREAM_C, 0, (short) 100, false);
setPriority(STREAM_D, 0, (short) 100, false);
initState(STREAM_A, 1000, true);
initState(STREAM_B, 1000, true);
initState(STREAM_C, 1000, true);
initState(STREAM_D, 1000, true);
// Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream.
distributor.allocationQuantum(1);
assertTrue(write(1000));
assertEquals(100, captureWrites(STREAM_A));
assertEquals(450, captureWrites(STREAM_B));
assertEquals(225, captureWrites(STREAM_C));
assertEquals(225, captureWrites(STREAM_D));
}
|
@Override
public void remove(final String name) {
this.faultItemTable.remove(name);
}
|
@Test
public void testRemove() throws Exception {
latencyFaultTolerance.updateFaultItem(brokerName, 3000, 3000, true);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();
latencyFaultTolerance.remove(brokerName);
assertThat(latencyFaultTolerance.isAvailable(brokerName)).isTrue();
}
|
@Override
public LeaveGroupRequest.Builder buildBatchedRequest(int coordinatorId, Set<CoordinatorKey> groupIds) {
validateKeys(groupIds);
return new LeaveGroupRequest.Builder(groupId.idValue, members);
}
|
@Test
public void testBuildRequest() {
RemoveMembersFromConsumerGroupHandler handler = new RemoveMembersFromConsumerGroupHandler(groupId, members, logContext);
LeaveGroupRequest request = handler.buildBatchedRequest(1, singleton(CoordinatorKey.byGroupId(groupId))).build();
assertEquals(groupId, request.data().groupId());
assertEquals(2, request.data().members().size());
}
|
@SuppressWarnings("unchecked")
protected ValueWrapper getSingleFactValueResult(FactMapping factMapping,
FactMappingValue expectedResult,
DMNDecisionResult decisionResult,
List<DMNMessage> failureMessages,
ExpressionEvaluator expressionEvaluator) {
Object resultRaw = decisionResult.getResult();
final DMNDecisionResult.DecisionEvaluationStatus evaluationStatus = decisionResult.getEvaluationStatus();
if (!SUCCEEDED.equals(evaluationStatus)) {
String failureReason = determineFailureMessage(evaluationStatus, failureMessages);
return errorWithMessage("The decision \"" +
decisionResult.getDecisionName() +
"\" has not been successfully evaluated: " +
failureReason);
}
List<ExpressionElement> elementsWithoutClass = factMapping.getExpressionElementsWithoutClass();
// DMN engine doesn't generate the whole object when no entry of the decision table match
if (resultRaw != null) {
for (ExpressionElement expressionElement : elementsWithoutClass) {
if (!(resultRaw instanceof Map)) {
throw new ScenarioException("Wrong resultRaw structure because it is not a complex type as expected");
}
Map<String, Object> result = (Map<String, Object>) resultRaw;
resultRaw = result.get(expressionElement.getStep());
}
}
Class<?> resultClass = resultRaw != null ? resultRaw.getClass() : null;
Object expectedResultRaw = expectedResult.getRawValue();
return getResultWrapper(factMapping.getClassName(),
expectedResult,
expressionEvaluator,
expectedResultRaw,
resultRaw,
resultClass);
}
|
@Test
public void getSingleFactValueResult_failDecision() {
DMNDecisionResult failedDecision = createDecisionResultMock("Test", false, new ArrayList<>());
ValueWrapper<?> failedResult = runnerHelper.getSingleFactValueResult(null,
null,
failedDecision,
null,
expressionEvaluator);
assertThat(failedResult.isValid()).isFalse();
assertThat(failedResult.getErrorMessage().get()).isEqualTo("The decision \"" +
failedDecision.getDecisionName() +
"\" has not been successfully evaluated: " +
failedDecision.getEvaluationStatus());
}
|
@Override
public void logoutSuccess(HttpRequest request, @Nullable String login) {
checkRequest(request);
if (!LOGGER.isDebugEnabled()) {
return;
}
LOGGER.debug("logout success [IP|{}|{}][login|{}]",
request.getRemoteAddr(), getAllIps(request),
preventLogFlood(emptyIfNull(login)));
}
|
@Test
public void logout_success_does_not_interact_with_request_if_log_level_is_above_DEBUG() {
HttpRequest request = mock(HttpRequest.class);
logTester.setLevel(Level.INFO);
underTest.logoutSuccess(request, "foo");
verifyNoInteractions(request);
}
|
public RingbufferConfig setRingbufferStoreConfig(RingbufferStoreConfig ringbufferStoreConfig) {
this.ringbufferStoreConfig = ringbufferStoreConfig;
return this;
}
|
@Test
public void setRingbufferStoreConfig() {
RingbufferStoreConfig ringbufferStoreConfig = new RingbufferStoreConfig()
.setEnabled(true)
.setClassName("myClassName");
RingbufferConfig config = new RingbufferConfig(NAME);
config.setRingbufferStoreConfig(ringbufferStoreConfig);
assertEquals(ringbufferStoreConfig, config.getRingbufferStoreConfig());
}
|
@VisibleForTesting
void parseWorkflowParameter(
Map<String, Parameter> workflowParams, Parameter param, String workflowId) {
parseWorkflowParameter(workflowParams, param, workflowId, new HashSet<>());
}
|
@Test
public void testParseWorkflowParameterWithImplicitToLong() {
LongParameter bar = LongParameter.builder().name("bar").expression("foo + 1;").build();
paramEvaluator.parseWorkflowParameter(
Collections.singletonMap("foo", StringParameter.builder().expression("1+2+3;").build()),
bar,
"test-workflow");
assertEquals(61, (long) bar.getEvaluatedResult());
assertEquals(
"Implicitly converted the evaluated result to a long for type String",
bar.getMeta().get("warn"));
bar = LongParameter.builder().name("bar").expression("foo + 1;").build();
paramEvaluator.parseWorkflowParameter(
Collections.singletonMap(
"foo", StringParameter.builder().evaluatedResult("100").evaluatedTime(123L).build()),
bar,
"test-workflow");
assertEquals(1001, (long) bar.getEvaluatedResult());
assertEquals(
"Implicitly converted the evaluated result to a long for type String",
bar.getMeta().get("warn"));
AssertHelper.assertThrows(
"Can only cast string to long",
IllegalArgumentException.class,
"Param [bar] is expected to be a Long compatible type but is [class java.lang.Double]",
() ->
paramEvaluator.parseWorkflowParameter(
Collections.emptyMap(),
LongParameter.builder().name("bar").expression("0.01;").build(),
"test-workflow"));
AssertHelper.assertThrows(
"Can only cast valid string to long",
NumberFormatException.class,
"For input string: \"foo\"",
() ->
paramEvaluator.parseWorkflowParameter(
Collections.emptyMap(),
LongParameter.builder().name("bar").expression("'foo';").build(),
"test-workflow"));
}
|
protected CompletableFuture<AckMessageResponse> ackMessageInBatch(ProxyContext ctx, String group, String topic, AckMessageRequest request) {
List<ReceiptHandleMessage> handleMessageList = new ArrayList<>(request.getEntriesCount());
for (AckMessageEntry ackMessageEntry : request.getEntriesList()) {
String handleString = getHandleString(ctx, group, request, ackMessageEntry);
handleMessageList.add(new ReceiptHandleMessage(ReceiptHandle.decode(handleString), ackMessageEntry.getMessageId()));
}
return this.messagingProcessor.batchAckMessage(ctx, handleMessageList, group, topic)
.thenApply(batchAckResultList -> {
AckMessageResponse.Builder responseBuilder = AckMessageResponse.newBuilder();
Set<Code> responseCodes = new HashSet<>();
for (BatchAckResult batchAckResult : batchAckResultList) {
AckMessageResultEntry entry = convertToAckMessageResultEntry(batchAckResult);
responseBuilder.addEntries(entry);
responseCodes.add(entry.getStatus().getCode());
}
setAckResponseStatus(responseBuilder, responseCodes);
return responseBuilder.build();
});
}
|
@Test
public void testAckMessageInBatch() throws Throwable {
ConfigurationManager.getProxyConfig().setEnableBatchAck(true);
String successMessageId = "msg1";
String notOkMessageId = "msg2";
String exceptionMessageId = "msg3";
doAnswer((Answer<CompletableFuture<List<BatchAckResult>>>) invocation -> {
List<ReceiptHandleMessage> receiptHandleMessageList = invocation.getArgument(1, List.class);
List<BatchAckResult> batchAckResultList = new ArrayList<>();
for (ReceiptHandleMessage receiptHandleMessage : receiptHandleMessageList) {
BatchAckResult batchAckResult;
if (receiptHandleMessage.getMessageId().equals(successMessageId)) {
AckResult ackResult = new AckResult();
ackResult.setStatus(AckStatus.OK);
batchAckResult = new BatchAckResult(receiptHandleMessage, ackResult);
} else if (receiptHandleMessage.getMessageId().equals(notOkMessageId)) {
AckResult ackResult = new AckResult();
ackResult.setStatus(AckStatus.NO_EXIST);
batchAckResult = new BatchAckResult(receiptHandleMessage, ackResult);
} else {
batchAckResult = new BatchAckResult(receiptHandleMessage, new ProxyException(ProxyExceptionCode.INVALID_RECEIPT_HANDLE, ""));
}
batchAckResultList.add(batchAckResult);
}
return CompletableFuture.completedFuture(batchAckResultList);
}).when(this.messagingProcessor).batchAckMessage(any(), anyList(), anyString(), anyString());
{
AckMessageResponse response = this.ackMessageActivity.ackMessage(
createContext(),
AckMessageRequest.newBuilder()
.setTopic(Resource.newBuilder().setName(TOPIC).build())
.setGroup(Resource.newBuilder().setName(GROUP).build())
.addEntries(AckMessageEntry.newBuilder()
.setMessageId(successMessageId)
.setReceiptHandle(buildReceiptHandle(TOPIC, System.currentTimeMillis(), 3000))
.build())
.build()
).get();
assertEquals(Code.OK, response.getStatus().getCode());
}
{
AckMessageResponse response = this.ackMessageActivity.ackMessage(
createContext(),
AckMessageRequest.newBuilder()
.setTopic(Resource.newBuilder().setName(TOPIC).build())
.setGroup(Resource.newBuilder().setName(GROUP).build())
.addEntries(AckMessageEntry.newBuilder()
.setMessageId(notOkMessageId)
.setReceiptHandle(buildReceiptHandle(TOPIC, System.currentTimeMillis(), 3000))
.build())
.build()
).get();
assertEquals(Code.INTERNAL_SERVER_ERROR, response.getStatus().getCode());
}
{
AckMessageResponse response = this.ackMessageActivity.ackMessage(
createContext(),
AckMessageRequest.newBuilder()
.setTopic(Resource.newBuilder().setName(TOPIC).build())
.setGroup(Resource.newBuilder().setName(GROUP).build())
.addEntries(AckMessageEntry.newBuilder()
.setMessageId(exceptionMessageId)
.setReceiptHandle(buildReceiptHandle(TOPIC, System.currentTimeMillis(), 3000))
.build())
.build()
).get();
assertEquals(Code.INVALID_RECEIPT_HANDLE, response.getStatus().getCode());
}
{
AckMessageResponse response = this.ackMessageActivity.ackMessage(
createContext(),
AckMessageRequest.newBuilder()
.setTopic(Resource.newBuilder().setName(TOPIC).build())
.setGroup(Resource.newBuilder().setName(GROUP).build())
.addEntries(AckMessageEntry.newBuilder()
.setMessageId(successMessageId)
.setReceiptHandle(buildReceiptHandle(TOPIC, System.currentTimeMillis(), 3000))
.build())
.addEntries(AckMessageEntry.newBuilder()
.setMessageId(notOkMessageId)
.setReceiptHandle(buildReceiptHandle(TOPIC, System.currentTimeMillis(), 3000))
.build())
.addEntries(AckMessageEntry.newBuilder()
.setMessageId(exceptionMessageId)
.setReceiptHandle(buildReceiptHandle(TOPIC, System.currentTimeMillis(), 3000))
.build())
.build()
).get();
assertEquals(Code.MULTIPLE_RESULTS, response.getStatus().getCode());
assertEquals(3, response.getEntriesCount());
Map<String, Code> msgCode = new HashMap<>();
for (AckMessageResultEntry entry : response.getEntriesList()) {
msgCode.put(entry.getMessageId(), entry.getStatus().getCode());
}
assertEquals(Code.OK, msgCode.get(successMessageId));
assertEquals(Code.INTERNAL_SERVER_ERROR, msgCode.get(notOkMessageId));
assertEquals(Code.INVALID_RECEIPT_HANDLE, msgCode.get(exceptionMessageId));
}
}
|
@GetMapping("/")
public List<ServiceDTO> listAllServices() {
List<ServiceDTO> allServices = Lists.newLinkedList();
allServices
.addAll(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE));
allServices.addAll(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE));
return allServices;
}
|
@Test
public void testListAllServices() {
ServiceDTO someServiceDto = mock(ServiceDTO.class);
ServiceDTO anotherServiceDto = mock(ServiceDTO.class);
when(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE)).thenReturn(
Lists.newArrayList(someServiceDto));
when(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE)).thenReturn(
Lists.newArrayList(anotherServiceDto));
List<ServiceDTO> allServices = homePageController.listAllServices();
assertEquals(2, allServices.size());
assertSame(someServiceDto, allServices.get(0));
assertSame(anotherServiceDto, allServices.get(1));
}
|
public SortOrder sortOrder() {
return sortOrdersById.get(defaultSortOrderId);
}
|
@Test
public void testSortOrder() {
Schema schema = new Schema(Types.NestedField.required(10, "x", Types.StringType.get()));
TableMetadata meta =
TableMetadata.newTableMetadata(
schema, PartitionSpec.unpartitioned(), null, ImmutableMap.of());
assertThat(meta.sortOrder().isUnsorted()).isTrue();
assertThat(meta.replaceSortOrder(SortOrder.unsorted()))
.as("Should detect identical unsorted order")
.isSameAs(meta);
}
|
@Override
public String toString() {
return "ConfigResource(type=" + type + ", name='" + name + "')";
}
|
@Test
public void shouldRoundTripEveryType() {
Arrays.stream(ConfigResource.Type.values()).forEach(type ->
assertEquals(type, ConfigResource.Type.forId(type.id()), type.toString()));
}
|
@Operation(summary = "provide session", tags = { SwaggerConfig.UPGRADE_LOGIN_LEVEL }, operationId = "digidRdaInit",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")})
@PostMapping(value = "rda/init", produces = "application/json")
@ResponseBody
public AppResponse getSessionRda(@RequestBody RdaSessionRequest request) throws FlowNotDefinedException, NoSuchAlgorithmException, FlowStateNotDefinedException, IOException, SharedServiceClientException {
return service.startFlow(UpgradeLoginLevel.NAME, Action.INIT_RDA, request);
}
|
@Test
void validateIfcorrectProcessesAreCalledRequestStationgetSessionRda () throws FlowNotDefinedException, SharedServiceClientException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException {
RdaSessionRequest request = new RdaSessionRequest();
activationController.getSessionRda(request);
verify(flowService, times(1)).startFlow(anyString(), any(), any());
}
|
public static URI parse(String gluePath) {
requireNonNull(gluePath, "gluePath may not be null");
if (gluePath.isEmpty()) {
return rootPackageUri();
}
// Legacy from the Cucumber Eclipse plugin
// Older versions of Cucumber allowed it.
if (CLASSPATH_SCHEME_PREFIX.equals(gluePath)) {
return rootPackageUri();
}
if (nonStandardPathSeparatorInUse(gluePath)) {
String standardized = replaceNonStandardPathSeparator(gluePath);
return parseAssumeClasspathScheme(standardized);
}
if (isProbablyPackage(gluePath)) {
String path = resourceNameOfPackageName(gluePath);
return parseAssumeClasspathScheme(path);
}
return parseAssumeClasspathScheme(gluePath);
}
|
@Test
void can_parse_empty_glue_path() {
URI uri = GluePath.parse("");
assertAll(
() -> assertThat(uri.getScheme(), is("classpath")),
() -> assertThat(uri.getSchemeSpecificPart(), is("/")));
}
|
public Map<String, PartitionStatistics> getQuickStats(ConnectorSession session, SemiTransactionalHiveMetastore metastore, SchemaTableName table,
MetastoreContext metastoreContext, List<String> partitionIds)
{
if (!isQuickStatsEnabled(session)) {
return partitionIds.stream().collect(toMap(k -> k, v -> empty()));
}
CompletableFuture<PartitionStatistics>[] partitionQuickStatCompletableFutures = new CompletableFuture[partitionIds.size()];
for (int counter = 0; counter < partitionIds.size(); counter++) {
String partitionId = partitionIds.get(counter);
partitionQuickStatCompletableFutures[counter] = supplyAsync(() -> getQuickStats(session, metastore, table, metastoreContext, partitionId), backgroundFetchExecutor);
}
try {
// Wait for all the partitions to get their quick stats
// If this query is reading a partition for which we do not already have cached quick stats,
// we will block the execution of the query until the stats are fetched for all such partitions,
// or we time out waiting for the fetch
allOf(partitionQuickStatCompletableFutures).get(getQuickStatsInlineBuildTimeoutMillis(session), MILLISECONDS);
}
catch (InterruptedException | ExecutionException e) {
log.error(e);
throw new RuntimeException(e);
}
catch (TimeoutException e) {
log.warn(e, "Timeout while building quick stats");
}
ImmutableMap.Builder<String, PartitionStatistics> result = ImmutableMap.builder();
for (int counter = 0; counter < partitionQuickStatCompletableFutures.length; counter++) {
String partitionId = partitionIds.get(counter);
CompletableFuture<PartitionStatistics> future = partitionQuickStatCompletableFutures[counter];
if (future.isDone() && !future.isCancelled() && !future.isCompletedExceptionally()) {
try {
result.put(partitionId, future.get());
}
catch (InterruptedException | ExecutionException e) {
// This should not happen because we checked that the future was completed successfully
log.error(e, "Failed to get value for a quick stats future which was completed successfully");
throw new RuntimeException(e);
}
}
else {
// If a future did not finish, or finished exceptionally, we do not add it to the results
// A new query for the same partition could trigger a successful quick stats fetch for this partition
result.put(partitionId, empty());
}
}
return result.build();
}
|
@Test(enabled = false, invocationCount = 3)
public void testConcurrentFetchForSamePartition()
throws ExecutionException, InterruptedException
{
QuickStatsBuilder longRunningQuickStatsBuilderMock = (session, metastore, table, metastoreContext, partitionId, files) -> {
// Sleep for 50ms to simulate a long-running quick stats call
sleepUninterruptibly(50, MILLISECONDS);
return mockPartitionQuickStats;
};
QuickStatsProvider quickStatsProvider = new QuickStatsProvider(hdfsEnvironment, directoryListerMock, hiveClientConfig, new NamenodeStats(),
ImmutableList.of(longRunningQuickStatsBuilderMock));
List<String> testPartitions = ImmutableList.of("partition1", "partition2", "partition3");
{
// Build a session where an inline quick stats build will occur for the 1st query that initiates the build,
// but subsequent queries will NOT wait
ConnectorSession session = getSession("600ms", "0ms");
// Execute two concurrent calls for the same partitions; wait for them to complete
CompletableFuture<Map<String, PartitionStatistics>> future1 = supplyAsync(() -> quickStatsProvider.getQuickStats(session, metastoreMock,
new SchemaTableName(TEST_SCHEMA, TEST_TABLE), metastoreContext, testPartitions), commonPool());
CompletableFuture<Map<String, PartitionStatistics>> future2 = supplyAsync(() -> quickStatsProvider.getQuickStats(session, metastoreMock,
new SchemaTableName(TEST_SCHEMA, TEST_TABLE), metastoreContext, testPartitions), commonPool());
allOf(future1, future2).join();
Map<String, PartitionStatistics> quickStats1 = future1.get();
Map<String, PartitionStatistics> quickStats2 = future2.get();
// Both PartitionStatistics have stats for all partitions
assertEquals(quickStats1.entrySet().size(), testPartitions.size());
assertTrue(quickStats1.keySet().containsAll(testPartitions));
assertEquals(quickStats2.entrySet().size(), testPartitions.size());
assertTrue(quickStats2.keySet().containsAll(testPartitions));
// For the same partition, we will observe that one of them has the expected partition stats and the other one is empty
for (String testPartition : testPartitions) {
PartitionStatistics partitionStatistics1 = quickStats1.get(testPartition);
PartitionStatistics partitionStatistics2 = quickStats2.get(testPartition);
if (partitionStatistics1.equals(empty())) {
assertEquals(partitionStatistics2, expectedPartitionStats);
}
else if (partitionStatistics2.equals(empty())) {
assertEquals(partitionStatistics1, expectedPartitionStats);
}
else {
fail(String.format("For [%s] one of the partitions stats was expected to be empty. Actual partitionStatistics1 [%s], partitionStatistics2 [%s]",
testPartition, partitionStatistics1, partitionStatistics2));
}
}
// Future calls for the same partitions will return from cached partition stats with valid values
Map<String, PartitionStatistics> quickStats = quickStatsProvider.getQuickStats(session, metastoreMock,
new SchemaTableName(TEST_SCHEMA, TEST_TABLE), metastoreContext, testPartitions);
// Verify only one call was made for each test partition
assertEquals(quickStats.entrySet().size(), testPartitions.size());
assertTrue(quickStats.keySet().containsAll(testPartitions));
quickStats.values().forEach(ps -> assertEquals(ps, expectedPartitionStats));
}
{
// Build a session where an inline quick stats build will occur for the 1st query that initiates the build,
// and subsequent queries will wait for this inline build to finish too
ConnectorSession session = getSession("300ms", "300ms");
// Execute two concurrent calls for the same partitions; wait for them to complete
CompletableFuture<Map<String, PartitionStatistics>> future1 = supplyAsync(() -> quickStatsProvider.getQuickStats(session, metastoreMock,
new SchemaTableName(TEST_SCHEMA, TEST_TABLE), metastoreContext, testPartitions), commonPool());
CompletableFuture<Map<String, PartitionStatistics>> future2 = supplyAsync(() -> quickStatsProvider.getQuickStats(session, metastoreMock,
new SchemaTableName(TEST_SCHEMA, TEST_TABLE), metastoreContext, testPartitions), commonPool());
allOf(future1, future2).join();
Map<String, PartitionStatistics> quickStats1 = future1.get();
Map<String, PartitionStatistics> quickStats2 = future2.get();
assertEquals(quickStats1, quickStats2); // Both PartitionStatistics have exactly same stats
assertTrue(quickStats1.keySet().containsAll(testPartitions)); // Stats for all partitions are present
// None of the partition stats are empty, they are all the mocked value
assertTrue(quickStats1.values().stream().allMatch(x -> x.equals(convertToPartitionStatistics(mockPartitionQuickStats))));
}
}
|
public static String keyToString(Object key,
URLEscaper.Escaping escaping,
UriComponent.Type componentType,
boolean full,
ProtocolVersion version)
{
if (version.compareTo(AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion()) >= 0)
{
return keyToStringV2(key, escaping, componentType, full);
}
else
{
return keyToStringV1(key, escaping, full);
}
}
|
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "stringKey")
public void testStringKeyToString(ProtocolVersion version, String expected)
{
String stringKey = "key";
String stringKeyString = URIParamUtils.keyToString(stringKey, NO_ESCAPING, null, true, version);
Assert.assertEquals(stringKeyString, expected);
}
|
@Override
public int write(String path, ByteBuffer buf, long size, long offset, FuseFileInfo fi) {
final long fd = fi.fh.get();
return AlluxioFuseUtils.call(LOG, () -> writeInternal(path, buf, size, offset, fd),
FuseConstants.FUSE_WRITE, "path=%s,fd=%d,size=%d,offset=%d",
path, fd, size, offset);
}
|
@Test
public void write() throws Exception {
FileOutStream fos = mock(FileOutStream.class);
AlluxioURI anyURI = any();
CreateFilePOptions options = any();
when(mFileSystem.createFile(anyURI, options)).thenReturn(fos);
// "create" checks if the file already exists first
when(mFileSystem.getStatus(any(AlluxioURI.class)))
.thenThrow(mock(FileDoesNotExistException.class));
// open a file
mFileInfo.flags.set(O_WRONLY.intValue());
mFuseFs.create("/foo/bar", 0, mFileInfo);
// prepare something to write into it
ByteBuffer ptr = ByteBuffer.allocateDirect(4);
byte[] expected = {42, -128, 1, 3};
ptr.put(expected, 0, 4);
ptr.flip();
mFuseFs.write("/foo/bar", ptr, 4, 0, mFileInfo);
verify(fos).write(expected);
// the second write is no-op because the writes must be sequential and overwriting is supported
mFuseFs.write("/foo/bar", ptr, 4, 0, mFileInfo);
verify(fos, times(1)).write(expected);
}
|
@Override
public void merge(Accumulator<Double, Double> other) {
this.min = Math.min(this.min, other.getLocalValue());
}
|
@Test
void testMerge() {
DoubleMinimum min1 = new DoubleMinimum();
min1.add(1234.5768);
DoubleMinimum min2 = new DoubleMinimum();
min2.add(5678.9012);
min2.merge(min1);
assertThat(min2.getLocalValue()).isCloseTo(1234.5768, within(0.0));
min1.merge(min2);
assertThat(min1.getLocalValue()).isCloseTo(1234.5768, within(0.0));
}
|
@Override
public AwsProxyResponse handle(Throwable ex) {
log.error("Called exception handler for:", ex);
// adding a print stack trace in case we have no appender or we are running inside SAM local, where need the
// output to go to the stderr.
ex.printStackTrace();
if (ex instanceof InvalidRequestEventException || ex instanceof InternalServerErrorException) {
return new AwsProxyResponse(500, HEADERS, getErrorJson(INTERNAL_SERVER_ERROR));
} else {
return new AwsProxyResponse(502, HEADERS, getErrorJson(GATEWAY_TIMEOUT_ERROR));
}
}
|
@Test
void streamHandle_InvalidResponseObjectException_responseString()
throws IOException {
ByteArrayOutputStream respStream = new ByteArrayOutputStream();
exceptionHandler.handle(new InvalidResponseObjectException(INVALID_RESPONSE_MESSAGE, null), respStream);
assertNotNull(respStream);
assertTrue(respStream.size() > 0);
AwsProxyResponse resp = objectMapper.readValue(new ByteArrayInputStream(respStream.toByteArray()), AwsProxyResponse.class);
assertNotNull(resp);
String body = objectMapper.writeValueAsString(new ErrorModel(AwsProxyExceptionHandler.GATEWAY_TIMEOUT_ERROR));
assertEquals(body, resp.getBody());
}
|
private QueryFederationQueuePoliciesResponse filterPoliciesConfigurationsByQueues(
List<String> queues, Map<String, SubClusterPolicyConfiguration> policiesConfigurations,
int pageSize, int currentPage) throws YarnException {
// Step1. Check the parameters, if the policy list is empty, return empty directly.
if (MapUtils.isEmpty(policiesConfigurations)) {
return null;
}
// Step2. Filtering for Queue Policies.
List<FederationQueueWeight> federationQueueWeights = new ArrayList<>();
for (String queue : queues) {
SubClusterPolicyConfiguration policyConf = policiesConfigurations.getOrDefault(queue, null);
if(policyConf == null) {
continue;
}
FederationQueueWeight federationQueueWeight = parseFederationQueueWeight(queue, policyConf);
if (federationQueueWeight != null) {
federationQueueWeights.add(federationQueueWeight);
}
}
// Step3. To paginate the returned results.
return queryFederationQueuePoliciesPagination(federationQueueWeights, pageSize, currentPage);
}
|
@Test
public void testFilterPoliciesConfigurationsByQueues() throws Exception {
// SubClusters : SC-1,SC-2
List<String> subClusterLists = new ArrayList<>();
subClusterLists.add("SC-1");
subClusterLists.add("SC-2");
// We initialize 26 queues, queue root.a~root.z
List<FederationQueueWeight> federationQueueWeights = new ArrayList<>();
for (char letter = 'a'; letter <= 'z'; letter++) {
FederationQueueWeight leaf =
generateFederationQueueWeight("root." + letter, subClusterLists);
federationQueueWeights.add(leaf);
}
// Save Queue Policies in Batches
BatchSaveFederationQueuePoliciesRequest request =
BatchSaveFederationQueuePoliciesRequest.newInstance(federationQueueWeights);
BatchSaveFederationQueuePoliciesResponse policiesResponse =
interceptor.batchSaveFederationQueuePolicies(request);
assertNotNull(policiesResponse);
assertNotNull(policiesResponse.getMessage());
assertEquals("batch save policies success.", policiesResponse.getMessage());
// We query 12 queues, root.a ~ root.l
List<String> queues = new ArrayList<>();
for (char letter = 'a'; letter <= 'l'; letter++) {
queues.add("root." + letter);
}
// Queue1: We query page 1, 10 items per page, and the returned result should be 10 items.
// TotalPage should be 2, TotalSize should be 12.
QueryFederationQueuePoliciesRequest request1 =
QueryFederationQueuePoliciesRequest.newInstance(10, 1, "", queues);
QueryFederationQueuePoliciesResponse response1 =
interceptor.listFederationQueuePolicies(request1);
assertNotNull(response1);
assertEquals(1, response1.getCurrentPage());
assertEquals(10, response1.getPageSize());
assertEquals(2, response1.getTotalPage());
assertEquals(12, response1.getTotalSize());
List<FederationQueueWeight> federationQueueWeights1 = response1.getFederationQueueWeights();
assertNotNull(federationQueueWeights1);
assertEquals(10, federationQueueWeights1.size());
// Queue2: We query page 1, 12 items per page, and the returned result should be 12 items.
// TotalPage should be 1, TotalSize should be 12.
QueryFederationQueuePoliciesRequest request2 =
QueryFederationQueuePoliciesRequest.newInstance(12, 1, "", queues);
QueryFederationQueuePoliciesResponse response2 =
interceptor.listFederationQueuePolicies(request2);
assertNotNull(response2);
assertEquals(1, response2.getCurrentPage());
assertEquals(12, response2.getPageSize());
assertEquals(1, response2.getTotalPage());
assertEquals(12, response2.getTotalSize());
List<FederationQueueWeight> federationQueueWeights2 = response2.getFederationQueueWeights();
assertNotNull(federationQueueWeights2);
assertEquals(12, federationQueueWeights2.size());
// Queue3: Boundary limit exceeded
// We filter 12 queues, should return 12 records, 12 per page,
// should return 1 page, but we are going to return page 2.
QueryFederationQueuePoliciesRequest request3 =
QueryFederationQueuePoliciesRequest.newInstance(12, 2, "", queues);
QueryFederationQueuePoliciesResponse response3 =
interceptor.listFederationQueuePolicies(request3);
assertNotNull(response3);
assertEquals(2, response3.getCurrentPage());
assertEquals(12, response3.getPageSize());
assertEquals(1, response2.getTotalPage());
assertEquals(12, response3.getTotalSize());
List<FederationQueueWeight> federationQueueWeights3 = response3.getFederationQueueWeights();
assertNotNull(federationQueueWeights3);
assertEquals(0, federationQueueWeights3.size());
// Queue4: Boundary limit exceeded
// We pass in some negative parameters and we will get some exceptions
QueryFederationQueuePoliciesRequest request4 =
QueryFederationQueuePoliciesRequest.newInstance(-1, 2, "", queues);
LambdaTestUtils.intercept(YarnException.class, "PageSize cannot be negative or zero.",
() -> interceptor.listFederationQueuePolicies(request4));
// Queue5: Boundary limit exceeded
// We pass in some negative parameters and we will get some exceptions
QueryFederationQueuePoliciesRequest request5 =
QueryFederationQueuePoliciesRequest.newInstance(10, -1, "", queues);
LambdaTestUtils.intercept(YarnException.class, "CurrentPage cannot be negative or zero.",
() -> interceptor.listFederationQueuePolicies(request5));
// Queue6: We use Queue as the condition,
// at this time we will only get the only one return value.
QueryFederationQueuePoliciesRequest request6 =
QueryFederationQueuePoliciesRequest.newInstance(10, 1, "root.a", null);
QueryFederationQueuePoliciesResponse response6 =
interceptor.listFederationQueuePolicies(request6);
assertNotNull(response6);
assertEquals(1, response6.getCurrentPage());
assertEquals(10, response6.getPageSize());
assertEquals(1, response6.getTotalPage());
assertEquals(1, response6.getTotalSize());
List<FederationQueueWeight> federationQueueWeights6 = response6.getFederationQueueWeights();
assertNotNull(federationQueueWeights6);
assertEquals(1, federationQueueWeights6.size());
// Queue7: We design such a test case, we do not set any filter conditions,
// but we need to get the return results
QueryFederationQueuePoliciesRequest request7 =
QueryFederationQueuePoliciesRequest.newInstance(10, 1, null, null);
QueryFederationQueuePoliciesResponse response7 =
interceptor.listFederationQueuePolicies(request7);
assertNotNull(response7);
assertEquals(1, response7.getCurrentPage());
assertEquals(10, response7.getPageSize());
assertEquals(3, response7.getTotalPage());
assertEquals(26, response7.getTotalSize());
List<FederationQueueWeight> federationQueueWeights7 = response7.getFederationQueueWeights();
assertNotNull(federationQueueWeights7);
assertEquals(10, federationQueueWeights7.size());
// Queue8: We are designing a unit test where the number of records
// we need to retrieve exceeds the maximum number of Policies available.
QueryFederationQueuePoliciesRequest request8 =
QueryFederationQueuePoliciesRequest.newInstance(10, 10, null, null);
LambdaTestUtils.intercept(YarnException.class,
"The index of the records to be retrieved has exceeded the maximum index.",
() -> interceptor.listFederationQueuePolicies(request8));
}
|
String getEntryName( String name ) {
return "${"
+ Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY + "}/" + name;
}
|
@Test
public void testEntryName() {
assertEquals( "${Internal.Entry.Current.Directory}/" + FILE_NAME, dialog.getEntryName( FILE_NAME ) );
}
|
@Override
public RSet<V> get(final K key) {
String keyHash = keyHash(key);
final String setName = getValuesName(keyHash);
return new RedissonSet<V>(codec, commandExecutor, setName, null) {
@Override
public RFuture<Boolean> addAsync(V value) {
return RedissonSetMultimap.this.putAsync(key, value);
}
@Override
public RFuture<Boolean> addAllAsync(Collection<? extends V> c) {
return RedissonSetMultimap.this.putAllAsync(key, c);
}
@Override
public RFuture<Boolean> removeAsync(Object value) {
return RedissonSetMultimap.this.removeAsync(key, value);
}
@Override
public RFuture<Boolean> removeAllAsync(Collection<?> c) {
if (c.isEmpty()) {
return new CompletableFutureWrapper<>(false);
}
List<Object> args = new ArrayList<Object>(c.size() + 1);
args.add(encodeMapKey(key));
encode(args, c);
return commandExecutor.evalWriteAsync(RedissonSetMultimap.this.getRawName(), codec, RedisCommands.EVAL_BOOLEAN_AMOUNT,
"local count = 0;" +
"for i=2, #ARGV, 5000 do " +
"count = count + redis.call('srem', KEYS[2], unpack(ARGV, i, math.min(i+4999, table.getn(ARGV)))) " +
"end; " +
"if count > 0 then " +
"if redis.call('scard', KEYS[2]) == 0 then " +
"redis.call('hdel', KEYS[1], ARGV[1]); " +
"end; " +
"return 1;" +
"end;" +
"return 0; ",
Arrays.<Object>asList(RedissonSetMultimap.this.getRawName(), setName),
args.toArray());
}
@Override
public RFuture<Boolean> deleteAsync() {
ByteBuf keyState = encodeMapKey(key);
return RedissonSetMultimap.this.fastRemoveAsync(Arrays.asList(keyState),
Arrays.asList(RedissonSetMultimap.this.getRawName(), setName), RedisCommands.EVAL_BOOLEAN_AMOUNT);
}
@Override
public RFuture<Boolean> clearExpireAsync() {
throw new UnsupportedOperationException("This operation is not supported for SetMultimap values Set");
}
@Override
public RFuture<Boolean> expireAsync(long timeToLive, TimeUnit timeUnit, String param, String... keys) {
throw new UnsupportedOperationException("This operation is not supported for SetMultimap values Set");
}
@Override
protected RFuture<Boolean> expireAtAsync(long timestamp, String param, String... keys) {
throw new UnsupportedOperationException("This operation is not supported for SetMultimap values Set");
}
@Override
public RFuture<Long> remainTimeToLiveAsync() {
throw new UnsupportedOperationException("This operation is not supported for SetMultimap values Set");
}
@Override
public RFuture<Void> renameAsync(String newName) {
throw new UnsupportedOperationException("This operation is not supported for SetMultimap values Set");
}
@Override
public RFuture<Boolean> renamenxAsync(String newName) {
throw new UnsupportedOperationException("This operation is not supported for SetMultimap values Set");
}
};
}
|
@Test
public void testDelete() {
RSetMultimap<String, String> map = redisson.getSetMultimap("simple");
map.put("1", "2");
map.put("2", "3");
assertThat(map.delete()).isTrue();
RSetMultimap<String, String> map2 = redisson.getSetMultimap("simple1");
assertThat(map2.delete()).isFalse();
RSetMultimap<String, String> multiset = redisson.getSetMultimap( "test" );
multiset.put("1", "01");
multiset.put("1", "02");
multiset.put("1", "03");
RSet<String> set = multiset.get( "1" );
set.delete();
assertThat(multiset.size()).isZero();
assertThat(multiset.get("1").size()).isZero();
}
|
public EnumSet<RepositoryFilePermission> processCheckboxes() {
return processCheckboxes( false );
}
|
@Test
public void testProcessCheckboxesWriteCheckedEnableAppropriateFalse() {
when( readCheckbox.isChecked() ).thenReturn( false );
when( writeCheckbox.isChecked() ).thenReturn( true );
when( deleteCheckbox.isChecked() ).thenReturn( false );
when( manageCheckbox.isChecked() ).thenReturn( false );
assertEquals( EnumSet.of( RepositoryFilePermission.READ, RepositoryFilePermission.WRITE ),
permissionsCheckboxHandler.processCheckboxes() );
verify( readCheckbox, times( 1 ) ).setDisabled( true );
verify( writeCheckbox, times( 1 ) ).setDisabled( true );
verify( deleteCheckbox, times( 1 ) ).setDisabled( true );
verify( manageCheckbox, times( 1 ) ).setDisabled( true );
}
|
@RequiresApi(api = Build.VERSION_CODES.O)
private static void createNormalChannel(Context context) {
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager.getNotificationChannel(CHANNEL_NORMAL_ID) == null) {
NotificationChannel mChannel =
new NotificationChannel(
CHANNEL_NORMAL_ID,
context.getString(R.string.channel_name_normal),
NotificationManager.IMPORTANCE_MIN);
// Configure the notification channel.
mChannel.setDescription(context.getString(R.string.channel_description_normal));
mNotificationManager.createNotificationChannel(mChannel);
}
}
|
@Test
@Config(sdk = {P}) // min sdk is O
public void testCreateNormalChannel() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_NORMAL_ID);
NotificationConstants.setMetadata(context, builder, TYPE_NORMAL);
List<Object> channels = shadowNotificationManager.getNotificationChannels();
assertNotNull(channels);
assertEquals(1, channels.size());
NotificationChannel channel = (NotificationChannel) channels.get(0);
assertEquals(IMPORTANCE_MIN, channel.getImportance());
assertEquals(CHANNEL_NORMAL_ID, channel.getId());
assertEquals(context.getString(R.string.channel_name_normal), channel.getName());
assertEquals(context.getString(R.string.channel_description_normal), channel.getDescription());
}
|
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScenario);
}
afterFeature();
}
}
|
@Test
void testTypeConversion() {
run("type-conversion.feature");
}
|
void visit(final PathItem.HttpMethod method, final Operation operation, final PathItem pathItem) {
if (filter.accept(operation.getOperationId())) {
final String methodName = method.name().toLowerCase();
emitter.emit(methodName, path);
emit("id", operation.getOperationId());
emit("description", operation.getDescription());
Set<String> operationLevelConsumes = new LinkedHashSet<>();
if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
operationLevelConsumes.addAll(operation.getRequestBody().getContent().keySet());
}
emit("consumes", operationLevelConsumes);
Set<String> operationLevelProduces = new LinkedHashSet<>();
if (operation.getResponses() != null) {
for (ApiResponse response : operation.getResponses().values()) {
if (response.getContent() != null) {
operationLevelProduces.addAll(response.getContent().keySet());
}
}
ApiResponse response = operation.getResponses().get(ApiResponses.DEFAULT);
if (response != null && response.getContent() != null) {
operationLevelProduces.addAll(response.getContent().keySet());
}
}
emit("produces", operationLevelProduces);
if (ObjectHelper.isNotEmpty(operation.getParameters())) {
operation.getParameters().forEach(this::emit);
}
if (ObjectHelper.isNotEmpty(pathItem.getParameters())) {
pathItem.getParameters().forEach(this::emit);
}
emitOperation(operation);
emitter.emit("to", destinationGenerator.generateDestinationFor(operation));
}
}
|
@Test
public void testDestinationToSyntax() {
final Builder method = MethodSpec.methodBuilder("configure");
final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method);
final OperationVisitor<?> visitor
= new OperationVisitor<>(
emitter, new OperationFilter(), "/path/{param}",
new DefaultDestinationGenerator("seda:${operationId}"), null);
final Paths paths = new Paths();
final PathItem pathItem = new PathItem();
paths.addPathItem("/path/{param}", pathItem);
final Operation operation = new Operation();
operation.setOperationId("my-operation");
final Parameter parameter = new Parameter();
parameter.setName("param");
parameter.setIn("path");
pathItem.addParametersItem(parameter);
visitor.visit(PathItem.HttpMethod.GET, operation, pathItem);
assertThat(method.build().toString()).isEqualTo("void configure() {\n"
+ " get(\"/path/{param}\")\n"
+ " .id(\"my-operation\")\n"
+ " .param()\n"
+ " .name(\"param\")\n"
+ " .type(org.apache.camel.model.rest.RestParamType.path)\n"
+ " .required(true)\n"
+ " .endParam()\n"
+ " .to(\"seda:my-operation\")\n"
+ " }\n");
}
|
@Override
public RefreshNodesResponse refreshNodes(RefreshNodesRequest request)
throws StandbyException, YarnException, IOException {
// parameter verification.
// We will not check whether the DecommissionType is empty,
// because this parameter has a default value at the proto level.
if (request == null) {
routerMetrics.incrRefreshNodesFailedRetrieved();
RouterServerUtil.logAndThrowException("Missing RefreshNodes request.", null);
}
// call refreshNodes of activeSubClusters.
try {
long startTime = clock.getTime();
RMAdminProtocolMethod remoteMethod = new RMAdminProtocolMethod(
new Class[] {RefreshNodesRequest.class}, new Object[] {request});
String subClusterId = request.getSubClusterId();
Collection<RefreshNodesResponse> refreshNodesResps =
remoteMethod.invokeConcurrent(this, RefreshNodesResponse.class, subClusterId);
if (CollectionUtils.isNotEmpty(refreshNodesResps)) {
long stopTime = clock.getTime();
routerMetrics.succeededRefreshNodesRetrieved(stopTime - startTime);
return RefreshNodesResponse.newInstance();
}
} catch (YarnException e) {
routerMetrics.incrRefreshNodesFailedRetrieved();
RouterServerUtil.logAndThrowException(e,
"Unable to refreshNodes due to exception. " + e.getMessage());
}
routerMetrics.incrRefreshNodesFailedRetrieved();
throw new YarnException("Unable to refreshNodes due to exception.");
}
|
@Test
public void testRefreshNodes() throws Exception {
// We will test 2 cases:
// case 1, request is null.
// case 2, normal request.
// If the request is null, a Missing RefreshNodes request exception will be thrown.
// null request.
LambdaTestUtils.intercept(YarnException.class,
"Missing RefreshNodes request.", () -> interceptor.refreshNodes(null));
// normal request.
RefreshNodesRequest request = RefreshNodesRequest.newInstance(DecommissionType.NORMAL);
interceptor.refreshNodes(request);
}
|
public static int booleanToValue(Boolean booleanValue) {
if (booleanValue) {
return TRUE;
} else {
return FALSE;
}
}
|
@Test
public void testBooleanToValue() {
assertTrue(BooleanUtils.valueToBoolean(1));
assertFalse(BooleanUtils.valueToBoolean(0));
}
|
@Override
public boolean isOldValueAvailable() {
return hasOldValue;
}
|
@Test
public void isOldValueAvailable() {
assertThat(event.isOldValueAvailable()).isTrue();
}
|
@SuppressWarnings("unchecked")
public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) {
final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported schema type: " + schema.type());
}
return (S) handler.apply(visitor, schema);
}
|
@Test
public void shouldThrowByDefaultFromNonStructured() {
// Given:
visitor = new Visitor<String, Integer>() {
};
nonStructuredSchemas().forEach(schema -> {
try {
// When:
SchemaWalker.visit(schema, visitor);
fail();
} catch (final UnsupportedOperationException e) {
// Then:
assertThat(e.getMessage(), is("Unsupported schema type: " + schema));
}
});
}
|
static Builder newBuilder() {
return new AutoValue_SplunkEventWriter.Builder();
}
|
@Test
public void eventWriterMissingURLProtocol() {
Exception thrown =
assertThrows(
IllegalArgumentException.class,
() -> SplunkEventWriter.newBuilder().withUrl("test-url").build());
assertTrue(thrown.getMessage().contains(SplunkEventWriter.INVALID_URL_FORMAT_MESSAGE));
}
|
@Override
public void close()
{
httpClient.dispatcher().executorService().shutdown();
httpClient.connectionPool().evictAll();
}
|
@Test
public void testConnectionResourceHandling()
throws Exception
{
List<Connection> connections = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Connection connection = createConnection();
connections.add(connection);
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT 123")) {
assertTrue(rs.next());
}
}
for (Connection connection : connections) {
connection.close();
}
}
|
public Optional<User> login(String nameOrEmail, String password) {
if (nameOrEmail == null || password == null) {
return Optional.empty();
}
User user = userDAO.findByName(nameOrEmail);
if (user == null) {
user = userDAO.findByEmail(nameOrEmail);
}
if (user != null && !user.isDisabled()) {
boolean authenticated = encryptionService.authenticate(password, user.getPassword(), user.getSalt());
if (authenticated) {
performPostLoginActivities(user);
return Optional.of(user);
}
}
return Optional.empty();
}
|
@Test
void callingLoginShouldLookupUserByName() {
userService.login("test", "password");
Mockito.verify(userDAO).findByName("test");
}
|
@Override
public RangeBoundary getLowBoundary() {
return lowBoundary;
}
|
@Test
void getLowBoundary() {
final Range.RangeBoundary lowBoundary = Range.RangeBoundary.CLOSED;
final RangeImpl rangeImpl = new RangeImpl(lowBoundary, 10, 15, Range.RangeBoundary.OPEN);
assertThat(rangeImpl.getLowBoundary()).isEqualTo(lowBoundary);
}
|
@Override
public Iterable<T> get() {
return values;
}
|
@Test
public void testGet() throws Exception {
FakeBeamFnStateClient fakeBeamFnStateClient =
new FakeBeamFnStateClient(
StringUtf8Coder.of(),
ImmutableMap.of(key(), asList("A1", "A2", "A3", "A4", "A5", "A6")));
IterableSideInput<String> iterableSideInput =
new IterableSideInput<>(
Caches.noop(), fakeBeamFnStateClient, "instructionId", key(), StringUtf8Coder.of());
assertArrayEquals(
new String[] {"A1", "A2", "A3", "A4", "A5", "A6"},
Iterables.toArray(iterableSideInput.get(), String.class));
}
|
public EndpointResponse streamQuery(
final KsqlSecurityContext securityContext,
final KsqlRequest request,
final CompletableFuture<Void> connectionClosedFuture,
final Optional<Boolean> isInternalRequest,
final MetricsCallbackHolder metricsCallbackHolder,
final Context context
) {
throwIfNotConfigured();
activenessRegistrar.updateLastRequestTime();
final PreparedStatement<?> statement = parseStatement(request);
CommandStoreUtil.httpWaitForCommandSequenceNumber(
commandQueue, request, commandQueueCatchupTimeout);
return handleStatement(securityContext, request, statement, connectionClosedFuture,
isInternalRequest, metricsCallbackHolder, context);
}
|
@Test
public void shouldReturn400OnBadStatement() {
// Given:
when(mockStatementParser.parseSingleStatement(any()))
.thenThrow(new IllegalArgumentException("some error message"));
// When:
final KsqlRestException e = assertThrows(
KsqlRestException.class,
() -> testResource.streamQuery(
securityContext,
new KsqlRequest("query", Collections.emptyMap(), Collections.emptyMap(), null),
new CompletableFuture<>(),
Optional.empty(),
new MetricsCallbackHolder(),
context
)
);
// Then:
assertThat(e, exceptionStatusCode(is(BAD_REQUEST.code())));
assertThat(e, exceptionErrorMessage(errorMessage(is("some error message"))));
assertThat(e, exceptionErrorMessage(errorCode(is(ERROR_CODE_BAD_STATEMENT))));
}
|
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
return command(getMigrationsDir(getConfigFile(), config));
}
|
@Test
public void shouldFailOnEmptyDescription() {
// Given:
command = PARSER.parse("");
// When:
final int result = command.command(migrationsDir);
// Then:
assertThat(result, is(1));
}
|
@Override
public long getStatusTimestamp(JobStatus status) {
return stateTimestamps[status.ordinal()];
}
|
@Test
void getStatusTimestamp() {
final JobStatusStore store = new JobStatusStore(0L);
store.jobStatusChanges(new JobID(), JobStatus.RUNNING, 1L);
assertThat(store.getStatusTimestamp(JobStatus.RUNNING), is(1L));
}
|
public static void apply(LoggingConfiguration conf, File logbackFile) {
Logback.configure(logbackFile, conf.getSubstitutionVariables());
if (conf.getLogOutput() != null) {
setCustomRootAppender(conf);
}
}
|
@Test
public void testNoListener() throws UnsupportedEncodingException {
System.setOut(new PrintStream(out, false, StandardCharsets.UTF_8.name()));
LoggingConfigurator.apply(conf);
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.info("info");
assertThat(out.toString(StandardCharsets.UTF_8)).contains("info");
}
|
List<GcpAddress> getAddresses() {
try {
return RetryUtils.retry(this::fetchGcpAddresses, RETRIES, NON_RETRYABLE_KEYWORDS);
} catch (RestClientException e) {
handleKnownException(e);
return emptyList();
}
}
|
@Test
public void getAddressesUnauthorized() {
// given
Label label = null;
String forbiddenMessage = "\"reason\":\"Request had insufficient authentication scopes\"";
RestClientException exception = new RestClientException(forbiddenMessage, HttpURLConnection.HTTP_UNAUTHORIZED);
given(gcpComputeApi.instances(CURRENT_PROJECT, CURRENT_ZONE, label, ACCESS_TOKEN)).willThrow(exception);
GcpConfig gcpConfig = GcpConfig.builder().setLabel(label).build();
GcpClient gcpClient = new GcpClient(gcpMetadataApi, gcpComputeApi, gcpAuthenticator, gcpConfig);
// when
List<GcpAddress> result = gcpClient.getAddresses();
// then
assertEquals(emptyList(), result);
}
|
void removeBuiltinRole(final String roleName) {
final Bson roleFindingFilter = Filters.eq(RoleServiceImpl.NAME_LOWER, roleName.toLowerCase(Locale.ENGLISH));
final MongoDatabase mongoDatabase = mongoConnection.getMongoDatabase();
final MongoCollection<Document> rolesCollection = mongoDatabase.getCollection(RoleServiceImpl.ROLES_COLLECTION_NAME);
final Document role = rolesCollection.find(roleFindingFilter)
.projection(include("_id"))
.first();
if (role != null) {
final ObjectId roleToBeRemovedId = role.getObjectId("_id");
final MongoCollection<Document> usersCollection = mongoDatabase.getCollection(UserImpl.COLLECTION_NAME);
final UpdateResult updateResult = usersCollection.updateMany(Filters.empty(), Updates.pull(UserImpl.ROLES, roleToBeRemovedId));
if (updateResult.getModifiedCount() > 0) {
LOG.info(StringUtils.f("Removed role %s from %d users", roleName, updateResult.getModifiedCount()));
}
final DeleteResult deleteResult = rolesCollection.deleteOne(roleFindingFilter);
if (deleteResult.getDeletedCount() > 0) {
LOG.info(StringUtils.f("Removed role %s ", roleName));
} else {
LOG.warn(StringUtils.f("Failed to remove role %s migration!", roleName));
}
}
}
|
@Test
public void testAttemptToRemoveNonExistingRoleDoesNotHaveEffectOnExistingUsersAndRoles() {
final Document adminUserBefore = usersCollection.find(Filters.eq(UserImpl.USERNAME, TEST_ADMIN_USER_WITH_BOTH_ROLES)).first();
final Document testUserBefore = usersCollection.find(Filters.eq(UserImpl.USERNAME, TEST_USER_WITH_FTM_MANAGER_ROLE_ONLY)).first();
toTest.removeBuiltinRole("Bayobongo!");
//both roles remain in DB
assertEquals(2, rolesCollection.countDocuments());
//both users are unchanged
final Document adminUser = usersCollection.find(Filters.eq(UserImpl.USERNAME, TEST_ADMIN_USER_WITH_BOTH_ROLES)).first();
final Document testUser = usersCollection.find(Filters.eq(UserImpl.USERNAME, TEST_USER_WITH_FTM_MANAGER_ROLE_ONLY)).first();
assertEquals(adminUserBefore, adminUser);
assertEquals(testUserBefore, testUser);
}
|
public static CompletableFuture<Void> runAfterwards(
CompletableFuture<?> future, RunnableWithException runnable) {
return runAfterwardsAsync(future, runnable, Executors.directExecutor());
}
|
@Test
void testRunAfterwardsExceptional() {
final CompletableFuture<Void> inputFuture = new CompletableFuture<>();
final OneShotLatch runnableLatch = new OneShotLatch();
final FlinkException testException = new FlinkException("Test exception");
final CompletableFuture<Void> runFuture =
FutureUtils.runAfterwards(inputFuture, runnableLatch::trigger);
assertThat(runnableLatch.isTriggered()).isFalse();
assertThat(runFuture).isNotDone();
inputFuture.completeExceptionally(testException);
assertThat(runnableLatch.isTriggered()).isTrue();
assertThat(runFuture).isDone();
assertThatFuture(runFuture)
.eventuallyFailsWith(ExecutionException.class)
.withCause(testException);
}
|
public synchronized boolean maybeUpdateGetRequestTimestamp(long currentTime) {
long lastRequestTimestamp = Math.max(lastGetRequestTimestamp, lastPushRequestTimestamp);
long timeElapsedSinceLastMsg = currentTime - lastRequestTimestamp;
if (timeElapsedSinceLastMsg >= pushIntervalMs) {
lastGetRequestTimestamp = currentTime;
return true;
}
return false;
}
|
@Test
public void testMaybeUpdateGetRequestWithImmediateRetryFail() {
assertTrue(clientInstance.maybeUpdateGetRequestTimestamp(System.currentTimeMillis()));
// Second request should be rejected as time since last request is less than the push interval.
assertFalse(clientInstance.maybeUpdateGetRequestTimestamp(System.currentTimeMillis()));
}
|
@Override
public boolean next() throws SQLException {
return proxyBackendHandler.next();
}
|
@Test
void assertNext() throws SQLException {
when(proxyBackendHandler.next()).thenReturn(true, false);
assertTrue(queryExecutor.next());
assertFalse(queryExecutor.next());
}
|
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// has the class loaded already?
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass == null) {
try {
// find the class from given jar urls as in first constructor parameter.
loadedClass = findClass(name);
} catch (ClassNotFoundException ignored) {
// ignore class not found
}
if (loadedClass == null) {
loadedClass = getParent().loadClass(name);
}
if (loadedClass == null) {
throw new ClassNotFoundException("Could not find class " + name + " in classloader nor in parent classloader");
}
}
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
|
@Test
public void canLoadClassFromIntermediate() throws Exception {
URL jarUrl = resourceJarUrl("deployment/sample-pojo-1.0-car.jar");
intermediateCl = new URLClassLoader(new URL[]{jarUrl}, ClassLoader.getSystemClassLoader());
cl = new ChildFirstClassLoader(new URL[]{emptyJarUrl},
intermediateCl);
String className = "com.sample.pojo.car.Car";
Class<?> clazz = cl.loadClass(className);
assertThat(clazz).isNotNull();
assertThat(clazz.getName()).isEqualTo(className);
assertThat(clazz.getClassLoader()).isEqualTo(intermediateCl);
}
|
@Override
public void doRun() {
final Instant mustBeOlderThan = Instant.now().minus(maximumSearchAge);
searchDbService.getExpiredSearches(findReferencedSearchIds(),
mustBeOlderThan).forEach(searchDbService::delete);
}
|
@Test
public void testForEmptyViews() {
when(viewService.streamAll()).thenReturn(Stream.empty());
final SearchSummary search = SearchSummary.builder()
.id("This search is expired and should be deleted")
.createdAt(DateTime.now(DateTimeZone.UTC).minus(Duration.standardDays(30)))
.build();
when(searchDbService.findSummaries()).thenReturn(Stream.of(search));
when(searchDbService.getExpiredSearches(any(), any())).thenCallRealMethod();
this.searchesCleanUpJob.doRun();
final ArgumentCaptor<String> deletedSearchId = ArgumentCaptor.forClass(String.class);
verify(searchDbService, times(1)).delete(deletedSearchId.capture());
assertThat(deletedSearchId.getValue()).isEqualTo("This search is expired and should be deleted");
}
|
@GET
@Path("{path:.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8})
public Response get(@PathParam("path") String path,
@Context UriInfo uriInfo,
@QueryParam(OperationParam.NAME) OperationParam op,
@Context Parameters params,
@Context HttpServletRequest request)
throws IOException, FileSystemAccessException {
// Restrict access to only GETFILESTATUS and LISTSTATUS in write-only mode
if((op.value() != HttpFSFileSystem.Operation.GETFILESTATUS) &&
(op.value() != HttpFSFileSystem.Operation.LISTSTATUS) &&
accessMode == AccessMode.WRITEONLY) {
return Response.status(Response.Status.FORBIDDEN).build();
}
UserGroupInformation user = HttpUserGroupInformation.get();
Response response;
path = makeAbsolute(path);
MDC.put(HttpFSFileSystem.OP_PARAM, op.value().name());
MDC.put("hostname", request.getRemoteAddr());
switch (op.value()) {
case OPEN: {
Boolean noRedirect = params.get(
NoRedirectParam.NAME, NoRedirectParam.class);
if (noRedirect) {
URI redirectURL = createOpenRedirectionURL(uriInfo);
final String js = JsonUtil.toJsonString("Location", redirectURL);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
} else {
//Invoking the command directly using an unmanaged FileSystem that is
// released by the FileSystemReleaseFilter
final FSOperations.FSOpen command = new FSOperations.FSOpen(path);
final FileSystem fs = createFileSystem(user);
InputStream is = null;
UserGroupInformation ugi = UserGroupInformation
.createProxyUser(user.getShortUserName(),
UserGroupInformation.getLoginUser());
try {
is = ugi.doAs(new PrivilegedExceptionAction<InputStream>() {
@Override
public InputStream run() throws Exception {
return command.execute(fs);
}
});
} catch (InterruptedException ie) {
LOG.warn("Open interrupted.", ie);
Thread.currentThread().interrupt();
}
Long offset = params.get(OffsetParam.NAME, OffsetParam.class);
Long len = params.get(LenParam.NAME, LenParam.class);
AUDIT_LOG.info("[{}] offset [{}] len [{}]",
new Object[] { path, offset, len });
InputStreamEntity entity = new InputStreamEntity(is, offset, len);
response = Response.ok(entity).type(MediaType.APPLICATION_OCTET_STREAM)
.build();
}
break;
}
case GETFILESTATUS: {
FSOperations.FSFileStatus command = new FSOperations.FSFileStatus(path);
Map json = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case LISTSTATUS: {
String filter = params.get(FilterParam.NAME, FilterParam.class);
FSOperations.FSListStatus command =
new FSOperations.FSListStatus(path, filter);
Map json = fsExecute(user, command);
AUDIT_LOG.info("[{}] filter [{}]", path, (filter != null) ? filter : "-");
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETHOMEDIRECTORY: {
enforceRootPath(op.value(), path);
FSOperations.FSHomeDir command = new FSOperations.FSHomeDir();
JSONObject json = fsExecute(user, command);
AUDIT_LOG.info("Home Directory for [{}]", user);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case INSTRUMENTATION: {
enforceRootPath(op.value(), path);
Groups groups = HttpFSServerWebApp.get().get(Groups.class);
Set<String> userGroups = groups.getGroupsSet(user.getShortUserName());
if (!userGroups.contains(HttpFSServerWebApp.get().getAdminGroup())) {
throw new AccessControlException(
"User not in HttpFSServer admin group");
}
Instrumentation instrumentation =
HttpFSServerWebApp.get().get(Instrumentation.class);
Map snapshot = instrumentation.getSnapshot();
response = Response.ok(snapshot).build();
break;
}
case GETCONTENTSUMMARY: {
FSOperations.FSContentSummary command =
new FSOperations.FSContentSummary(path);
Map json = fsExecute(user, command);
AUDIT_LOG.info("Content summary for [{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETQUOTAUSAGE: {
FSOperations.FSQuotaUsage command =
new FSOperations.FSQuotaUsage(path);
Map json = fsExecute(user, command);
AUDIT_LOG.info("Quota Usage for [{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETFILECHECKSUM: {
FSOperations.FSFileChecksum command =
new FSOperations.FSFileChecksum(path);
Boolean noRedirect = params.get(
NoRedirectParam.NAME, NoRedirectParam.class);
AUDIT_LOG.info("[{}]", path);
if (noRedirect) {
URI redirectURL = createOpenRedirectionURL(uriInfo);
final String js = JsonUtil.toJsonString("Location", redirectURL);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
} else {
Map json = fsExecute(user, command);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
}
break;
}
case GETFILEBLOCKLOCATIONS: {
long offset = 0;
long len = Long.MAX_VALUE;
Long offsetParam = params.get(OffsetParam.NAME, OffsetParam.class);
Long lenParam = params.get(LenParam.NAME, LenParam.class);
AUDIT_LOG.info("[{}] offset [{}] len [{}]", path, offsetParam, lenParam);
if (offsetParam != null && offsetParam > 0) {
offset = offsetParam;
}
if (lenParam != null && lenParam > 0) {
len = lenParam;
}
FSOperations.FSFileBlockLocations command =
new FSOperations.FSFileBlockLocations(path, offset, len);
@SuppressWarnings("rawtypes")
Map locations = fsExecute(user, command);
final String json = JsonUtil.toJsonString("BlockLocations", locations);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETACLSTATUS: {
FSOperations.FSAclStatus command = new FSOperations.FSAclStatus(path);
Map json = fsExecute(user, command);
AUDIT_LOG.info("ACL status for [{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETXATTRS: {
List<String> xattrNames =
params.getValues(XAttrNameParam.NAME, XAttrNameParam.class);
XAttrCodec encoding =
params.get(XAttrEncodingParam.NAME, XAttrEncodingParam.class);
FSOperations.FSGetXAttrs command =
new FSOperations.FSGetXAttrs(path, xattrNames, encoding);
@SuppressWarnings("rawtypes") Map json = fsExecute(user, command);
AUDIT_LOG.info("XAttrs for [{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case LISTXATTRS: {
FSOperations.FSListXAttrs command = new FSOperations.FSListXAttrs(path);
@SuppressWarnings("rawtypes") Map json = fsExecute(user, command);
AUDIT_LOG.info("XAttr names for [{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case LISTSTATUS_BATCH: {
String startAfter = params.get(
HttpFSParametersProvider.StartAfterParam.NAME,
HttpFSParametersProvider.StartAfterParam.class);
byte[] token = HttpFSUtils.EMPTY_BYTES;
if (startAfter != null) {
token = startAfter.getBytes(StandardCharsets.UTF_8);
}
FSOperations.FSListStatusBatch command = new FSOperations
.FSListStatusBatch(path, token);
@SuppressWarnings("rawtypes") Map json = fsExecute(user, command);
AUDIT_LOG.info("[{}] token [{}]", path, token);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETTRASHROOT: {
FSOperations.FSTrashRoot command = new FSOperations.FSTrashRoot(path);
JSONObject json = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETALLSTORAGEPOLICY: {
FSOperations.FSGetAllStoragePolicies command =
new FSOperations.FSGetAllStoragePolicies();
JSONObject json = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSTORAGEPOLICY: {
FSOperations.FSGetStoragePolicy command =
new FSOperations.FSGetStoragePolicy(path);
JSONObject json = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSNAPSHOTDIFF: {
String oldSnapshotName = params.get(OldSnapshotNameParam.NAME,
OldSnapshotNameParam.class);
String snapshotName = params.get(SnapshotNameParam.NAME,
SnapshotNameParam.class);
FSOperations.FSGetSnapshotDiff command =
new FSOperations.FSGetSnapshotDiff(path, oldSnapshotName,
snapshotName);
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSNAPSHOTDIFFLISTING: {
String oldSnapshotName = params.get(OldSnapshotNameParam.NAME,
OldSnapshotNameParam.class);
String snapshotName = params.get(SnapshotNameParam.NAME,
SnapshotNameParam.class);
String snapshotDiffStartPath = params
.get(HttpFSParametersProvider.SnapshotDiffStartPathParam.NAME,
HttpFSParametersProvider.SnapshotDiffStartPathParam.class);
Integer snapshotDiffIndex = params.get(HttpFSParametersProvider.SnapshotDiffIndexParam.NAME,
HttpFSParametersProvider.SnapshotDiffIndexParam.class);
FSOperations.FSGetSnapshotDiffListing command =
new FSOperations.FSGetSnapshotDiffListing(path, oldSnapshotName,
snapshotName, snapshotDiffStartPath, snapshotDiffIndex);
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSNAPSHOTTABLEDIRECTORYLIST: {
FSOperations.FSGetSnapshottableDirListing command =
new FSOperations.FSGetSnapshottableDirListing();
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", "/");
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSNAPSHOTLIST: {
FSOperations.FSGetSnapshotListing command =
new FSOperations.FSGetSnapshotListing(path);
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", "/");
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSERVERDEFAULTS: {
FSOperations.FSGetServerDefaults command =
new FSOperations.FSGetServerDefaults();
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", "/");
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case CHECKACCESS: {
String mode = params.get(FsActionParam.NAME, FsActionParam.class);
FsActionParam fsparam = new FsActionParam(mode);
FSOperations.FSAccess command = new FSOperations.FSAccess(path,
FsAction.getFsAction(fsparam.value()));
fsExecute(user, command);
AUDIT_LOG.info("[{}]", "/");
response = Response.ok().build();
break;
}
case GETECPOLICY: {
FSOperations.FSGetErasureCodingPolicy command =
new FSOperations.FSGetErasureCodingPolicy(path);
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETECPOLICIES: {
FSOperations.FSGetErasureCodingPolicies command =
new FSOperations.FSGetErasureCodingPolicies();
String js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETECCODECS: {
FSOperations.FSGetErasureCodingCodecs command =
new FSOperations.FSGetErasureCodingCodecs();
Map json = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GET_BLOCK_LOCATIONS: {
long offset = 0;
long len = Long.MAX_VALUE;
Long offsetParam = params.get(OffsetParam.NAME, OffsetParam.class);
Long lenParam = params.get(LenParam.NAME, LenParam.class);
AUDIT_LOG.info("[{}] offset [{}] len [{}]", path, offsetParam, lenParam);
if (offsetParam != null && offsetParam > 0) {
offset = offsetParam;
}
if (lenParam != null && lenParam > 0) {
len = lenParam;
}
FSOperations.FSFileBlockLocationsLegacy command =
new FSOperations.FSFileBlockLocationsLegacy(path, offset, len);
@SuppressWarnings("rawtypes")
Map locations = fsExecute(user, command);
final String json = JsonUtil.toJsonString("LocatedBlocks", locations);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETFILELINKSTATUS: {
FSOperations.FSFileLinkStatus command =
new FSOperations.FSFileLinkStatus(path);
@SuppressWarnings("rawtypes") Map js = fsExecute(user, command);
AUDIT_LOG.info("[{}]", path);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETSTATUS: {
FSOperations.FSStatus command = new FSOperations.FSStatus(path);
@SuppressWarnings("rawtypes") Map js = fsExecute(user, command);
response = Response.ok(js).type(MediaType.APPLICATION_JSON).build();
break;
}
case GETTRASHROOTS: {
Boolean allUsers = params.get(AllUsersParam.NAME, AllUsersParam.class);
FSOperations.FSGetTrashRoots command = new FSOperations.FSGetTrashRoots(allUsers);
Map json = fsExecute(user, command);
AUDIT_LOG.info("allUsers [{}]", allUsers);
response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
break;
}
default: {
throw new IOException(
MessageFormat.format("Invalid HTTP GET operation [{0}]", op.value()));
}
}
return response;
}
|
@Test
@TestDir
@TestJetty
@TestHdfs
public void testGlobFilter() throws Exception {
createHttpFSServer(false, false);
long oldOpsListStatus =
metricsGetter.get("LISTSTATUS").call();
FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
fs.mkdirs(new Path("/tmp"));
fs.create(new Path("/tmp/foo.txt")).close();
String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
URL url = new URL(TestJettyHelper.getJettyURL(),
MessageFormat.format(
"/webhdfs/v1/tmp?user.name={0}&op=liststatus&filter=f*", user));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
reader.readLine();
reader.close();
Assert.assertEquals(1 + oldOpsListStatus,
(long) metricsGetter.get("LISTSTATUS").call());
}
|
public static synchronized void configure(DataflowWorkerLoggingOptions options) {
if (!initialized) {
throw new RuntimeException("configure() called before initialize()");
}
// For compatibility reason, we do not call SdkHarnessOptions.getConfiguredLoggerFromOptions
// to config the logging for legacy worker, instead replicate the config steps used for
// DataflowWorkerLoggingOptions for default log level and log level overrides.
SdkHarnessOptions harnessOptions = options.as(SdkHarnessOptions.class);
boolean usedDeprecated = false;
// default value for both DefaultSdkHarnessLogLevel and DefaultWorkerLogLevel are INFO
Level overrideLevel = getJulLevel(harnessOptions.getDefaultSdkHarnessLogLevel());
if (options.getDefaultWorkerLogLevel() != null && options.getDefaultWorkerLogLevel() != INFO) {
overrideLevel = getJulLevel(options.getDefaultWorkerLogLevel());
usedDeprecated = true;
}
LogManager.getLogManager().getLogger(ROOT_LOGGER_NAME).setLevel(overrideLevel);
if (options.getWorkerLogLevelOverrides() != null) {
for (Map.Entry<String, DataflowWorkerLoggingOptions.Level> loggerOverride :
options.getWorkerLogLevelOverrides().entrySet()) {
Logger logger = Logger.getLogger(loggerOverride.getKey());
logger.setLevel(getJulLevel(loggerOverride.getValue()));
configuredLoggers.add(logger);
}
usedDeprecated = true;
} else if (harnessOptions.getSdkHarnessLogLevelOverrides() != null) {
for (Map.Entry<String, SdkHarnessOptions.LogLevel> loggerOverride :
harnessOptions.getSdkHarnessLogLevelOverrides().entrySet()) {
Logger logger = Logger.getLogger(loggerOverride.getKey());
logger.setLevel(getJulLevel(loggerOverride.getValue()));
configuredLoggers.add(logger);
}
}
// If the options specify a level for messages logged to System.out/err, we need to reconfigure
// the corresponding stream adapter.
if (options.getWorkerSystemOutMessageLevel() != null) {
System.out.close();
System.setOut(
JulHandlerPrintStreamAdapterFactory.create(
loggingHandler,
SYSTEM_OUT_LOG_NAME,
getJulLevel(options.getWorkerSystemOutMessageLevel()),
Charset.defaultCharset()));
}
if (options.getWorkerSystemErrMessageLevel() != null) {
System.err.close();
System.setErr(
JulHandlerPrintStreamAdapterFactory.create(
loggingHandler,
SYSTEM_ERR_LOG_NAME,
getJulLevel(options.getWorkerSystemErrMessageLevel()),
Charset.defaultCharset()));
}
if (usedDeprecated) {
LOG.warn(
"Deprecated DataflowWorkerLoggingOptions are used for log level settings."
+ "Consider using options defined in SdkHarnessOptions for forward compatibility.");
}
}
|
@Test
public void testWithWorkerCustomLogLevels() {
DataflowWorkerLoggingOptions options =
PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class);
options.setWorkerLogLevelOverrides(
new WorkerLogLevelOverrides()
.addOverrideForName("A", DataflowWorkerLoggingOptions.Level.DEBUG)
.addOverrideForName("B", DataflowWorkerLoggingOptions.Level.ERROR));
DataflowWorkerLoggingInitializer.configure(options);
Logger aLogger = LogManager.getLogManager().getLogger("A");
assertEquals(0, aLogger.getHandlers().length);
assertEquals(Level.FINE, aLogger.getLevel());
assertTrue(aLogger.getUseParentHandlers());
Logger bLogger = LogManager.getLogManager().getLogger("B");
assertEquals(Level.SEVERE, bLogger.getLevel());
assertEquals(0, bLogger.getHandlers().length);
assertTrue(aLogger.getUseParentHandlers());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.