focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public Input<DefaultIssue> create(Component component) {
if (component.getType() == Component.Type.PROJECT) {
return new ProjectTrackerBaseLazyInput(dbClient, issuesLoader, component);
}
if (component.getType() == Component.Type.DIRECTORY) {
// Folders have no issues
return new EmptyTrackerBaseLazyInput(dbClient, component);
}
return new FileTrackerBaseLazyInput(dbClient, component, movedFilesRepository.getOriginalFile(component).orElse(null));
}
|
@Test
public void create_returns_Input_which_retrieves_issues_of_specified_file_component_when_it_has_no_original_file() {
underTest.create(FILE).getIssues();
verify(issuesLoader).loadOpenIssues(FILE_UUID);
}
|
@Override
public String digest(final Object plainValue) {
return null == plainValue ? null : DigestUtils.md5Hex(plainValue + salt);
}
|
@Test
void assertDigest() {
assertThat(digestAlgorithm.digest("test"), is("098f6bcd4621d373cade4e832627b4f6"));
}
|
@Override
public boolean supportsSubqueriesInComparisons() {
return false;
}
|
@Test
void assertSupportsSubqueriesInComparisons() {
assertFalse(metaData.supportsSubqueriesInComparisons());
}
|
public String toBasicHeader(){
return "Basic " + new String(Base64.getEncoder().encode((getUser() + ":" + getPass()).
getBytes(Charset.defaultCharset())), Charset.defaultCharset());
}
|
@Test
public void testToBasicHeader() {
Authorization basicAuthorization = new Authorization("http://example.com", "foo", "bar", null, "Test Realm",
Mechanism.BASIC);
assertThat(basicAuthorization.toBasicHeader(), CoreMatchers.is("Basic Zm9vOmJhcg=="));
}
|
static String indent(String item) {
// '([^']|'')*': Matches the escape sequence "'...'" where the content between "'"
// characters can contain anything except "'" unless its doubled ('').
//
// Then each match is checked. If it starts with "'", it's left unchanged
// (escaped sequence). Otherwise, it replaces newlines within the match with indent.
Pattern pattern = Pattern.compile("('([^']|'')*')|\\n");
Matcher matcher = pattern.matcher(item);
StringBuffer output = new StringBuffer();
while (matcher.find()) {
final String group = matcher.group();
if (group.startsWith("'")) {
matcher.appendReplacement(output, Matcher.quoteReplacement(group));
} else {
String replaced = group.replaceAll("\n", "\n" + OPERATION_INDENT);
matcher.appendReplacement(output, Matcher.quoteReplacement(replaced));
}
}
matcher.appendTail(output);
return "\n" + OPERATION_INDENT + output;
}
|
@Test
void testSimpleIndent() {
String sourceQuery = "SELECT * FROM source_t";
String s =
String.format(
"SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery));
assertThat(s)
.isEqualTo("SELECT * FROM (\n" + " SELECT * FROM source_t\n" + ") WHERE a > 5");
}
|
static void populateAllowCommentAttribute(ITemplateContext context, boolean allowComment) {
if (Contexts.isWebContext(context)) {
IWebContext webContext = Contexts.asWebContext(context);
webContext.getExchange()
.setAttributeValue(COMMENT_ENABLED_MODEL_ATTRIBUTE, allowComment);
}
}
|
@Test
void populateAllowCommentAttribute() {
WebEngineContext webContext = mock(WebEngineContext.class);
IWebExchange webExchange = mock(IWebExchange.class);
when(webContext.getExchange()).thenReturn(webExchange);
CommentEnabledVariableProcessor.populateAllowCommentAttribute(webContext, true);
verify(webExchange).setAttributeValue(
eq(CommentEnabledVariableProcessor.COMMENT_ENABLED_MODEL_ATTRIBUTE), eq(true));
CommentEnabledVariableProcessor.populateAllowCommentAttribute(webContext, false);
verify(webExchange).setAttributeValue(
eq(CommentEnabledVariableProcessor.COMMENT_ENABLED_MODEL_ATTRIBUTE), eq(false));
}
|
public static LocalDateTime formatLocalDateTimeFromTimestampBySystemTimezone(final Long timestamp) {
return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, OffsetDateTime.now().getOffset());
}
|
@Test
public void testFormatLocalDateTimeFromTimestampBySystemTimezone() {
LocalDateTime localDateTime1 = LocalDateTime.now();
LocalDateTime localDateTime2 = DateUtils.formatLocalDateTimeFromTimestampBySystemTimezone(ZonedDateTime.of(localDateTime1, ZoneId.systemDefault()).toInstant().toEpochMilli());
assertEquals(localDateTime1.getYear(), localDateTime2.getYear());
assertEquals(localDateTime1.getDayOfMonth(), localDateTime2.getDayOfMonth());
assertEquals(localDateTime1.getMonth(), localDateTime2.getMonth());
assertEquals(localDateTime1.getHour(), localDateTime2.getHour());
assertEquals(localDateTime1.getMinute(), localDateTime2.getMinute());
assertEquals(localDateTime1.getSecond(), localDateTime2.getSecond());
}
|
public static ByteBuf copyShort(int value) {
ByteBuf buf = buffer(2);
buf.writeShort(value);
return buf;
}
|
@Test
public void testWrapShortFromShortArray() {
ByteBuf buffer = copyShort(new short[]{1, 4});
assertEquals(4, buffer.capacity());
assertEquals(1, buffer.readShort());
assertEquals(4, buffer.readShort());
assertFalse(buffer.isReadable());
buffer.release();
buffer = copyShort((short[]) null);
assertEquals(0, buffer.capacity());
buffer.release();
buffer = copyShort(new short[] {});
assertEquals(0, buffer.capacity());
buffer.release();
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (StringUtil.isNotEmpty(msg)) {
sb.append(msg);
}
int tempCount = 0;
for (Map.Entry<String, Object> kv : kvs.entrySet()) {
tempCount++;
Object value = kv.getValue();
if (value != null) {
if (value instanceof String && StringUtil.isEmpty((String) value)) {
continue;
}
sb.append(kv.getKey() + "=").append(kv.getValue());
if (tempCount != kvs.size()) {
sb.append("||");
}
}
}
return sb.toString();
}
|
@Test
public void testToStringShouldHaveAnEmptyMessage() {
assertEquals(Strings.EMPTY, logMessage.toString());
}
|
public InputBuffer(BufferType type, int inputSize) throws IOException {
final int capacity = inputSize;
this.type = type;
if (capacity > 0) {
switch (type) {
case DIRECT_BUFFER:
this.byteBuffer = bufferPool.getBuffer(capacity);
this.byteBuffer.order(ByteOrder.BIG_ENDIAN);
break;
case HEAP_BUFFER:
this.byteBuffer = ByteBuffer.allocate(capacity);
this.byteBuffer.order(ByteOrder.BIG_ENDIAN);
break;
}
byteBuffer.position(0);
byteBuffer.limit(0);
}
}
|
@Test
public void testInputBuffer() throws IOException {
final int size = 100;
final InputBuffer input1 = new InputBuffer(BufferType.DIRECT_BUFFER, size);
assertThat(input1.getType()).isEqualTo(BufferType.DIRECT_BUFFER);
assertThat(input1.position()).isZero();
assertThat(input1.length()).isZero();
assertThat(input1.remaining()).isZero();
assertThat(input1.capacity()).isEqualTo(size);
final InputBuffer input2 = new InputBuffer(BufferType.HEAP_BUFFER, size);
assertThat(input2.getType()).isEqualTo(BufferType.HEAP_BUFFER);
assertThat(input2.position()).isZero();
assertThat(input2.length()).isZero();
assertThat(input2.remaining()).isZero();
assertThat(input2.capacity()).isEqualTo(size);
final InputBuffer input3 = new InputBuffer(new byte[size]);
assertThat(input3.getType()).isEqualTo(BufferType.HEAP_BUFFER);
assertThat(input3.position()).isZero();
assertThat(input3.length()).isZero();
assertThat(input3.remaining()).isZero();
assertThat(input3.capacity()).isEqualTo(size);
}
|
public static String createUniqID() {
char[] sb = new char[LEN * 2];
System.arraycopy(FIX_STRING, 0, sb, 0, FIX_STRING.length);
long current = System.currentTimeMillis();
if (current >= nextStartTime) {
setStartTime(current);
}
int diff = (int)(current - startTime);
if (diff < 0 && diff > -1000_000) {
// may cause by NTP
diff = 0;
}
int pos = FIX_STRING.length;
UtilAll.writeInt(sb, pos, diff);
pos += 8;
UtilAll.writeShort(sb, pos, COUNTER.getAndIncrement());
return new String(sb);
}
|
@Test
public void testGetCountFromID() {
String uniqID = MessageClientIDSetter.createUniqID();
String uniqID2 = MessageClientIDSetter.createUniqID();
String idHex = uniqID.substring(uniqID.length() - 4);
String idHex2 = uniqID2.substring(uniqID2.length() - 4);
int s1 = Integer.parseInt(idHex, 16);
int s2 = Integer.parseInt(idHex2, 16);
assertThat(s1 == s2 - 1).isTrue();
}
|
static URI cleanUrl(String originalUrl, String host) {
return URI.create(originalUrl.replaceFirst(host, ""));
}
|
@Test
void cleanUrl() throws IOException {
URI uri = RibbonClient.cleanUrl("http://myservice/questions/answer/123", "myservice");
assertThat(uri.toString()).isEqualTo("http:///questions/answer/123");
}
|
@Override
public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView,
String fileId, int count) throws ResourceExhaustedException {
if (workerClusterView.size() < count) {
throw new ResourceExhaustedException(String.format(
"Not enough workers in the cluster %d workers in the cluster but %d required",
workerClusterView.size(), count));
}
Set<WorkerIdentity> workerIdentities = workerClusterView.workerIds();
mHashProvider.refresh(workerIdentities);
List<WorkerIdentity> workers = mHashProvider.getMultiple(fileId, count);
if (workers.size() != count) {
throw new ResourceExhaustedException(String.format(
"Found %d workers from the hash ring but %d required", workers.size(), count));
}
ImmutableList.Builder<BlockWorkerInfo> builder = ImmutableList.builder();
for (WorkerIdentity worker : workers) {
Optional<WorkerInfo> optionalWorkerInfo = workerClusterView.getWorkerById(worker);
final WorkerInfo workerInfo;
if (optionalWorkerInfo.isPresent()) {
workerInfo = optionalWorkerInfo.get();
} else {
// the worker returned by the policy does not exist in the cluster view
// supplied by the client.
// this can happen when the membership changes and some callers fail to update
// to the latest worker cluster view.
// in this case, just skip this worker
LOG.debug("Inconsistency between caller's view of cluster and that of "
+ "the consistent hash policy's: worker {} selected by policy does not exist in "
+ "caller's view {}. Skipping this worker.",
worker, workerClusterView);
continue;
}
BlockWorkerInfo blockWorkerInfo = new BlockWorkerInfo(
worker, workerInfo.getAddress(), workerInfo.getCapacityBytes(),
workerInfo.getUsedBytes(), workerInfo.getState() == WorkerState.LIVE
);
builder.add(blockWorkerInfo);
}
List<BlockWorkerInfo> infos = builder.build();
return infos;
}
|
@Test
public void getOneWorker() throws Exception {
WorkerLocationPolicy policy = WorkerLocationPolicy.Factory.create(mConf);
assertTrue(policy instanceof KetamaHashPolicy);
// Prepare a worker list
WorkerClusterView workers = new WorkerClusterView(Arrays.asList(
new WorkerInfo()
.setIdentity(WorkerIdentityTestUtils.ofLegacyId(1))
.setAddress(new WorkerNetAddress()
.setHost("master1").setRpcPort(29998).setDataPort(29999).setWebPort(30000))
.setCapacityBytes(1024)
.setUsedBytes(0),
new WorkerInfo()
.setIdentity(WorkerIdentityTestUtils.ofLegacyId(2))
.setAddress(new WorkerNetAddress()
.setHost("master2").setRpcPort(29998).setDataPort(29999).setWebPort(30000))
.setCapacityBytes(1024)
.setUsedBytes(0)));
List<BlockWorkerInfo> assignedWorkers = policy.getPreferredWorkers(workers, "hdfs://a/b/c", 1);
assertEquals(1, assignedWorkers.size());
assertTrue(contains(workers, assignedWorkers.get(0)));
assertThrows(ResourceExhaustedException.class, () -> {
// Getting 1 out of no workers will result in an error
policy.getPreferredWorkers(new WorkerClusterView(ImmutableList.of()), "hdfs://a/b/c", 1);
});
}
|
@Override
public synchronized boolean tryReturnRecordAt(
boolean isAtSplitPoint, @Nullable ShufflePosition groupStart) {
if (lastGroupStart == null && !isAtSplitPoint) {
throw new IllegalStateException(
String.format("The first group [at %s] must be at a split point", groupStart.toString()));
}
if (this.startPosition != null && groupStart.compareTo(this.startPosition) < 0) {
throw new IllegalStateException(
String.format(
"Trying to return record at %s which is before the starting position at %s",
groupStart, this.startPosition));
}
int comparedToLast = (lastGroupStart == null) ? 1 : groupStart.compareTo(this.lastGroupStart);
if (comparedToLast < 0) {
throw new IllegalStateException(
String.format(
"Trying to return group at %s which is before the last-returned group at %s",
groupStart, this.lastGroupStart));
}
if (isAtSplitPoint) {
splitPointsSeen++;
if (comparedToLast == 0) {
throw new IllegalStateException(
String.format(
"Trying to return a group at a split point with same position as the "
+ "previous group: both at %s, last group was %s",
groupStart,
lastGroupWasAtSplitPoint ? "at a split point." : "not at a split point."));
}
if (stopPosition != null && groupStart.compareTo(stopPosition) >= 0) {
return false;
}
} else {
checkState(
comparedToLast == 0,
// This case is not a violation of general RangeTracker semantics, but it is
// contrary to how GroupingShuffleReader in particular works. Hitting it would
// mean it's behaving unexpectedly.
"Trying to return a group not at a split point, but with a different position "
+ "than the previous group: last group was %s at %s, current at %s",
lastGroupWasAtSplitPoint ? "a split point" : "a non-split point",
lastGroupStart,
groupStart);
}
this.lastGroupStart = groupStart;
this.lastGroupWasAtSplitPoint = isAtSplitPoint;
return true;
}
|
@Test
public void testFirstRecordNonSplitPoint() throws Exception {
GroupingShuffleRangeTracker tracker =
new GroupingShuffleRangeTracker(ofBytes(3, 0, 0), ofBytes(5, 0, 0));
expected.expect(IllegalStateException.class);
tracker.tryReturnRecordAt(false, ofBytes(3, 4, 5));
}
|
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) throws AccessDeniedException {
if(input.getOptionValues(action.name()).length == 2) {
final String path = input.getOptionValues(action.name())[1];
// This only applies to a shell where the glob is not already expanded into multiple arguments
if(StringUtils.containsAny(path, '*', '?')) {
final Local directory = LocalFactory.get(FilenameUtils.getFullPath(path));
if(directory.isDirectory()) {
final Set<TransferItem> items = new HashSet<TransferItem>();
for(Local file : directory.list(new NullFilter<String>() {
@Override
public boolean accept(final String file) {
return FilenameUtils.wildcardMatch(file, PathNormalizer.name(path));
}
})) {
items.add(new TransferItem(new Path(remote, file.getName(), EnumSet.of(Path.Type.file)), file));
}
return items;
}
}
}
return new SingleTransferItemFinder().find(input, action, remote);
}
|
@Test
public void testNoLocalInOptionsUploadFile() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "rackspace://cdn.cyberduck.ch/remote"});
final Set<TransferItem> found = new GlobTransferItemFinder().find(input, TerminalAction.upload, new Path("/cdn.cyberduck.ch/remote", EnumSet.of(Path.Type.file)));
assertTrue(found.isEmpty());
}
|
public List<KuduPredicate> convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
}
|
@Test
public void testEqDateTime() {
ConstantOperator value = ConstantOperator.createDatetime(LocalDateTime.of(2024, 1, 1, 0, 0));
ScalarOperator op = new BinaryPredicateOperator(BinaryType.EQ, F4, value);
List<KuduPredicate> result = CONVERTER.convert(op);
Assert.assertEquals(result.get(0).toString(), "`f4` = 2024-01-01T00:00:00.000000Z");
}
|
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) {
return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs));
}
|
@Test
public void testGroupingKeyTypeWithEvolvedIntoUnpartitionedSpecV2Table() {
TestTables.TestTable table =
TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V2_FORMAT_VERSION);
table.updateSpec().removeField("data").commit();
assertThat(table.specs()).hasSize(2);
StructType expectedType = StructType.of();
StructType actualType = Partitioning.groupingKeyType(table.schema(), table.specs().values());
assertThat(actualType).isEqualTo(expectedType);
}
|
public static void cleanDirectory(File directory) throws IOException {
requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL);
if (!directory.exists()) {
return;
}
cleanDirectoryImpl(directory.toPath());
}
|
@Test
public void cleanDirectory_follows_symlink_to_target_directory() throws IOException {
assumeTrue(SystemUtils.IS_OS_UNIX);
Path target = temporaryFolder.newFolder().toPath();
Path symToDir = Files.createSymbolicLink(temporaryFolder.newFolder().toPath().resolve("sym_to_dir"), target);
Path childFile1 = Files.createFile(target.resolve("file1.txt"));
Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
assertThat(target).isDirectory();
assertThat(symToDir).isSymbolicLink();
assertThat(childFile1).isRegularFile();
assertThat(childDir1).isDirectory();
assertThat(childFile2).isRegularFile();
assertThat(childDir2).isDirectory();
// on supporting FileSystem, target will change if directory is recreated
Object targetKey = getFileKey(target);
Object symLinkKey = getFileKey(symToDir);
FileUtils2.cleanDirectory(symToDir.toFile());
assertThat(target).isDirectory();
assertThat(symToDir).isSymbolicLink();
assertThat(childFile1).doesNotExist();
assertThat(childDir1).doesNotExist();
assertThat(childFile2).doesNotExist();
assertThat(childDir2).doesNotExist();
assertThat(getFileKey(target)).isEqualTo(targetKey);
assertThat(getFileKey(symToDir)).isEqualTo(symLinkKey);
}
|
private void ensureRoleNamesAnno(User user) {
roleService.getRolesByUsername(user.getMetadata().getName())
.collectList()
.map(JsonUtils::objectToJson)
.doOnNext(roleNamesJson -> {
var annotations = Optional.ofNullable(user.getMetadata().getAnnotations())
.orElseGet(HashMap::new);
user.getMetadata().setAnnotations(annotations);
annotations.put(User.ROLE_NAMES_ANNO, roleNamesJson);
})
.block(Duration.ofMinutes(1));
}
|
@Test
void ensureRoleNamesAnno() {
when(roleService.getRolesByUsername("fake-user")).thenReturn(Flux.just("fake-role"));
when(client.fetch(eq(User.class), eq("fake-user")))
.thenReturn(Optional.of(user("fake-user")));
when(externalUrlSupplier.get()).thenReturn(URI.create("/"));
userReconciler.reconcile(new Reconciler.Request("fake-user"));
verify(client).update(assertArg(user -> {
assertEquals("""
["fake-role"]\
""",
user.getMetadata().getAnnotations().get(User.ROLE_NAMES_ANNO));
}));
}
|
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) {
ServletRequest wsRequest = new ServletRequest(request);
ServletResponse wsResponse = new ServletResponse(response);
webServiceEngine.execute(wsRequest, wsResponse);
}
|
@Test
public void execute_ws() {
underTest = new WebServiceFilter(webServiceEngine);
underTest.doFilter(new JavaxHttpRequest(request), new JavaxHttpResponse(response), chain);
verify(webServiceEngine).execute(any(), any());
}
|
public static Date addTimeToDate( Date input, String time, String dateFormat ) throws Exception {
if ( Utils.isEmpty( time ) ) {
return input;
}
if ( input == null ) {
return null;
}
String dateformatString = NVL( dateFormat, "HH:mm:ss" );
int t = decodeTime( time, dateformatString );
return new Date( input.getTime() + t );
}
|
@Test
public void testAddTimeToDate() throws Exception {
final Date date = new Date( 1447252914241L );
assertNull( Const.addTimeToDate( null, null, null ) );
assertEquals( date, Const.addTimeToDate( date, null, null ) );
assertEquals( 1447256637241L, Const.addTimeToDate( date, "01:02:03", "HH:mm:ss" ).getTime() );
}
|
public static MetadataUpdate fromJson(String json) {
return JsonUtil.parse(json, MetadataUpdateParser::fromJson);
}
|
@Test
public void testAddViewVersionFromJson() {
String action = MetadataUpdateParser.ADD_VIEW_VERSION;
long timestamp = 123456789;
ViewVersion viewVersion =
ImmutableViewVersion.builder()
.versionId(23)
.timestampMillis(timestamp)
.schemaId(4)
.putSummary("user", "some-user")
.defaultNamespace(Namespace.of("ns"))
.build();
String json =
String.format(
"{\"action\":\"%s\",\"view-version\":{\"version-id\":23,\"timestamp-ms\":123456789,\"schema-id\":4,\"summary\":{\"user\":\"some-user\"},\"default-namespace\":[\"ns\"],\"representations\":[]}}",
action);
MetadataUpdate expected = new MetadataUpdate.AddViewVersion(viewVersion);
assertEquals(action, expected, MetadataUpdateParser.fromJson(json));
}
|
public static void checkProjectKey(String keyCandidate) {
checkArgument(isValidProjectKey(keyCandidate), MALFORMED_KEY_MESSAGE, keyCandidate, ALLOWED_CHARACTERS_MESSAGE);
}
|
@Test
public void checkProjectKey_fail_if_only_digit() {
assertThatThrownBy(() -> ComponentKeys.checkProjectKey("0123"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Malformed key for '0123'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
}
|
public boolean isAfter(VectorClock other) {
boolean anyTimestampGreater = false;
for (Entry<UUID, Long> otherEntry : other.replicaTimestamps.entrySet()) {
final UUID replicaId = otherEntry.getKey();
final Long otherReplicaTimestamp = otherEntry.getValue();
final Long localReplicaTimestamp = this.getTimestampForReplica(replicaId);
if (localReplicaTimestamp == null || localReplicaTimestamp < otherReplicaTimestamp) {
return false;
} else if (localReplicaTimestamp > otherReplicaTimestamp) {
anyTimestampGreater = true;
}
}
// there is at least one local timestamp greater or local vector clock has additional timestamps
return anyTimestampGreater || other.replicaTimestamps.size() < replicaTimestamps.size();
}
|
@Test
public void testIsAfter() {
assertFalse(vectorClock().isAfter(vectorClock()));
assertTrue(vectorClock(uuidParams[0], 1).isAfter(vectorClock()));
assertFalse(vectorClock(uuidParams[0], 1).isAfter(vectorClock(uuidParams[0], 1)));
assertFalse(vectorClock(uuidParams[0], 1).isAfter(vectorClock(uuidParams[1], 1)));
assertTrue(vectorClock(uuidParams[0], 1, uuidParams[1], 1).isAfter(vectorClock(uuidParams[0], 1)));
assertFalse(vectorClock(uuidParams[0], 1).isAfter(vectorClock(uuidParams[0], 1, uuidParams[1], 1)));
assertTrue(vectorClock(uuidParams[0], 2).isAfter(vectorClock(uuidParams[0], 1)));
assertFalse(vectorClock(uuidParams[0], 2).isAfter(vectorClock(uuidParams[0], 1, uuidParams[1], 1)));
assertTrue(vectorClock(uuidParams[0], 2, uuidParams[1], 1).isAfter(vectorClock(uuidParams[0], 1, uuidParams[1], 1)));
}
|
@Override
public List<TransferItem> list(final Session<?> session, final Path directory,
final Local local, final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("List children for %s", directory));
}
if(directory.isSymbolicLink()
&& new DownloadSymlinkResolver(roots).resolve(directory)) {
if(log.isDebugEnabled()) {
log.debug(String.format("Do not list children for symbolic link %s", directory));
}
return Collections.emptyList();
}
else {
final AttributedList<Path> list;
if(cache.isCached(directory)) {
list = cache.get(directory);
}
else {
list = session.getFeature(ListService.class).list(directory, listener);
cache.put(directory, list);
}
final List<TransferItem> children = new ArrayList<>();
// Return copy with filtered result only
for(Path f : new AttributedList<>(list.filter(comparator, filter))) {
children.add(new TransferItem(f, LocalFactory.get(local, f.getName())));
}
return children;
}
}
|
@Test
public void testDownloadDuplicateNameFolderAndFile() throws Exception {
final Path parent = new Path("t", EnumSet.of(Path.Type.directory));
final Transfer t = new DownloadTransfer(new Host(new TestProtocol()), parent, new NullLocal(System.getProperty("java.io.tmpdir")));
final NullSession session = new NullSession(new Host(new TestProtocol())) {
@Override
public AttributedList<Path> list(final Path file, final ListProgressListener listener) {
final AttributedList<Path> l = new AttributedList<>();
// File first in list
l.add(new Path("/f", EnumSet.of(Path.Type.file)));
l.add(new Path("/f", EnumSet.of(Path.Type.directory)));
return l;
}
};
final List<TransferItem> list = t.list(session, parent,
new NullLocal(System.getProperty("java.io.tmpdir")), new DisabledListProgressListener());
assertEquals(2, list.size());
// Make sure folder is first in list
assertEquals(new TransferItem(new Path("/f", EnumSet.of(Path.Type.directory)), new Local(System.getProperty("java.io.tmpdir"), "f")), list.get(0));
assertTrue(list.contains(new TransferItem(new Path("/f", EnumSet.of(Path.Type.file)), new Local(System.getProperty("java.io.tmpdir"), "f"))));
}
|
@Override
public Object get(int fieldNum) {
try {
StructField fref = soi.getAllStructFieldRefs().get(fieldNum);
return HCatRecordSerDe.serializeField(
soi.getStructFieldData(wrappedObject, fref),
fref.getFieldObjectInspector());
} catch (SerDeException e) {
throw new IllegalStateException("SerDe Exception deserializing",e);
}
}
|
@Test
public void testGetWithName() throws Exception {
TypeInfo ti = getTypeInfo();
HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector(ti));
HCatSchema schema = HCatSchemaUtils.getHCatSchema(ti)
.get(0).getStructSubSchema();
Assert.assertEquals(INT_CONST, ((Integer) r.get("an_int", schema)).intValue());
Assert.assertEquals(LONG_CONST, ((Long) r.get("a_long", schema)).longValue());
Assert.assertEquals(DOUBLE_CONST, ((Double) r.get("a_double", schema)).doubleValue(), 0);
Assert.assertEquals(STRING_CONST, r.get("a_string", schema));
}
|
@Override
public AppsInfo getApps(HttpServletRequest hsr, String stateQuery,
Set<String> statesQuery, String finalStatusQuery, String userQuery,
String queueQuery, String count, String startedBegin, String startedEnd,
String finishBegin, String finishEnd, Set<String> applicationTypes,
Set<String> applicationTags, String name, Set<String> unselectedFields) {
RouterAppInfoCacheKey routerAppInfoCacheKey = RouterAppInfoCacheKey.newInstance(
hsr, stateQuery, statesQuery, finalStatusQuery, userQuery, queueQuery, count,
startedBegin, startedEnd, finishBegin, finishEnd, applicationTypes,
applicationTags, name, unselectedFields);
if (appInfosCacheEnabled && routerAppInfoCacheKey != null) {
if (appInfosCaches.containsKey(routerAppInfoCacheKey)) {
return appInfosCaches.get(routerAppInfoCacheKey);
}
}
AppsInfo apps = new AppsInfo();
long startTime = clock.getTime();
// HttpServletRequest does not work with ExecutorCompletionService.
// Create a duplicate hsr.
final HttpServletRequest hsrCopy = clone(hsr);
Collection<SubClusterInfo> subClusterInfos = federationFacade.getActiveSubClusters();
List<AppsInfo> appsInfos = subClusterInfos.parallelStream().map(subCluster -> {
try {
DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorForSubCluster(subCluster);
AppsInfo rmApps = interceptor.getApps(hsrCopy, stateQuery, statesQuery, finalStatusQuery,
userQuery, queueQuery, count, startedBegin, startedEnd, finishBegin, finishEnd,
applicationTypes, applicationTags, name, unselectedFields);
if (rmApps != null) {
return rmApps;
}
} catch (Exception e) {
LOG.warn("Failed to get application report.", e);
}
routerMetrics.incrMultipleAppsFailedRetrieved();
LOG.error("Subcluster {} failed to return appReport.", subCluster.getSubClusterId());
return null;
}).collect(Collectors.toList());
appsInfos.forEach(appsInfo -> {
if (appsInfo != null) {
apps.addAll(appsInfo.getApps());
long stopTime = clock.getTime();
routerMetrics.succeededMultipleAppsRetrieved(stopTime - startTime);
}
});
if (apps.getApps().isEmpty()) {
return new AppsInfo();
}
// Merge all the application reports got from all the available YARN RMs
AppsInfo resultAppsInfo = RouterWebServiceUtil.mergeAppsInfo(
apps.getApps(), returnPartialReport);
if (appInfosCacheEnabled && routerAppInfoCacheKey != null) {
appInfosCaches.put(routerAppInfoCacheKey, resultAppsInfo);
}
return resultAppsInfo;
}
|
@Test
public void testGetApplicationsReport() {
AppsInfo responseGet = interceptor.getApps(null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null);
Assert.assertNotNull(responseGet);
Assert.assertEquals(NUM_SUBCLUSTER, responseGet.getApps().size());
// The merged operations is tested in TestRouterWebServiceUtil
}
|
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
}
|
@Test
public void issueIA74K2Test() {
UserAgent ua = UserAgentUtil.parse(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) MicroMessenger/6.8.0(0x16080000) MacWechat/3.8.7(0x13080710) Safari/605.1.15 NetType/WIFI");
assertEquals("MicroMessenger", ua.getBrowser().toString());
assertEquals("6.8.0", ua.getVersion());
assertEquals("Webkit", ua.getEngine().toString());
assertEquals("605.1.15", ua.getEngineVersion());
assertEquals("OSX", ua.getOs().toString());
assertEquals("10_15_7", ua.getOsVersion());
assertEquals("Mac", ua.getPlatform().toString());
assertFalse(ua.isMobile());
}
|
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances)
throws NacosException {
synchronized (redoService.getRegisteredInstances()) {
List<Instance> retainInstance = getRetainInstance(serviceName, groupName, instances);
batchRegisterService(serviceName, groupName, retainInstance);
}
}
|
@Test
void testBatchDeregisterServiceWithoutCacheData() throws NacosException {
assertThrows(NacosException.class, () -> {
List<Instance> instanceList = new ArrayList<>();
instance.setHealthy(true);
instanceList.add(instance);
client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList);
});
}
|
public String get(Component c) {
return get(Group.Alphabetic, c);
}
|
@Test
public void testSubsumeSurplusComponentInSuffix() {
PersonName pn = new PersonName("Adams^John Robert Quincy^^Rev.^B.A.^M.Div.", true);
assertEquals("Adams", pn.get(PersonName.Component.FamilyName));
assertEquals("John Robert Quincy", pn.get(PersonName.Component.GivenName));
assertEquals("Rev.", pn.get(PersonName.Component.NamePrefix));
assertEquals("B.A. M.Div.", pn.get(PersonName.Component.NameSuffix));
}
|
public PlainAccessConfig createAclAccessConfigMap(PlainAccessConfig existedAccountMap,
PlainAccessConfig plainAccessConfig) {
PlainAccessConfig newAccountsMap = null;
if (existedAccountMap == null) {
newAccountsMap = new PlainAccessConfig();
} else {
newAccountsMap = existedAccountMap;
}
if (StringUtils.isEmpty(plainAccessConfig.getAccessKey()) ||
plainAccessConfig.getAccessKey().length() <= AclConstants.ACCESS_KEY_MIN_LENGTH) {
throw new AclException(String.format(
"The accessKey=%s cannot be null and length should longer than 6",
plainAccessConfig.getAccessKey()));
}
newAccountsMap.setAccessKey(plainAccessConfig.getAccessKey());
if (!StringUtils.isEmpty(plainAccessConfig.getSecretKey())) {
if (plainAccessConfig.getSecretKey().length() <= AclConstants.SECRET_KEY_MIN_LENGTH) {
throw new AclException(String.format(
"The secretKey=%s value length should longer than 6",
plainAccessConfig.getSecretKey()));
}
newAccountsMap.setSecretKey(plainAccessConfig.getSecretKey());
}
if (plainAccessConfig.getWhiteRemoteAddress() != null) {
newAccountsMap.setWhiteRemoteAddress(plainAccessConfig.getWhiteRemoteAddress());
}
if (!StringUtils.isEmpty(String.valueOf(plainAccessConfig.isAdmin()))) {
newAccountsMap.setAdmin(plainAccessConfig.isAdmin());
}
if (!StringUtils.isEmpty(plainAccessConfig.getDefaultTopicPerm())) {
newAccountsMap.setDefaultTopicPerm(plainAccessConfig.getDefaultTopicPerm());
}
if (!StringUtils.isEmpty(plainAccessConfig.getDefaultGroupPerm())) {
newAccountsMap.setDefaultGroupPerm(plainAccessConfig.getDefaultGroupPerm());
}
if (plainAccessConfig.getTopicPerms() != null) {
newAccountsMap.setTopicPerms(plainAccessConfig.getTopicPerms());
}
if (plainAccessConfig.getGroupPerms() != null) {
newAccountsMap.setGroupPerms(plainAccessConfig.getGroupPerms());
}
return newAccountsMap;
}
|
@Test
public void createAclAccessConfigMapTest() {
PlainAccessConfig existedAccountMap = new PlainAccessConfig();
plainAccessConfig.setAccessKey("admin123");
plainAccessConfig.setSecretKey("12345678");
plainAccessConfig.setWhiteRemoteAddress("192.168.1.1");
plainAccessConfig.setAdmin(false);
plainAccessConfig.setDefaultGroupPerm(AclConstants.SUB_PUB);
plainAccessConfig.setTopicPerms(Arrays.asList(DEFAULT_TOPIC + "=" + AclConstants.PUB));
plainAccessConfig.setGroupPerms(Lists.newArrayList("groupA=SUB"));
final PlainAccessConfig map = plainPermissionManager.createAclAccessConfigMap(existedAccountMap, plainAccessConfig);
Assert.assertEquals(AclConstants.SUB_PUB, map.getDefaultGroupPerm());
Assert.assertEquals("groupA=SUB", map.getGroupPerms().get(0));
Assert.assertEquals("12345678", map.getSecretKey());
Assert.assertEquals("admin123", map.getAccessKey());
Assert.assertEquals("192.168.1.1", map.getWhiteRemoteAddress());
Assert.assertEquals("topic-acl=PUB", map.getTopicPerms().get(0));
Assert.assertEquals(false, map.isAdmin());
}
|
public static DLPDeidentifyText.Builder newBuilder() {
return new AutoValue_DLPDeidentifyText.Builder();
}
|
@Test
public void throwsExceptionWhenBatchSizeIsTooLarge() {
assertThrows(
String.format(
"Batch size is too large! It should be smaller or equal than %d.",
DLPDeidentifyText.DLP_PAYLOAD_LIMIT_BYTES),
IllegalArgumentException.class,
() ->
DLPDeidentifyText.newBuilder()
.setProjectId(PROJECT_ID)
.setBatchSizeBytes(Integer.MAX_VALUE)
.setDeidentifyTemplateName(TEMPLATE_NAME)
.setColumnDelimiter(DELIMITER)
.build());
}
|
@Nullable
@Override
public Message decode(@Nonnull final RawMessage rawMessage) {
final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
final String json = gelfMessage.getJSON(decompressSizeLimit, charset);
final JsonNode node;
try {
node = objectMapper.readTree(json);
if (node == null) {
throw new IOException("null result");
}
} catch (final Exception e) {
log.error("Could not parse JSON, first 400 characters: " +
StringUtils.abbreviate(json, 403), e);
throw new IllegalStateException("JSON is null/could not be parsed (invalid JSON)", e);
}
try {
validateGELFMessage(node, rawMessage.getId(), rawMessage.getRemoteAddress());
} catch (IllegalArgumentException e) {
log.trace("Invalid GELF message <{}>", node);
throw e;
}
// Timestamp.
final double messageTimestamp = timestampValue(node);
final DateTime timestamp;
if (messageTimestamp <= 0) {
timestamp = rawMessage.getTimestamp();
} else {
// we treat this as a unix timestamp
timestamp = Tools.dateTimeFromDouble(messageTimestamp);
}
final Message message = messageFactory.createMessage(
stringValue(node, "short_message"),
stringValue(node, "host"),
timestamp
);
message.addField(Message.FIELD_FULL_MESSAGE, stringValue(node, "full_message"));
final String file = stringValue(node, "file");
if (file != null && !file.isEmpty()) {
message.addField("file", file);
}
final long line = longValue(node, "line");
if (line > -1) {
message.addField("line", line);
}
// Level is set by server if not specified by client.
final int level = intValue(node, "level");
if (level > -1) {
message.addField("level", level);
}
// Facility is set by server if not specified by client.
final String facility = stringValue(node, "facility");
if (facility != null && !facility.isEmpty()) {
message.addField("facility", facility);
}
// Add additional data if there is some.
final Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
final Map.Entry<String, JsonNode> entry = fields.next();
String key = entry.getKey();
// Do not index useless GELF "version" field.
if ("version".equals(key)) {
continue;
}
// Don't include GELF syntax underscore in message field key.
if (key.startsWith("_") && key.length() > 1) {
key = key.substring(1);
}
// We already set short_message and host as message and source. Do not add as fields again.
if ("short_message".equals(key) || "host".equals(key)) {
continue;
}
// Skip standard or already set fields.
if (message.getField(key) != null || Message.RESERVED_FIELDS.contains(key) && !Message.RESERVED_SETTABLE_FIELDS.contains(key)) {
continue;
}
// Convert JSON containers to Strings, and pick a suitable number representation.
final JsonNode value = entry.getValue();
final Object fieldValue;
if (value.isContainerNode()) {
fieldValue = value.toString();
} else if (value.isFloatingPointNumber()) {
fieldValue = value.asDouble();
} else if (value.isIntegralNumber()) {
fieldValue = value.asLong();
} else if (value.isNull()) {
log.debug("Field [{}] is NULL. Skipping.", key);
continue;
} else if (value.isTextual()) {
fieldValue = value.asText();
} else {
log.debug("Field [{}] has unknown value type. Skipping.", key);
continue;
}
message.addField(key, fieldValue);
}
return message;
}
|
@Test
public void decodeFailsWithoutShortMessage() throws Exception {
final String json = "{"
+ "\"version\": \"1.1\","
+ "\"host\": \"example.org\""
+ "}";
final RawMessage rawMessage = new RawMessage(json.getBytes(StandardCharsets.UTF_8));
assertThatIllegalArgumentException().isThrownBy(() -> codec.decode(rawMessage))
.withNoCause()
.withMessageMatching("GELF message <[0-9a-f-]+> is missing mandatory \"short_message\" or \"message\" field.");
}
|
public Response request(Request request) throws NacosException {
return request(request, rpcClientConfig.timeOutMills());
}
|
@Test
void testRequestWhenResponseErrorThenThrowException() throws NacosException {
assertThrows(NacosException.class, () -> {
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
rpcClient.currentConnection = connection;
doReturn(new ErrorResponse()).when(connection).request(any(), anyLong());
rpcClient.request(null, 10000);
});
}
|
@Override
public RemoteData.Builder serialize() {
RemoteData.Builder remoteBuilder = RemoteData.newBuilder();
remoteBuilder.addDataObjectStrings(count.toStorageData());
remoteBuilder.addDataObjectStrings(summation.toStorageData());
remoteBuilder.addDataLongs(getTimeBucket());
remoteBuilder.addDataStrings(entityId);
remoteBuilder.addDataStrings(serviceId);
return remoteBuilder;
}
|
@Test
public void testSerialize() {
function.accept(
MeterEntity.newService("request_count", Layer.GENERAL), build(asList("200", "404"), asList(10L, 2L)));
AvgLabeledFunction function2 = Mockito.spy(AvgLabeledFunction.class);
function2.deserialize(function.serialize().build());
assertThat(function2.getEntityId()).isEqualTo(function.getEntityId());
assertThat(function2.getTimeBucket()).isEqualTo(function.getTimeBucket());
}
|
@Override
public Map<String, String> loadStreamTitles(Collection<String> streamIds) {
if (streamIds.isEmpty()) {
return Map.of();
}
final var streamObjectIds = streamIds.stream().map(ObjectId::new).toList();
final var cursor = collection(StreamImpl.class).find(
new BasicDBObject("_id", new BasicDBObject("$in", streamObjectIds)),
new BasicDBObject("_id", 1).append("title", 1)
);
try (cursor) {
return cursorToList(cursor).stream()
.collect(Collectors.toMap(i -> i.get("_id").toString(), i -> i.get("title").toString()));
}
}
|
@Test
@MongoDBFixtures("someStreamsWithAlertConditions.json")
public void loadStreamTitles() {
final var result = streamService.loadStreamTitles(Set.of("565f02223b0c25a537197af2", "559d14663b0cf26a15ee0f01"));
assertThat(result).hasSize(2);
assertThat(result.get("565f02223b0c25a537197af2")).isEqualTo("Logins");
assertThat(result.get("559d14663b0cf26a15ee0f01")).isEqualTo("footitle");
assertThat(streamService.loadStreamTitles(Set.of())).isEmpty();
// Invalid ObjectIds throw an error
assertThatThrownBy(() -> streamService.loadStreamTitles(Set.of("foo")))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> streamService.loadStreamTitles(Collections.singleton(null)))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> streamService.loadStreamTitles(Collections.singleton("")))
.isInstanceOf(IllegalArgumentException.class);
}
|
public Connection connection(Connection connection) {
// It is common to implement both interfaces
if (connection instanceof XAConnection) {
return xaConnection((XAConnection) connection);
}
return TracingConnection.create(connection, this);
}
|
@Test void connection_wrapsXaInput() {
abstract class Both implements XAConnection, Connection {
}
assertThat(jmsTracing.connection(mock(Both.class)))
.isInstanceOf(XAConnection.class);
}
|
@Override
@Transactional(value="defaultTransactionManager")
public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) throws AuthenticationException, InvalidClientException {
if (authentication != null && authentication.getOAuth2Request() != null) {
// look up our client
OAuth2Request request = authentication.getOAuth2Request();
ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());
if (client == null) {
throw new InvalidClientException("Client not found: " + request.getClientId());
}
// handle the PKCE code challenge if present
if (request.getExtensions().containsKey(CODE_CHALLENGE)) {
String challenge = (String) request.getExtensions().get(CODE_CHALLENGE);
PKCEAlgorithm alg = PKCEAlgorithm.parse((String) request.getExtensions().get(CODE_CHALLENGE_METHOD));
String verifier = request.getRequestParameters().get(CODE_VERIFIER);
if (alg.equals(PKCEAlgorithm.plain)) {
// do a direct string comparison
if (!challenge.equals(verifier)) {
throw new InvalidRequestException("Code challenge and verifier do not match");
}
} else if (alg.equals(PKCEAlgorithm.S256)) {
// hash the verifier
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
String hash = Base64URL.encode(digest.digest(verifier.getBytes(StandardCharsets.US_ASCII))).toString();
if (!challenge.equals(hash)) {
throw new InvalidRequestException("Code challenge and verifier do not match");
}
} catch (NoSuchAlgorithmException e) {
logger.error("Unknown algorithm for PKCE digest", e);
}
}
}
OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();//accessTokenFactory.createNewAccessToken();
// attach the client
token.setClient(client);
// inherit the scope from the auth, but make a new set so it is
//not unmodifiable. Unmodifiables don't play nicely with Eclipselink, which
//wants to use the clone operation.
Set<SystemScope> scopes = scopeService.fromStrings(request.getScope());
// remove any of the special system scopes
scopes = scopeService.removeReservedScopes(scopes);
token.setScope(scopeService.toStrings(scopes));
// make it expire if necessary
if (client.getAccessTokenValiditySeconds() != null && client.getAccessTokenValiditySeconds() > 0) {
Date expiration = new Date(System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L));
token.setExpiration(expiration);
}
// attach the authorization so that we can look it up later
AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
authHolder.setAuthentication(authentication);
authHolder = authenticationHolderRepository.save(authHolder);
token.setAuthenticationHolder(authHolder);
// attach a refresh token, if this client is allowed to request them and the user gets the offline scope
if (client.isAllowRefresh() && token.getScope().contains(SystemScopeService.OFFLINE_ACCESS)) {
OAuth2RefreshTokenEntity savedRefreshToken = createRefreshToken(client, authHolder);
token.setRefreshToken(savedRefreshToken);
}
//Add approved site reference, if any
OAuth2Request originalAuthRequest = authHolder.getAuthentication().getOAuth2Request();
if (originalAuthRequest.getExtensions() != null && originalAuthRequest.getExtensions().containsKey("approved_site")) {
Long apId = Long.parseLong((String) originalAuthRequest.getExtensions().get("approved_site"));
ApprovedSite ap = approvedSiteService.getById(apId);
token.setApprovedSite(ap);
}
OAuth2AccessTokenEntity enhancedToken = (OAuth2AccessTokenEntity) tokenEnhancer.enhance(token, authentication);
OAuth2AccessTokenEntity savedToken = saveAccessToken(enhancedToken);
if (savedToken.getRefreshToken() != null) {
tokenRepository.saveRefreshToken(savedToken.getRefreshToken()); // make sure we save any changes that might have been enhanced
}
return savedToken;
}
throw new AuthenticationCredentialsNotFoundException("No authentication credentials found");
}
|
@Test
public void createAccessToken_checkAttachedAuthentication() {
AuthenticationHolderEntity authHolder = mock(AuthenticationHolderEntity.class);
when(authHolder.getAuthentication()).thenReturn(authentication);
when(authenticationHolderRepository.save(any(AuthenticationHolderEntity.class))).thenReturn(authHolder);
OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
assertThat(token.getAuthenticationHolder().getAuthentication(), equalTo(authentication));
verify(authenticationHolderRepository).save(any(AuthenticationHolderEntity.class));
verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
}
|
@Override
public <X> TypeInformation<X> getTypeAt(String fieldExpression) {
Matcher matcher = PATTERN_NESTED_FIELDS.matcher(fieldExpression);
if (!matcher.matches()) {
if (fieldExpression.equals(ExpressionKeys.SELECT_ALL_CHAR)
|| fieldExpression.equals(ExpressionKeys.SELECT_ALL_CHAR_SCALA)) {
throw new InvalidFieldReferenceException(
"Wildcard expressions are not allowed here.");
} else {
throw new InvalidFieldReferenceException(
"Invalid format of Row field expression \"" + fieldExpression + "\".");
}
}
String field = matcher.group(1);
Matcher intFieldMatcher = PATTERN_INT_FIELD.matcher(field);
int fieldIndex;
if (intFieldMatcher.matches()) {
// field expression is an integer
fieldIndex = Integer.valueOf(field);
} else {
fieldIndex = this.getFieldIndex(field);
}
// fetch the field type will throw exception if the index is illegal
TypeInformation<X> fieldType = this.getTypeAt(fieldIndex);
String tail = matcher.group(3);
if (tail == null) {
// found the type
return fieldType;
} else {
if (fieldType instanceof CompositeType) {
return ((CompositeType<?>) fieldType).getTypeAt(tail);
} else {
throw new InvalidFieldReferenceException(
"Nested field expression \""
+ tail
+ "\" not possible on atomic type "
+ fieldType
+ ".");
}
}
}
|
@Test
void testGetTypeAt() {
RowTypeInfo typeInfo = new RowTypeInfo(typeList);
assertThat(typeInfo.getFieldNames()).isEqualTo(new String[] {"f0", "f1", "f2"});
assertThat(typeInfo.getTypeAt("f2")).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO);
assertThat(typeInfo.getTypeAt("f1.f0")).isEqualTo(BasicTypeInfo.SHORT_TYPE_INFO);
assertThat(typeInfo.getTypeAt("f1.1")).isEqualTo(BasicTypeInfo.BIG_DEC_TYPE_INFO);
}
|
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
}
|
@Test
public void detectCircularReferencesInDefault() {
context.putProperty("A", "${B:-${A}}");
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${B} --> ${A}]");
OptionHelper.substVars("${A}", context);
}
|
@Deprecated
public Expression createExpression(String expression)
{
return createExpression(expression, new ParsingOptions());
}
|
@Test(timeOut = 2_000)
public void testPotentialUnboundedLookahead()
{
SQL_PARSER.createExpression("(\n" +
" 1 * -1 +\n" +
" 1 * -2 +\n" +
" 1 * -3 +\n" +
" 1 * -4 +\n" +
" 1 * -5 +\n" +
" 1 * -6 +\n" +
" 1 * -7 +\n" +
" 1 * -8 +\n" +
" 1 * -9 +\n" +
" 1 * -10 +\n" +
" 1 * -11 +\n" +
" 1 * -12 \n" +
")\n");
}
|
@Override
public List<ParsedStatement> parse(final String sql) {
return primaryContext.parse(sql);
}
|
@Test
public void shouldNotEnforceTopicExistenceWhileParsing() {
setupKsqlEngineWithSharedRuntimeEnabled();
final String runScriptContent = "CREATE STREAM S1 (COL1 BIGINT, COL2 VARCHAR) "
+ "WITH (KAFKA_TOPIC = 's1_topic', VALUE_FORMAT = 'JSON', KEY_FORMAT = 'KAFKA');\n"
+ "CREATE TABLE T1 AS SELECT COL1, count(*) FROM "
+ "S1 GROUP BY COL1;\n"
+ "CREATE STREAM S2 (C1 BIGINT, C2 BIGINT) "
+ "WITH (KAFKA_TOPIC = 'T1', VALUE_FORMAT = 'JSON', KEY_FORMAT = 'KAFKA');\n";
final List<?> parsedStatements = ksqlEngine.parse(runScriptContent);
assertThat(parsedStatements.size(), equalTo(3));
}
|
@Override
public void updateGroup(MemberGroupUpdateReqVO updateReqVO) {
// 校验存在
validateGroupExists(updateReqVO.getId());
// 更新
MemberGroupDO updateObj = MemberGroupConvert.INSTANCE.convert(updateReqVO);
memberGroupMapper.updateById(updateObj);
}
|
@Test
public void testUpdateGroup_success() {
// mock 数据
MemberGroupDO dbGroup = randomPojo(MemberGroupDO.class);
groupMapper.insert(dbGroup);// @Sql: 先插入出一条存在的数据
// 准备参数
MemberGroupUpdateReqVO reqVO = randomPojo(MemberGroupUpdateReqVO.class, o -> {
o.setId(dbGroup.getId()); // 设置更新的 ID
o.setStatus(randomCommonStatus());
});
// 调用
groupService.updateGroup(reqVO);
// 校验是否更新正确
MemberGroupDO group = groupMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, group);
}
|
@Override
public String getCommandName() {
return COMMAND_NAME;
}
|
@Test
public void linuxCmdExecuted()
throws IOException, AlluxioException, NoSuchFieldException, IllegalAccessException {
CollectEnvCommand cmd = new CollectEnvCommand(FileSystemContext.create());
// Write to temp dir
File targetDir = InfoCollectorTestUtils.createTemporaryDirectory();
CommandLine mockCommandLine = mock(CommandLine.class);
String[] mockArgs = new String[]{cmd.getCommandName(), targetDir.getAbsolutePath()};
when(mockCommandLine.getArgs()).thenReturn(mockArgs);
// Replace commands to execute
Field f = cmd.getClass().getSuperclass().getDeclaredField("mCommands");
f.setAccessible(true);
ShellCommand mockCommand = mock(ShellCommand.class);
when(mockCommand.runWithOutput()).thenReturn(new CommandReturn(0, "nothing happens"));
when(mockCommandLine.getOptionValue("output-dir", ""))
.thenReturn(targetDir.getAbsolutePath());
Map<String, ShellCommand> mockCommandMap = new HashMap<>();
mockCommandMap.put("mockCommand", mockCommand);
f.set(cmd, mockCommandMap);
int ret = cmd.run(mockCommandLine);
assertEquals(0, ret);
// Verify the command has been run
verify(mockCommand).runWithOutput();
// Files will be copied to sub-dir of target dir
File subDir = new File(Paths.get(targetDir.getAbsolutePath(), cmd.getCommandName()).toString());
assertEquals(new String[]{"collectEnv.txt"}, subDir.list());
// Verify the command output is found
String fileContent = new String(Files.readAllBytes(subDir.listFiles()[0].toPath()));
assertTrue(fileContent.contains("nothing happens"));
}
|
static public String jsonEscapeString(String input) {
int length = input.length();
int lenthWithLeeway = (int) (length * 1.1);
StringBuilder sb = new StringBuilder(lenthWithLeeway);
for (int i = 0; i < length; i++) {
final char c = input.charAt(i);
String escaped = getObligatoryEscapeCode(c);
if (escaped == null)
sb.append(c);
else {
sb.append(escaped);
}
}
return sb.toString();
}
|
@Test
public void testEscapingLF() {
String input = "{\nhello: \"wo\nrld\"}";
System.out.println(input);
assertEquals("{\\nhello: "+'\\'+'"'+"wo\\nrld\\\"}", JsonEscapeUtil.jsonEscapeString(input));
}
|
public BeamFnApi.InstructionResponse.Builder finalizeBundle(BeamFnApi.InstructionRequest request)
throws Exception {
String bundleId = request.getFinalizeBundle().getInstructionId();
Collection<CallbackRegistration> callbacks = bundleFinalizationCallbacks.remove(bundleId);
if (callbacks == null) {
// We have already processed the callbacks on a prior bundle finalization attempt
return BeamFnApi.InstructionResponse.newBuilder()
.setFinalizeBundle(FinalizeBundleResponse.getDefaultInstance());
}
Collection<Exception> failures = new ArrayList<>();
for (CallbackRegistration callback : callbacks) {
try {
callback.getCallback().onBundleSuccess();
} catch (Exception e) {
failures.add(e);
}
}
if (!failures.isEmpty()) {
Exception e =
new Exception(
String.format("Failed to handle bundle finalization for bundle %s.", bundleId));
for (Exception failure : failures) {
e.addSuppressed(failure);
}
throw e;
}
return BeamFnApi.InstructionResponse.newBuilder()
.setFinalizeBundle(FinalizeBundleResponse.getDefaultInstance());
}
|
@Test
public void testFinalizationIgnoresMissingBundleIds() throws Exception {
FinalizeBundleHandler handler = new FinalizeBundleHandler(Executors.newCachedThreadPool());
assertEquals(SUCCESSFUL_RESPONSE, handler.finalizeBundle(requestFor("test")).build());
}
|
private String setField(BufferedReader reader) throws IOException {
String targetObjectId = reader.readLine();
String fieldName = reader.readLine();
String value = reader.readLine();
reader.readLine(); // read EndOfCommand;
Object valueObject = Protocol.getObject(value, this.gateway);
Object object = gateway.getObject(targetObjectId);
Field field = reflectionEngine.getField(object, fieldName);
logger.finer("Setting field " + fieldName);
String returnCommand = null;
if (field == null) {
returnCommand = Protocol.getNoSuchFieldOutputCommand();
} else {
reflectionEngine.setFieldValue(object, field, valueObject);
returnCommand = Protocol.getOutputVoidCommand();
}
return returnCommand;
}
|
@Test
public void testSetField() {
String inputCommand = "s\n" + target + "\nfield10\ni123\ne\n";
try {
command.execute("f", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!yv\n", sWriter.toString());
assertEquals(((ExampleClass) gateway.getObject(target)).field10, 123);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
|
public static Index simple(String name) {
return new Index(name, false);
}
|
@Test
public void getJoinField_throws_ISE_on_simple_index() {
Index underTest = Index.simple("foo");
assertThatThrownBy(underTest::getJoinField)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Only index accepting relations has a join field");
}
|
public static void renameTo(File src, File dst)
throws IOException {
if (!nativeLoaded) {
if (!src.renameTo(dst)) {
throw new IOException("renameTo(src=" + src + ", dst=" +
dst + ") failed.");
}
} else {
renameTo0(src.getAbsolutePath(), dst.getAbsolutePath());
}
}
|
@Test (timeout = 30000)
public void testRenameTo() throws Exception {
final File TEST_DIR = GenericTestUtils.getTestDir("renameTest") ;
assumeTrue(TEST_DIR.mkdirs());
File nonExistentFile = new File(TEST_DIR, "nonexistent");
File targetFile = new File(TEST_DIR, "target");
// Test attempting to rename a nonexistent file.
try {
NativeIO.renameTo(nonExistentFile, targetFile);
Assert.fail();
} catch (NativeIOException e) {
if (Path.WINDOWS) {
Assert.assertEquals(
String.format("The system cannot find the file specified.%n"),
e.getMessage());
} else {
Assert.assertEquals(Errno.ENOENT, e.getErrno());
}
}
// Test renaming a file to itself. It should succeed and do nothing.
File sourceFile = new File(TEST_DIR, "source");
Assert.assertTrue(sourceFile.createNewFile());
NativeIO.renameTo(sourceFile, sourceFile);
// Test renaming a source to a destination.
NativeIO.renameTo(sourceFile, targetFile);
// Test renaming a source to a path which uses a file as a directory.
sourceFile = new File(TEST_DIR, "source");
Assert.assertTrue(sourceFile.createNewFile());
File badTarget = new File(targetFile, "subdir");
try {
NativeIO.renameTo(sourceFile, badTarget);
Assert.fail();
} catch (NativeIOException e) {
if (Path.WINDOWS) {
Assert.assertEquals(
String.format("The parameter is incorrect.%n"),
e.getMessage());
} else {
Assert.assertEquals(Errno.ENOTDIR, e.getErrno());
}
}
// Test renaming to an existing file
assertTrue(targetFile.exists());
NativeIO.renameTo(sourceFile, targetFile);
}
|
@Override
public void cancel(InterpreterContext context) throws InterpreterException {
String shinyApp = context.getStringLocalProperty("app", DEFAULT_APP_NAME);
IRInterpreter irInterpreter = getIRInterpreter(shinyApp);
irInterpreter.cancel(context);
}
|
@Test
void testInvalidShinyApp()
throws IOException, InterpreterException, InterruptedException, UnirestException {
InterpreterContext context = getInterpreterContext();
context.getLocalProperties().put("type", "ui");
InterpreterResult result =
interpreter.interpret(IOUtils.toString(getClass().getResource("/invalid_ui.R"), StandardCharsets.UTF_8), context);
assertEquals(InterpreterResult.Code.SUCCESS, result.code());
context = getInterpreterContext();
context.getLocalProperties().put("type", "server");
result = interpreter.interpret(IOUtils.toString(getClass().getResource("/server.R"), StandardCharsets.UTF_8), context);
assertEquals(InterpreterResult.Code.SUCCESS, result.code());
final InterpreterContext context2 = getInterpreterContext();
context2.getLocalProperties().put("type", "run");
Thread thread = new Thread(() -> {
try {
interpreter.interpret("", context2);
} catch (Exception e) {
e.printStackTrace();
}
});
thread.start();
// wait for the shiny app start
Thread.sleep(5 * 1000);
List<InterpreterResultMessage> resultMessages = context2.out.toInterpreterResultMessage();
assertEquals(1, resultMessages.size(), resultMessages.toString());
assertEquals(InterpreterResult.Type.HTML, resultMessages.get(0).getType());
String resultMessageData = resultMessages.get(0).getData();
assertTrue(resultMessageData.contains("<iframe"), resultMessageData);
Pattern urlPattern = Pattern.compile(".*src=\"(http\\S*)\".*", Pattern.DOTALL);
Matcher matcher = urlPattern.matcher(resultMessageData);
if (!matcher.matches()) {
fail("Unable to extract url: " + resultMessageData);
}
String shinyURL = matcher.group(1);
// call shiny app via rest api
HttpResponse<String> response = Unirest.get(shinyURL).asString();
assertEquals(500, response.getStatus());
resultMessages = context2.out.toInterpreterResultMessage();
assertTrue(resultMessages.get(1).getData().contains("Invalid_code"),
resultMessages.get(1).getData());
// depends on JVM language
// assertTrue(resultMessages.get(1).getData().contains("object 'Invalid_code' not found"),
// resultMessages.get(1).getData());
// cancel paragraph to stop shiny app
interpreter.cancel(getInterpreterContext());
// wait for shiny app to be stopped
Thread.sleep(1000);
try {
Unirest.get(shinyURL).asString();
fail("Should fail to connect to shiny app");
} catch (Exception e) {
assertTrue(e.getMessage().contains("Connection refused"), e.getMessage());
}
}
|
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] lines = splitAndRemoveEmpty(st, "\n");
return interpret(lines, context);
}
|
@Test
void lsTest() throws IOException, AlluxioException {
URIStatus[] files = new URIStatus[3];
FileSystemTestUtils.createByteFile(fs, "/testRoot/testFileA",
WritePType.MUST_CACHE, 10, 10);
FileSystemTestUtils.createByteFile(fs, "/testRoot/testDir/testFileB",
WritePType.MUST_CACHE, 20, 20);
FileSystemTestUtils.createByteFile(fs, "/testRoot/testFileC",
WritePType.THROUGH, 30, 30);
files[0] = fs.getStatus(new AlluxioURI("/testRoot/testFileA"));
files[1] = fs.getStatus(new AlluxioURI("/testRoot/testDir"));
files[2] = fs.getStatus(new AlluxioURI("/testRoot/testFileC"));
InterpreterResult output = alluxioInterpreter.interpret("ls /testRoot", null);
assertEquals(Code.SUCCESS, output.code());
}
|
protected void processFileContents(List<String> fileLines, String filePath, Engine engine) throws AnalysisException {
fileLines.stream()
.map(fileLine -> fileLine.split("(,|=>)"))
.map(requires -> {
//LOGGER.debug("perl scanning file:" + fileLine);
final String fqName = requires[0].substring(8)
.replace("'", "")
.replace("\"", "")
.trim();
final String version;
if (requires.length == 1) {
version = "0";
} else {
final Matcher matcher = VERSION_PATTERN.matcher(requires[1]);
if (matcher.find()) {
version = matcher.group(1);
} else {
version = "0";
}
}
final int pos = fqName.lastIndexOf("::");
final String namespace;
final String name;
if (pos > 0) {
namespace = fqName.substring(0, pos);
name = fqName.substring(pos + 2);
} else {
namespace = null;
name = fqName;
}
final Dependency dependency = new Dependency(true);
final File f = new File(filePath);
dependency.setFileName(f.getName());
dependency.setFilePath(filePath);
dependency.setActualFilePath(filePath);
dependency.setDisplayFileName("'" + fqName + "', '" + version + "'");
dependency.setEcosystem(Ecosystem.PERL);
dependency.addEvidence(EvidenceType.VENDOR, "cpanfile", "requires", fqName, Confidence.HIGHEST);
dependency.addEvidence(EvidenceType.PRODUCT, "cpanfile", "requires", fqName, Confidence.HIGHEST);
dependency.addEvidence(EvidenceType.VERSION, "cpanfile", "requires", version, Confidence.HIGHEST);
Identifier id = null;
try {
//note - namespace might be null and that's okay.
final PackageURL purl = PackageURLBuilder.aPackageURL()
.withType("cpan")
.withNamespace(namespace)
.withName(name)
.withVersion(version)
.build();
id = new PurlIdentifier(purl, Confidence.HIGH);
} catch (MalformedPackageURLException ex) {
LOGGER.debug("Error building package url for " + fqName + "; using generic identifier instead.", ex);
id = new GenericIdentifier("cpan:" + fqName + "::" + version, Confidence.HIGH);
}
dependency.setVersion(version);
dependency.setName(fqName);
dependency.addSoftwareIdentifier(id);
//sha1sum is used for anchor links in the HtML report
dependency.setSha1sum(Checksum.getSHA1Checksum(id.getValue()));
return dependency;
}).forEachOrdered(engine::addDependency);
}
|
@Test
public void testProcessFileContents() throws AnalysisException {
Dependency d = new Dependency();
List<String> dependencyLines = Arrays.asList(new String[]{
"requires 'Plack', '1.0'",
"requires 'JSON', '>= 2.00, < 2.80'",
"requires 'Mojolicious::Plugin::ZAPI' => '>= 2.015",
"requires 'Hash::MoreUtils' => '>= 0.05",
"requires 'JSON::MaybeXS' => '>= 1.002004'",
"requires 'Test::MockModule'"
});
PerlCpanfileAnalyzer instance = new PerlCpanfileAnalyzer();
Engine engine = new Engine(getSettings());
instance.processFileContents(dependencyLines, "./cpanfile", engine);
assertEquals(6, engine.getDependencies().length);
}
|
public static String getShortName(String destinationName) {
if (destinationName == null) {
throw new IllegalArgumentException("destinationName is null");
}
if (destinationName.startsWith("queue:")) {
return destinationName.substring(6);
} else if (destinationName.startsWith("topic:")) {
return destinationName.substring(6);
} else {
return destinationName;
}
}
|
@Test
public void testGetShortNameNullDestinationName() {
assertThrows(IllegalArgumentException.class,
() -> DestinationNameParser.getShortName(null));
}
|
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) {
if(StringUtils.containsAny(remote.getName(), '*')) {
// Treat asterisk as wildcard
return Collections.singleton(new TransferItem(remote.getParent()));
}
return Collections.singleton(new TransferItem(remote));
}
|
@Test
public void testFindDirectory() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace://cdn.cyberduck.ch/remote"});
assertTrue(new DeletePathFinder().find(input, TerminalAction.delete, new Path("/remote", EnumSet.of(Path.Type.directory))).contains(
new TransferItem(new Path("/remote", EnumSet.of(Path.Type.directory)))
));
}
|
public static IcebergDecimalObjectInspector get(int precision, int scale) {
Preconditions.checkArgument(scale <= precision);
Preconditions.checkArgument(precision <= HiveDecimal.MAX_PRECISION);
Preconditions.checkArgument(scale <= HiveDecimal.MAX_SCALE);
Integer key = precision << 8 | scale;
return CACHE.get(key, k -> new IcebergDecimalObjectInspector(precision, scale));
}
|
@Test
public void testCache() {
HiveDecimalObjectInspector oi = IcebergDecimalObjectInspector.get(38, 18);
Assert.assertSame(oi, IcebergDecimalObjectInspector.get(38, 18));
Assert.assertNotSame(oi, IcebergDecimalObjectInspector.get(28, 18));
Assert.assertNotSame(oi, IcebergDecimalObjectInspector.get(38, 28));
}
|
public GroupInformation createGroup(DbSession dbSession, String name, @Nullable String description) {
validateGroupName(name);
checkNameDoesNotExist(dbSession, name);
GroupDto group = new GroupDto()
.setUuid(uuidFactory.create())
.setName(name)
.setDescription(description);
return groupDtoToGroupInformation(dbClient.groupDao().insert(dbSession, group), dbSession);
}
|
@Test
@UseDataProvider("invalidGroupNames")
public void createGroup_whenGroupNameIsInvalid_throws(String groupName, String errorMessage) {
mockDefaultGroup();
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.createGroup(dbSession, groupName, "Description"))
.withMessage(errorMessage);
}
|
@Override
public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
checkPermission(FLOWRULE_WRITE);
if (forwardingObjective.nextId() == null ||
flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
!queueFwdObjective(deviceId, forwardingObjective)) {
// fast path
installerExecutor.execute(new ObjectiveProcessor(deviceId, forwardingObjective, installerExecutor));
}
}
|
@Test
public void forwardingObjective() {
TrafficSelector selector = DefaultTrafficSelector.emptySelector();
TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment();
ForwardingObjective forward =
DefaultForwardingObjective.builder()
.fromApp(NetTestTools.APP_ID)
.withFlag(ForwardingObjective.Flag.SPECIFIC)
.withSelector(selector)
.withTreatment(treatment)
.makePermanent()
.add();
manager.forward(id1, forward);
TestTools.assertAfter(RETRY_MS, () ->
assertThat(forwardingObjectives, hasSize(1)));
assertThat(forwardingObjectives, hasItem("of:d1"));
assertThat(filteringObjectives, hasSize(0));
assertThat(nextObjectives, hasSize(0));
}
|
@Override
public UnitExtension getUnitExtension(String extensionName) {
if (extensionName.equals("SoldierExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this));
}
return super.getUnitExtension(extensionName);
}
|
@Test
void getUnitExtension() {
final var unit = new SoldierUnit("SoldierUnitName");
assertNotNull(unit.getUnitExtension("SoldierExtension"));
assertNull(unit.getUnitExtension("SergeantExtension"));
assertNull(unit.getUnitExtension("CommanderExtension"));
}
|
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) {
List<String> basePath = getPathComponents(canonicalBaseFile);
List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize);
//if the roots aren't the same (i.e. different drives on a windows machine), we can't construct a relative
//path from one to the other, so just return the canonical file
if (!basePath.get(0).equals(pathToRelativize.get(0))) {
return canonicalFileToRelativize.getPath();
}
int commonDirs;
StringBuilder sb = new StringBuilder();
for (commonDirs=1; commonDirs<basePath.size() && commonDirs<pathToRelativize.size(); commonDirs++) {
if (!basePath.get(commonDirs).equals(pathToRelativize.get(commonDirs))) {
break;
}
}
boolean first = true;
for (int i=commonDirs; i<basePath.size(); i++) {
if (!first) {
sb.append(File.separatorChar);
} else {
first = false;
}
sb.append("..");
}
first = true;
for (int i=commonDirs; i<pathToRelativize.size(); i++) {
if (first) {
if (sb.length() != 0) {
sb.append(File.separatorChar);
}
first = false;
} else {
sb.append(File.separatorChar);
}
sb.append(pathToRelativize.get(i));
}
if (sb.length() == 0) {
return ".";
}
return sb.toString();
}
|
@Test
public void pathUtilTest1() {
File[] roots = File.listRoots();
if (roots.length > 1) {
File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt");
File relativePath = new File(roots[1] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt");
String path = PathUtil.getRelativeFileInternal(basePath, relativePath);
Assert.assertEquals(path, relativePath.getPath());
}
}
|
public <T> T getFieldAs(final Class<T> T, final String key) throws ClassCastException {
return T.cast(getField(key));
}
|
@Test
public void testGetFieldAs() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields"));
}
|
public void addStripAction(@NonNull StripActionProvider provider, boolean highPriority) {
for (var stripActionView : mStripActionViews) {
if (stripActionView.getTag(PROVIDER_TAG_ID) == provider) {
return;
}
}
var actionView = provider.inflateActionView(this);
if (actionView.getParent() != null)
throw new IllegalStateException("StripActionProvider inflated a view with a parent!");
actionView.setTag(PROVIDER_TAG_ID, provider);
if (mShowActionStrip) {
if (highPriority) {
addView(actionView, FIRST_PROVIDER_VIEW_INDEX);
} else {
addView(actionView);
}
}
if (highPriority) {
mStripActionViews.add(0, actionView);
} else {
mStripActionViews.add(actionView);
}
invalidate();
}
|
@Test
public void testHighBothPriority() {
View view = new View(mUnderTest.getContext());
View view2 = new View(mUnderTest.getContext());
KeyboardViewContainerView.StripActionProvider provider =
Mockito.mock(KeyboardViewContainerView.StripActionProvider.class);
Mockito.doReturn(view).when(provider).inflateActionView(any());
KeyboardViewContainerView.StripActionProvider provider2 =
Mockito.mock(KeyboardViewContainerView.StripActionProvider.class);
Mockito.doReturn(view2).when(provider2).inflateActionView(any());
mUnderTest.addStripAction(provider, true);
Assert.assertEquals(3, mUnderTest.getChildCount());
Assert.assertSame(view, mUnderTest.getChildAt(2));
mUnderTest.addStripAction(provider2, true);
Assert.assertEquals(4, mUnderTest.getChildCount());
Assert.assertSame(view2, mUnderTest.getChildAt(2));
Assert.assertSame(view, mUnderTest.getChildAt(3));
}
|
public static JaasContext loadServerContext(ListenerName listenerName, String mechanism, Map<String, ?> configs) {
if (listenerName == null)
throw new IllegalArgumentException("listenerName should not be null for SERVER");
if (mechanism == null)
throw new IllegalArgumentException("mechanism should not be null for SERVER");
String listenerContextName = listenerName.value().toLowerCase(Locale.ROOT) + "." + GLOBAL_CONTEXT_NAME_SERVER;
Password dynamicJaasConfig = (Password) configs.get(mechanism.toLowerCase(Locale.ROOT) + "." + SaslConfigs.SASL_JAAS_CONFIG);
if (dynamicJaasConfig == null && configs.get(SaslConfigs.SASL_JAAS_CONFIG) != null)
LOG.warn("Server config {} should be prefixed with SASL mechanism name, ignoring config", SaslConfigs.SASL_JAAS_CONFIG);
return load(Type.SERVER, listenerContextName, GLOBAL_CONTEXT_NAME_SERVER, dynamicJaasConfig);
}
|
@Test
public void testLoadForServerWithWrongListenerName() throws IOException {
writeConfiguration("Server", "test.LoginModule required;");
assertThrows(IllegalArgumentException.class, () -> JaasContext.loadServerContext(new ListenerName("plaintext"),
"SOME-MECHANISM", Collections.emptyMap()));
}
|
public final int getEventLen() {
return eventLen;
}
|
@Test
public void getEventLenOutputZero() {
// Arrange
final LogHeader objectUnderTest = new LogHeader(0);
// Act
final int actual = objectUnderTest.getEventLen();
// Assert result
Assert.assertEquals(0, actual);
}
|
public static URI buildExternalUri(@NotNull MultivaluedMap<String, String> httpHeaders, @NotNull URI defaultUri) {
Optional<URI> externalUri = Optional.empty();
final List<String> headers = httpHeaders.get(HttpConfiguration.OVERRIDE_HEADER);
if (headers != null && !headers.isEmpty()) {
externalUri = headers.stream()
.filter(s -> {
try {
if (Strings.isNullOrEmpty(s)) {
return false;
}
final URI uri = new URI(s);
if (!uri.isAbsolute()) {
return true;
}
switch (uri.getScheme()) {
case "http":
case "https":
return true;
}
return false;
} catch (URISyntaxException e) {
return false;
}
})
.map(URI::create)
.findFirst();
}
final URI uri = externalUri.orElse(defaultUri);
// Make sure we return an URI object with a trailing slash
if (!uri.toString().endsWith("/")) {
return URI.create(uri.toString() + "/");
}
return uri;
}
|
@Test
public void buildExternalUriReturnsDefaultUriIfHeaderIsEmpty() throws Exception {
final MultivaluedMap<String, String> httpHeaders = new MultivaluedHashMap<>();
httpHeaders.putSingle(HttpConfiguration.OVERRIDE_HEADER, "");
final URI externalUri = URI.create("http://graylog.example.com/");
assertThat(RestTools.buildExternalUri(httpHeaders, externalUri)).isEqualTo(externalUri);
}
|
public static SimpleTransform exp() {
return new SimpleTransform(Operation.exp);
}
|
@Test
public void testExp() {
TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.exp()),new HashMap<>());
testSimple(t,Math::exp);
}
|
public boolean isAllBindingTables(final Collection<String> logicTableNames) {
if (logicTableNames.isEmpty()) {
return false;
}
Optional<BindingTableRule> bindingTableRule = findBindingTableRule(logicTableNames);
if (!bindingTableRule.isPresent()) {
return false;
}
Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
result.addAll(bindingTableRule.get().getAllLogicTables());
return !result.isEmpty() && result.containsAll(logicTableNames);
}
|
@Test
void assertIsAllBindingTableWithoutJoinQuery() {
SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class);
when(sqlStatementContext.isContainsJoinQuery()).thenReturn(false);
assertTrue(
createMaximumShardingRule().isAllBindingTables(mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), sqlStatementContext, Arrays.asList("logic_Table", "sub_Logic_Table")));
}
|
public Optional<String> getType(Set<String> streamIds, String field) {
final Map<String, Set<String>> allFieldTypes = this.get(streamIds);
final Set<String> fieldTypes = allFieldTypes.get(field);
return typeFromFieldType(fieldTypes);
}
|
@Test
void returnsEmptyOptionalIfFieldTypesAreEmpty() {
final Pair<IndexFieldTypesService, StreamService> services = mockServices();
final FieldTypesLookup lookup = new FieldTypesLookup(services.getLeft(), services.getRight());
final Optional<String> result = lookup.getType(Collections.singleton("SomeStream"), "somefield");
assertThat(result).isEmpty();
}
|
static Serializer createSerializer(Fury fury, Class<?> cls) {
for (Tuple2<Class<?>, Function> factory : synchronizedFactories()) {
if (factory.f0 == cls) {
return createSerializer(fury, factory);
}
}
throw new IllegalArgumentException("Unsupported type " + cls);
}
|
@Test
public void testWrite() throws Exception {
Fury fury = Fury.builder().withLanguage(Language.JAVA).requireClassRegistration(false).build();
MemoryBuffer buffer = MemoryUtils.buffer(32);
Object[] values =
new Object[] {
Collections.synchronizedCollection(Collections.singletonList("abc")),
Collections.synchronizedCollection(Arrays.asList(1, 2)),
Collections.synchronizedList(Arrays.asList("abc", "def")),
Collections.synchronizedList(new LinkedList<>(Arrays.asList("abc", "def"))),
Collections.synchronizedSet(new HashSet<>(Arrays.asList("abc", "def"))),
Collections.synchronizedSortedSet(new TreeSet<>(Arrays.asList("abc", "def"))),
Collections.synchronizedMap(ImmutableMap.of("k1", "v1")),
Collections.synchronizedSortedMap(new TreeMap<>(ImmutableMap.of("k1", "v1")))
};
for (Object value : values) {
buffer.writerIndex(0);
buffer.readerIndex(0);
Serializer serializer = SynchronizedSerializers.createSerializer(fury, value.getClass());
serializer.write(buffer, value);
Object newObj = serializer.read(buffer);
assertEquals(newObj.getClass(), value.getClass());
long sourceCollectionFieldOffset =
Collection.class.isAssignableFrom(value.getClass())
? SOURCE_COLLECTION_FIELD_OFFSET
: SOURCE_MAP_FIELD_OFFSET;
Object innerValue = Platform.getObject(value, sourceCollectionFieldOffset);
Object newValue = Platform.getObject(newObj, sourceCollectionFieldOffset);
assertEquals(innerValue, newValue);
newObj = serDe(fury, value);
innerValue = Platform.getObject(value, sourceCollectionFieldOffset);
newValue = Platform.getObject(newObj, sourceCollectionFieldOffset);
assertEquals(innerValue, newValue);
assertTrue(
fury.getClassResolver()
.getSerializerClass(value.getClass())
.getName()
.contains("Synchronized"));
}
}
|
@Override
public WebSocketServerExtension handshakeExtension(WebSocketExtensionData extensionData) {
if (!X_WEBKIT_DEFLATE_FRAME_EXTENSION.equals(extensionData.name()) &&
!DEFLATE_FRAME_EXTENSION.equals(extensionData.name())) {
return null;
}
if (extensionData.parameters().isEmpty()) {
return new DeflateFrameServerExtension(compressionLevel, extensionData.name(), extensionFilterProvider);
} else {
return null;
}
}
|
@Test
public void testWebkitHandshake() {
// initialize
DeflateFrameServerExtensionHandshaker handshaker =
new DeflateFrameServerExtensionHandshaker();
// execute
WebSocketServerExtension extension = handshaker.handshakeExtension(
new WebSocketExtensionData(X_WEBKIT_DEFLATE_FRAME_EXTENSION, Collections.<String, String>emptyMap()));
// test
assertNotNull(extension);
assertEquals(WebSocketServerExtension.RSV1, extension.rsv());
assertTrue(extension.newExtensionDecoder() instanceof PerFrameDeflateDecoder);
assertTrue(extension.newExtensionEncoder() instanceof PerFrameDeflateEncoder);
}
|
public void performAction(Command s, int actionIndex) {
actions.get(actionIndex).updateModel(s);
}
|
@Test
void testPerformAction() {
final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT,
Nourishment.SATURATED);
Action action = new Action(model);
GiantView giantView = new GiantView();
Dispatcher dispatcher = new Dispatcher(giantView);
assertEquals(Nourishment.SATURATED, model.getNourishment());
dispatcher.addAction(action);
for (final var nourishment : Nourishment.values()) {
for (final var fatigue : Fatigue.values()) {
for (final var health : Health.values()) {
Command cmd = new Command(fatigue, health, nourishment);
dispatcher.performAction(cmd, 0);
assertEquals(nourishment, model.getNourishment());
assertEquals(fatigue, model.getFatigue());
assertEquals(health, model.getHealth());
}
}
}
}
|
public static Extension findExtensionAnnotation(Class<?> clazz) {
if (clazz.isAnnotationPresent(Extension.class)) {
return clazz.getAnnotation(Extension.class);
}
// search recursively through all annotations
for (Annotation annotation : clazz.getAnnotations()) {
Class<? extends Annotation> annotationClass = annotation.annotationType();
if (!annotationClass.getName().startsWith("java.lang.annotation")) {
Extension extensionAnnotation = findExtensionAnnotation(annotationClass);
if (extensionAnnotation != null) {
return extensionAnnotation;
}
}
}
return null;
}
|
@Test
public void findExtensionAnnotationThatMissing() {
List<JavaFileObject> generatedFiles = JavaSources.compileAll(JavaSources.Greeting,
ExtensionAnnotationProcessorTest.SpinnakerExtension_NoExtension,
ExtensionAnnotationProcessorTest.WhazzupGreeting_SpinnakerExtension);
assertEquals(3, generatedFiles.size());
Map<String, Class<?>> loadedClasses = new JavaFileObjectClassLoader().load(generatedFiles);
Class<?> clazz = loadedClasses.get("test.WhazzupGreeting");
Extension extension = AbstractExtensionFinder.findExtensionAnnotation(clazz);
Assertions.assertNull(extension);
}
|
public DropTypeCommand create(final DropType statement) {
final String typeName = statement.getTypeName();
final boolean ifExists = statement.getIfExists();
if (!ifExists && !metaStore.resolveType(typeName).isPresent()) {
throw new KsqlException("Type " + typeName + " does not exist.");
}
return new DropTypeCommand(typeName);
}
|
@Test
public void shouldCreateDropType() {
// Given:
final DropType dropType = new DropType(Optional.empty(), EXISTING_TYPE, false);
// When:
final DropTypeCommand cmd = factory.create(dropType);
// Then:
assertThat(cmd.getTypeName(), equalTo(EXISTING_TYPE));
}
|
public static Object eval(String expression, Map<String, Object> context) {
return eval(expression, context, ListUtil.empty());
}
|
@Test
public void spELTest(){
final ExpressionEngine engine = new SpELEngine();
final Dict dict = Dict.create()
.set("a", 100.3)
.set("b", 45)
.set("c", -199.100);
final Object eval = engine.eval("#a-(#b-#c)", dict, null);
assertEquals(-143.8, (double)eval, 0);
}
|
protected boolean inList(String includeMethods, String excludeMethods, String methodName) {
//判断是否在白名单中
if (!StringUtils.ALL.equals(includeMethods)) {
if (!inMethodConfigs(includeMethods, methodName)) {
return false;
}
}
//判断是否在黑白单中
if (inMethodConfigs(excludeMethods, methodName)) {
return false;
}
//默认还是要发布
return true;
}
|
@Test
public void PrefixIncludeListTest() {
ProviderConfig providerConfig = new ProviderConfig();
DefaultProviderBootstrap defaultProviderBootstra = new DefaultProviderBootstrap(providerConfig);
boolean result = defaultProviderBootstra.inList("hello1", "hello1", "hello");
Assert.assertTrue(!result);
}
|
public static JsonElement parseString(String json) throws JsonSyntaxException {
return parseReader(new StringReader(json));
}
|
@Test
public void testParseString() {
String json = "{a:10,b:'c'}";
JsonElement e = JsonParser.parseString(json);
assertThat(e.isJsonObject()).isTrue();
assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
}
|
@PublicAPI(usage = ACCESS)
public static ArchRule testClassesShouldResideInTheSamePackageAsImplementation() {
return testClassesShouldResideInTheSamePackageAsImplementation("Test");
}
|
@Test
public void should_pass_when_test_class_is_missing_and_only_implementation_provided() {
assertThatRule(testClassesShouldResideInTheSamePackageAsImplementation())
.checking(new ClassFileImporter().importPackagesOf(ImplementationClassWithoutTestClass.class))
.hasNoViolation();
}
|
@Override
public InterpreterResult interpret(final String st, final InterpreterContext context)
throws InterpreterException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("st:\n{}", st);
}
final FormType form = getFormType();
RemoteInterpreterProcess interpreterProcess = null;
try {
interpreterProcess = getOrCreateInterpreterProcess();
} catch (IOException e) {
throw new InterpreterException(e);
}
if (!interpreterProcess.isRunning()) {
return new InterpreterResult(InterpreterResult.Code.ERROR,
"Interpreter process is not running\n" + interpreterProcess.getErrorMessage());
}
return interpreterProcess.callRemoteFunction(client -> {
RemoteInterpreterResult remoteResult = client.interpret(
sessionId, className, st, convert(context));
Map<String, Object> remoteConfig = (Map<String, Object>) GSON.fromJson(
remoteResult.getConfig(), new TypeToken<Map<String, Object>>() {
}.getType());
context.getConfig().clear();
if (remoteConfig != null) {
context.getConfig().putAll(remoteConfig);
}
GUI currentGUI = context.getGui();
GUI currentNoteGUI = context.getNoteGui();
if (form == FormType.NATIVE) {
GUI remoteGui = GUI.fromJson(remoteResult.getGui());
GUI remoteNoteGui = GUI.fromJson(remoteResult.getNoteGui());
currentGUI.clear();
currentGUI.setParams(remoteGui.getParams());
currentGUI.setForms(remoteGui.getForms());
currentNoteGUI.setParams(remoteNoteGui.getParams());
currentNoteGUI.setForms(remoteNoteGui.getForms());
} else if (form == FormType.SIMPLE) {
final Map<String, Input> currentForms = currentGUI.getForms();
final Map<String, Object> currentParams = currentGUI.getParams();
final GUI remoteGUI = GUI.fromJson(remoteResult.getGui());
final Map<String, Input> remoteForms = remoteGUI.getForms();
final Map<String, Object> remoteParams = remoteGUI.getParams();
currentForms.putAll(remoteForms);
currentParams.putAll(remoteParams);
}
return convert(remoteResult);
}
);
}
|
@Test
void testFailToLaunchInterpreterProcess_InvalidRunner() {
try {
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_REMOTE_RUNNER.getVarName(), "invalid_runner");
final Interpreter interpreter1 = interpreterSetting.getInterpreter("user1", note1Id, "sleep");
final InterpreterContext context1 = createDummyInterpreterContext();
// run this dummy interpret method first to launch the RemoteInterpreterProcess to avoid the
// time overhead of launching the process.
try {
interpreter1.interpret("1", context1);
fail("Should not be able to launch interpreter process");
} catch (InterpreterException e) {
assertTrue(ExceptionUtils.getStackTrace(e).contains("java.io.IOException"));
}
} finally {
System.clearProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_REMOTE_RUNNER.getVarName());
}
}
|
public static void executeWithRetry(RetryFunction function) throws Exception {
executeWithRetry(maxAttempts, minDelay, function);
}
|
@Test
public void retryFunctionThatWillFail() throws Exception {
exceptionRule.expect(SQLException.class);
exceptionRule.expectMessage("Problem with connection");
executeWithRetry(IOITHelperTest::failingFunction);
assertEquals(3, listOfExceptionsThrown.size());
}
|
@Override
public Serde<List<?>> getSerde(
final PersistenceSchema schema,
final Map<String, String> formatProps,
final KsqlConfig config,
final Supplier<SchemaRegistryClient> srFactory,
final boolean isKey
) {
SerdeUtils.throwOnUnsupportedFeatures(schema.features(), supportedFeatures());
final ConnectSchema outerSchema = ConnectSchemas.columnsToConnectSchema(schema.columns());
final ConnectSchema innerSchema = SerdeUtils
.applySinglesUnwrapping(outerSchema, schema.features());
final Class<?> targetType = SchemaConverters.connectToJavaTypeConverter()
.toJavaType(innerSchema);
return schema.features().enabled(SerdeFeature.UNWRAP_SINGLES)
? handleUnwrapped(innerSchema, formatProps, config, srFactory, targetType, isKey)
: handleWrapped(innerSchema, formatProps, config, srFactory, targetType, isKey);
}
|
@Test
public void shouldThrowOnSerializationIfStructColumnValueDoesNotMatchSchema() {
// Given:
final SimpleColumn singleColumn = createColumn(
"bob",
SqlTypes.struct()
.field("vic", SqlTypes.STRING)
.build()
);
when(persistenceSchema.columns()).thenReturn(ImmutableList.of(singleColumn));
final ConnectSchema connectSchema = (ConnectSchema) SchemaBuilder.struct()
.field("vic", Schema.STRING_SCHEMA)
.build();
final Serializer<List<?>> serializer = format
.getSerde(persistenceSchema, formatProps, config, srFactory, false)
.serializer();
final List<?> values = ImmutableList.of(new Struct(connectSchema));
// When:
final Exception e = assertThrows(
SerializationException.class,
() -> serializer.serialize("topicName", values)
);
// Then:
assertThat(e.getMessage(), is(
"Failed to prepare Struct value field 'bob' for serialization. "
+ "This could happen if the value was produced by a user-defined function "
+ "where the schema has non-optional return types. ksqlDB requires all "
+ "schemas to be optional at all levels of the Struct: the Struct itself, "
+ "schemas for all fields within the Struct, and so on."
));
}
|
public static boolean equalsIgnoreCase(String a, String b) {
if (a == null) {
return b == null;
}
return a.equalsIgnoreCase(b);
}
|
@Test
void testEqualsIgnoreCase() {
Assertions.assertTrue(StringUtils.equalsIgnoreCase("a", "a"));
Assertions.assertTrue(StringUtils.equalsIgnoreCase("a", "A"));
Assertions.assertTrue(StringUtils.equalsIgnoreCase("A", "a"));
Assertions.assertFalse(StringUtils.equalsIgnoreCase("1", "2"));
Assertions.assertFalse(StringUtils.equalsIgnoreCase(null, "1"));
Assertions.assertFalse(StringUtils.equalsIgnoreCase("1", null));
Assertions.assertFalse(StringUtils.equalsIgnoreCase("", null));
Assertions.assertFalse(StringUtils.equalsIgnoreCase(null, ""));
}
|
public static LeaderInformationRegister merge(
@Nullable LeaderInformationRegister leaderInformationRegister,
String componentId,
LeaderInformation leaderInformation) {
final Map<String, LeaderInformation> existingLeaderInformation =
new HashMap<>(
leaderInformationRegister == null
? Collections.emptyMap()
: leaderInformationRegister.leaderInformationPerComponentId);
if (leaderInformation.isEmpty()) {
existingLeaderInformation.remove(componentId);
} else {
existingLeaderInformation.put(componentId, leaderInformation);
}
return new LeaderInformationRegister(existingLeaderInformation);
}
|
@Test
void testMerge() {
final String componentId = "component-id";
final LeaderInformation leaderInformation =
LeaderInformation.known(UUID.randomUUID(), "address");
final String newComponentId = "new-component-id";
final LeaderInformation newLeaderInformation =
LeaderInformation.known(UUID.randomUUID(), "new-address");
final LeaderInformationRegister initialRegister =
LeaderInformationRegister.of(componentId, leaderInformation);
final LeaderInformationRegister newRegister =
LeaderInformationRegister.merge(
initialRegister, newComponentId, newLeaderInformation);
assertThat(newRegister).isNotSameAs(initialRegister);
assertThat(newRegister.getRegisteredComponentIds())
.containsExactlyInAnyOrder(componentId, newComponentId);
assertThat(newRegister.forComponentId(componentId)).hasValue(leaderInformation);
assertThat(newRegister.forComponentId(newComponentId)).hasValue(newLeaderInformation);
}
|
public static Collection<File> getFileResourcesFromDirectory(File directory, Pattern pattern) {
if (directory == null || directory.listFiles() == null) {
return Collections.emptySet();
}
return Arrays.stream(Objects.requireNonNull(directory.listFiles()))
.flatMap(
elem -> {
if (elem.isDirectory()) {
return getFileResourcesFromDirectory(elem, pattern).stream();
} else {
try {
if (pattern.matcher(elem.getCanonicalPath()).matches()) {
return Stream.of(elem);
}
} catch (final IOException e) {
throw new RuntimeException("Failed to retrieve resources from directory " + directory.getAbsolutePath() + " with pattern " + pattern.pattern(), e);
}
}
return Stream.empty();
})
.collect(Collectors.toSet());
}
|
@Test
public void getResourcesFromDirectoryExisting() {
File directory = new File("." + File.separator + "target" + File.separator + "test-classes");
Pattern pattern = Pattern.compile(".*txt");
final Collection<File> retrieved = getFileResourcesFromDirectory(directory, pattern);
commonVerifyCollectionWithExpectedFile(retrieved, TEST_FILE);
}
|
public static InternalRequestSignature fromHeaders(Crypto crypto, byte[] requestBody, HttpHeaders headers) {
if (headers == null) {
return null;
}
String signatureAlgorithm = headers.getHeaderString(SIGNATURE_ALGORITHM_HEADER);
String encodedSignature = headers.getHeaderString(SIGNATURE_HEADER);
if (signatureAlgorithm == null || encodedSignature == null) {
return null;
}
Mac mac;
try {
mac = crypto.mac(signatureAlgorithm);
} catch (NoSuchAlgorithmException e) {
throw new BadRequestException(e.getMessage());
}
byte[] decodedSignature;
try {
decodedSignature = Base64.getDecoder().decode(encodedSignature);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
return new InternalRequestSignature(
requestBody,
mac,
decodedSignature
);
}
|
@Test
public void fromHeadersShouldReturnNullIfSignatureHeaderMissing() {
assertNull(InternalRequestSignature.fromHeaders(crypto, REQUEST_BODY, internalRequestHeaders(null, SIGNATURE_ALGORITHM)));
}
|
public void inject(Inspector inspector, Inserter inserter) {
if (inspector.valid()) {
injectValue(inserter, inspector, null);
}
}
|
@Test
public void injectIntoSlime() {
assertTrue(f1.empty.get().valid()); // explicit nix
inject(f1.empty.get(), new SlimeInserter(f2.slime1));
inject(f1.nixValue.get(), new SlimeInserter(f2.slime2));
inject(f1.boolValue.get(), new SlimeInserter(f2.slime3));
inject(f1.longValue.get(), new SlimeInserter(f2.slime4));
inject(f1.doubleValue.get(), new SlimeInserter(f2.slime5));
inject(f1.stringValue.get(), new SlimeInserter(f2.slime6));
inject(f1.dataValue.get(), new SlimeInserter(f2.slime7));
inject(f1.arrayValue.get(), new SlimeInserter(f2.slime8));
inject(f1.objectValue.get(), new SlimeInserter(f2.slime9));
assertEquals(f1.empty.get().toString(), f2.slime1.get().toString());
assertEquals(f1.nixValue.get().toString(), f2.slime2.get().toString());
assertEquals(f1.boolValue.get().toString(), f2.slime3.get().toString());
assertEquals(f1.longValue.get().toString(), f2.slime4.get().toString());
assertEquals(f1.doubleValue.get().toString(), f2.slime5.get().toString());
assertEquals(f1.stringValue.get().toString(), f2.slime6.get().toString());
assertEquals(f1.dataValue.get().toString(), f2.slime7.get().toString());
assertEquals(f1.arrayValue.get().toString(), f2.slime8.get().toString());
assertEqualTo(f1.objectValue.get(), f2.slime9.get());
}
|
static Properties adminClientConfiguration(String bootstrapHostnames, PemTrustSet kafkaCaTrustSet, PemAuthIdentity authIdentity, Properties config) {
if (config == null) {
throw new InvalidConfigurationException("The config parameter should not be null");
}
config.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapHostnames);
// configuring TLS encryption if requested
if (kafkaCaTrustSet != null) {
config.putIfAbsent(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SSL");
config.setProperty(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PEM");
config.setProperty(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, kafkaCaTrustSet.trustedCertificatesString());
}
// configuring TLS client authentication
if (authIdentity != null) {
config.putIfAbsent(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SSL");
config.setProperty(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PEM");
config.setProperty(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, authIdentity.certificateChainAsPem());
config.setProperty(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, authIdentity.privateKeyAsPem());
}
config.putIfAbsent(AdminClientConfig.METADATA_MAX_AGE_CONFIG, "30000");
config.putIfAbsent(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, "10000");
config.putIfAbsent(AdminClientConfig.RETRIES_CONFIG, "3");
config.putIfAbsent(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, "40000");
return config;
}
|
@Test
public void testPlainConnection() {
Properties config = DefaultAdminClientProvider.adminClientConfiguration("my-kafka:9092", null, null, new Properties());
assertThat(config.size(), is(5));
assertDefaultConfigs(config);
}
|
@Override
public void close() throws IOException {
InputFileBlockHolder.unset();
// close the current iterator
this.currentIterator.close();
// exhaust the task iterator
while (tasks.hasNext()) {
tasks.next();
}
}
|
@Test
public void testClosureWithoutAnyRead() throws IOException {
Integer totalTasks = 10;
Integer recordPerTask = 10;
List<FileScanTask> tasks = createFileScanTasks(totalTasks, recordPerTask);
ClosureTrackingReader reader = new ClosureTrackingReader(table, tasks);
reader.close();
tasks.forEach(
t ->
Assert.assertFalse(
"Iterator should not be created eagerly for tasks", reader.hasIterator(t)));
}
|
public static void checkDrivingLicenceMrz(String mrz) {
if (mrz.charAt(0) != 'D') {
throw new VerificationException("MRZ should start with D");
}
if (mrz.charAt(1) != '1') {
throw new VerificationException("Only BAP configuration is supported (1)");
}
if (!mrz.substring(2, 5).equals("NLD")) {
throw new VerificationException("Only Dutch driving licence supported");
}
if (mrz.length() != 30) {
throw new VerificationException("Dutch MRZ should have length of 30");
}
checkMrzCheckDigit(mrz);
}
|
@Test
public void checkDrivingLicenceMrzCheckFirstLetterWrong() {
assertThrows(VerificationException.class, () -> {
MrzUtils.checkDrivingLicenceMrz("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
});
}
|
@Override
public void onDraw(Canvas canvas) {
final boolean keyboardChanged = mKeyboardChanged;
super.onDraw(canvas);
// switching animation
if (mAnimationLevel != AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) {
startAnimation(mInAnimation);
mInAnimation = null;
}
if (mGestureTypingPathShouldBeDrawn) {
mGestureDrawingHelper.draw(canvas);
}
// showing any requested watermark
float watermarkX = mWatermarkEdgeX;
final float watermarkY = getHeight() - mWatermarkDimen - mWatermarkMargin;
for (Drawable watermark : mWatermarks) {
watermarkX -= (mWatermarkDimen + mWatermarkMargin);
canvas.translate(watermarkX, watermarkY);
watermark.draw(canvas);
canvas.translate(-watermarkX, -watermarkY);
}
}
|
@Test
public void testExtraDrawMultiple() {
ExtraDraw mockDraw1 = Mockito.mock(ExtraDraw.class);
ExtraDraw mockDraw2 = Mockito.mock(ExtraDraw.class);
Mockito.doReturn(true).when(mockDraw1).onDraw(any(), any(), same(mViewUnderTest));
Mockito.doReturn(true).when(mockDraw2).onDraw(any(), any(), same(mViewUnderTest));
Robolectric.getForegroundThreadScheduler().pause();
Assert.assertFalse(Robolectric.getForegroundThreadScheduler().areAnyRunnable());
mViewUnderTest.addExtraDraw(mockDraw1);
mViewUnderTest.addExtraDraw(mockDraw2);
Mockito.verify(mockDraw1, Mockito.never()).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.never()).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(1)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(1)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(2)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(2)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Mockito.doReturn(false).when(mockDraw1).onDraw(any(), any(), same(mViewUnderTest));
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(3)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(3)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(3)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(4)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(3)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(5)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Mockito.doReturn(false).when(mockDraw2).onDraw(any(), any(), same(mViewUnderTest));
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(3)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(6)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertFalse(Robolectric.getForegroundThreadScheduler().size() > 0);
// adding another one
ExtraDraw mockDraw3 = Mockito.mock(ExtraDraw.class);
mViewUnderTest.addExtraDraw(mockDraw3);
Assert.assertTrue(Robolectric.getForegroundThreadScheduler().size() > 0);
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
mViewUnderTest.onDraw(Mockito.mock(Canvas.class));
Mockito.verify(mockDraw1, Mockito.times(3)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw2, Mockito.times(6)).onDraw(any(), any(), same(mViewUnderTest));
Mockito.verify(mockDraw3, Mockito.times(1)).onDraw(any(), any(), same(mViewUnderTest));
Assert.assertFalse(Robolectric.getForegroundThreadScheduler().size() > 0);
}
|
@Override
public Validator getValidator(final URL url) {
return new ApacheDubboClientValidator(url);
}
|
@Test
public void testGetValidator() {
String mockServiceUrl =
"mock://localhost:28000/org.apache.shenyu.client.apache.dubbo.validation.mock.MockValidatorTarget";
final URL url = URL.valueOf(mockServiceUrl);
apacheDubboClientValidationUnderTest.getValidator(url);
}
|
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);
checkKRaftControllerCount(warnings);
checkKafkaMetadataVersion(warnings);
checkInterBrokerProtocolVersionInKRaft(warnings);
checkLogMessageFormatVersionInKRaft(warnings);
} else {
// Additional checks done for ZooKeeper-based clusters
checkKafkaLogMessageFormatVersion(warnings);
checkKafkaInterBrokerProtocolVersion(warnings);
checkKRaftMetadataStorageConfiguredForZooBasedCLuster(warnings);
}
return warnings;
}
|
@Test
public void checkKafkaJbodEphemeralStorageSingleController() {
KafkaNodePool singleNode = new KafkaNodePoolBuilder(CONTROLLERS)
.editSpec()
.withReplicas(1)
.withStorage(
new JbodStorageBuilder().withVolumes(
new EphemeralStorageBuilder().withId(1).build(),
new EphemeralStorageBuilder().withId(2).build()
).build())
.endSpec()
.build();
KafkaSpecChecker checker = generateChecker(KAFKA, List.of(singleNode, POOL_A), KafkaVersionTestUtils.DEFAULT_KRAFT_VERSION_CHANGE);
List<Condition> warnings = checker.run(true);
assertThat(warnings, hasSize(1));
Condition warning = warnings.get(0);
assertThat(warning.getReason(), is("KafkaStorage"));
assertThat(warning.getStatus(), is("True"));
assertThat(warning.getMessage(), is("A Kafka cluster with a single controller node and ephemeral storage will lose data after any restart or rolling update."));
}
|
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, events);
return events;
}
|
@Test
void storage_node_maintenance_grace_period_event_only_emitted_on_maintenance_to_down_edge() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .0.s:u")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
.maxMaintenanceGracePeriodTimeMs(123_456)
.storageNodeReasonAfter(0, NodeStateReason.NODE_NOT_BACK_UP_WITHIN_GRACE_PERIOD);
final List<Event> events = fixture.computeEventDiff();
assertThat(events.size(), equalTo(1));
assertThat(events, hasItem(allOf(
eventForNode(storageNode(0)),
nodeEventForBaseline())));
}
|
protected boolean isVfsPath( String filePath ) {
boolean ret = false;
try {
VFSFileProvider vfsFileProvider = (VFSFileProvider) providerService.get( VFSFileProvider.TYPE );
if ( vfsFileProvider == null ) {
return false;
}
return vfsFileProvider.isSupported( filePath );
} catch ( InvalidFileProviderException | ClassCastException e ) {
// DO NOTHING
}
return ret;
}
|
@Test
public void testIsVfsPath_NotSupported() throws Exception {
// SETUP
String vfsPath = "pvfs://someConnection/someFilePath";
ProviderService mockProviderService = mock( ProviderService.class );
VFSFileProvider mockVFSFileProvider = mock( VFSFileProvider.class );
when( mockProviderService.get( VFSFileProvider.TYPE ) ).thenReturn( mockVFSFileProvider );
when( mockVFSFileProvider.isSupported( any() ) ).thenReturn( false );
FileOpenSaveExtensionPoint testInstance = new FileOpenSaveExtensionPoint( mockProviderService, null );
assertFalse( testInstance.isVfsPath( vfsPath ) );
}
|
public Map<String, List<PartitionInfo>> getAllTopicMetadata(Timer timer) {
MetadataRequest.Builder request = MetadataRequest.Builder.allTopics();
return getTopicMetadata(request, timer);
}
|
@Test
public void testGetAllTopicsUnauthorized() {
buildFetcher();
assignFromUser(singleton(tp0));
client.prepareResponse(newMetadataResponse(Errors.TOPIC_AUTHORIZATION_FAILED));
try {
topicMetadataFetcher.getAllTopicMetadata(time.timer(10L));
fail();
} catch (TopicAuthorizationException e) {
assertEquals(singleton(topicName), e.unauthorizedTopics());
}
}
|
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appName");
}
if (Strings.isNullOrEmpty(dataflowOptions.getRegion())
&& isServiceEndpoint(dataflowOptions.getDataflowEndpoint())) {
missing.add("region");
}
if (missing.size() > 0) {
throw new IllegalArgumentException(
"Missing required pipeline options: " + Joiner.on(',').join(missing));
}
validateWorkerSettings(
PipelineOptionsValidator.validate(DataflowPipelineWorkerPoolOptions.class, options));
PathValidator validator = dataflowOptions.getPathValidator();
String gcpTempLocation;
try {
gcpTempLocation = dataflowOptions.getGcpTempLocation();
} catch (Exception e) {
throw new IllegalArgumentException(
"DataflowRunner requires gcpTempLocation, "
+ "but failed to retrieve a value from PipelineOptions",
e);
}
validator.validateOutputFilePrefixSupported(gcpTempLocation);
String stagingLocation;
try {
stagingLocation = dataflowOptions.getStagingLocation();
} catch (Exception e) {
throw new IllegalArgumentException(
"DataflowRunner requires stagingLocation, "
+ "but failed to retrieve a value from PipelineOptions",
e);
}
validator.validateOutputFilePrefixSupported(stagingLocation);
if (!isNullOrEmpty(dataflowOptions.getSaveProfilesToGcs())) {
validator.validateOutputFilePrefixSupported(dataflowOptions.getSaveProfilesToGcs());
}
if (dataflowOptions.getFilesToStage() != null) {
// The user specifically requested these files, so fail now if they do not exist.
// (automatically detected classpath elements are permitted to not exist, so later
// staging will not fail on nonexistent files)
dataflowOptions.getFilesToStage().stream()
.forEach(
stagedFileSpec -> {
File localFile;
if (stagedFileSpec.contains("=")) {
String[] components = stagedFileSpec.split("=", 2);
localFile = new File(components[1]);
} else {
localFile = new File(stagedFileSpec);
}
if (!localFile.exists()) {
// should be FileNotFoundException, but for build-time backwards compatibility
// cannot add checked exception
throw new RuntimeException(
String.format("Non-existent files specified in filesToStage: %s", localFile));
}
});
} else {
dataflowOptions.setFilesToStage(
detectClassPathResourcesToStage(DataflowRunner.class.getClassLoader(), options));
if (dataflowOptions.getFilesToStage().isEmpty()) {
throw new IllegalArgumentException("No files to stage has been found.");
} else {
LOG.info(
"PipelineOptions.filesToStage was not specified. "
+ "Defaulting to files from the classpath: will stage {} files. "
+ "Enable logging at DEBUG level to see which files will be staged.",
dataflowOptions.getFilesToStage().size());
LOG.debug("Classpath elements: {}", dataflowOptions.getFilesToStage());
}
}
// Verify jobName according to service requirements, truncating converting to lowercase if
// necessary.
String jobName = dataflowOptions.getJobName().toLowerCase();
checkArgument(
jobName.matches("[a-z]([-a-z0-9]*[a-z0-9])?"),
"JobName invalid; the name must consist of only the characters "
+ "[-a-z0-9], starting with a letter and ending with a letter "
+ "or number");
if (!jobName.equals(dataflowOptions.getJobName())) {
LOG.info(
"PipelineOptions.jobName did not match the service requirements. "
+ "Using {} instead of {}.",
jobName,
dataflowOptions.getJobName());
}
dataflowOptions.setJobName(jobName);
// Verify project
String project = dataflowOptions.getProject();
if (project.matches("[0-9]*")) {
throw new IllegalArgumentException(
"Project ID '"
+ project
+ "' invalid. Please make sure you specified the Project ID, not project number.");
} else if (!project.matches(PROJECT_ID_REGEXP)) {
throw new IllegalArgumentException(
"Project ID '"
+ project
+ "' invalid. Please make sure you specified the Project ID, not project"
+ " description.");
}
DataflowPipelineDebugOptions debugOptions =
dataflowOptions.as(DataflowPipelineDebugOptions.class);
// Verify the number of worker threads is a valid value
if (debugOptions.getNumberOfWorkerHarnessThreads() < 0) {
throw new IllegalArgumentException(
"Number of worker harness threads '"
+ debugOptions.getNumberOfWorkerHarnessThreads()
+ "' invalid. Please make sure the value is non-negative.");
}
// Verify that if recordJfrOnGcThrashing is set, the pipeline is at least on java 11
if (dataflowOptions.getRecordJfrOnGcThrashing()
&& Environments.getJavaVersion() == Environments.JavaVersion.java8) {
throw new IllegalArgumentException(
"recordJfrOnGcThrashing is only supported on java 9 and up.");
}
if (dataflowOptions.isStreaming() && dataflowOptions.getGcsUploadBufferSizeBytes() == null) {
dataflowOptions.setGcsUploadBufferSizeBytes(GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT);
}
// Adding the Java version to the SDK name for user's and support convenience.
String agentJavaVer = "(JRE 8 environment)";
if (Environments.getJavaVersion() != Environments.JavaVersion.java8) {
agentJavaVer =
String.format("(JRE %s environment)", Environments.getJavaVersion().specification());
}
DataflowRunnerInfo dataflowRunnerInfo = DataflowRunnerInfo.getDataflowRunnerInfo();
String userAgentName = dataflowRunnerInfo.getName();
Preconditions.checkArgument(
!userAgentName.equals(""), "Dataflow runner's `name` property cannot be empty.");
String userAgentVersion = dataflowRunnerInfo.getVersion();
Preconditions.checkArgument(
!userAgentVersion.equals(""), "Dataflow runner's `version` property cannot be empty.");
String userAgent =
String.format("%s/%s%s", userAgentName, userAgentVersion, agentJavaVer).replace(" ", "_");
dataflowOptions.setUserAgent(userAgent);
return new DataflowRunner(dataflowOptions);
}
|
@Test
public void testRegionOptionalForNonServiceRunner() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setRegion(null);
options.setDataflowEndpoint("http://localhost:20281");
DataflowRunner.fromOptions(options);
}
|
public static void removeUnavailableStepsFromMapping( Map<TargetStepAttribute, SourceStepField> targetMap,
Set<SourceStepField> unavailableSourceSteps, Set<TargetStepAttribute> unavailableTargetSteps ) {
Iterator<Entry<TargetStepAttribute, SourceStepField>> targetMapIterator = targetMap.entrySet().iterator();
while ( targetMapIterator.hasNext() ) {
Entry<TargetStepAttribute, SourceStepField> entry = targetMapIterator.next();
SourceStepField currentSourceStepField = entry.getValue();
TargetStepAttribute currentTargetStepAttribute = entry.getKey();
if ( unavailableSourceSteps.contains( currentSourceStepField ) || unavailableTargetSteps.contains(
currentTargetStepAttribute ) ) {
targetMapIterator.remove();
}
}
}
|
@Test
public void removeUnavailableStepsFromMapping_unavailable_target_step() {
TargetStepAttribute unavailableTargetStep = new TargetStepAttribute( UNAVAILABLE_STEP, TEST_ATTR_VALUE, false );
SourceStepField unavailableSourceStep = new SourceStepField( UNAVAILABLE_STEP, TEST_FIELD );
Map<TargetStepAttribute, SourceStepField> targetMap = new HashMap<TargetStepAttribute, SourceStepField>();
targetMap.put( unavailableTargetStep, unavailableSourceStep );
Set<TargetStepAttribute> unavailableTargetSteps = Collections.singleton( UNAVAILABLE_TARGET_STEP );
MetaInject.removeUnavailableStepsFromMapping( targetMap, Collections.<SourceStepField>emptySet(),
unavailableTargetSteps );
assertTrue( targetMap.isEmpty() );
}
|
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "executions/latest/group-by-flow")
@Operation(tags = {"Stats"}, summary = "Get latest execution by flows")
public List<Execution> lastExecutions(
@Parameter(description = "A list of flows filter") @Body @Valid LastExecutionsRequest lastExecutionsRequest
) {
return executionRepository.lastExecutions(
tenantService.resolveTenant(),
lastExecutionsRequest.flows() != null && lastExecutionsRequest.flows().getFirst().getNamespace() != null && lastExecutionsRequest.flows().getFirst().getId() != null ? lastExecutionsRequest.flows() : null
);
}
|
@Test
void lastExecutions() {
var dailyStatistics = client.toBlocking().retrieve(
HttpRequest
.POST("/api/v1/stats/executions/latest/group-by-flow", new StatsController.LastExecutionsRequest(List.of(ExecutionRepositoryInterface.FlowFilter.builder().namespace("io.kestra.test").id("logs").build())))
.contentType(MediaType.APPLICATION_JSON),
Argument.listOf(Execution.class)
);
assertThat(dailyStatistics, notNullValue());
}
|
@Override
public String getSchema() {
return dialectDatabaseMetaData.getSchema(connection);
}
|
@Test
void assertGetSchemaReturnNullWhenThrowsSQLException() throws SQLException {
when(connection.getSchema()).thenThrow(SQLException.class);
MetaDataLoaderConnection connection = new MetaDataLoaderConnection(databaseType, this.connection);
assertNull(connection.getSchema());
}
|
long getNodeResultLimit(int ownedPartitions) {
return isQueryResultLimitEnabled ? (long) ceil(resultLimitPerPartition * ownedPartitions) : Long.MAX_VALUE;
}
|
@Test
public void testNodeResultLimitMinResultLimit() {
initMocksWithConfiguration(QueryResultSizeLimiter.MINIMUM_MAX_RESULT_LIMIT, 3);
long nodeResultLimit1 = limiter.getNodeResultLimit(1);
initMocksWithConfiguration(QueryResultSizeLimiter.MINIMUM_MAX_RESULT_LIMIT / 2, 3);
long nodeResultLimit2 = limiter.getNodeResultLimit(1);
assertEquals(nodeResultLimit1, nodeResultLimit2);
}
|
@Override
public V fetch(final K key, final long time) {
Objects.requireNonNull(key, "key can't be null");
final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType);
for (final ReadOnlyWindowStore<K, V> windowStore : stores) {
try {
final V result = windowStore.fetch(key, time);
if (result != null) {
return result;
}
} catch (final InvalidStateStoreException e) {
throw new InvalidStateStoreException(
"State store is not available anymore and may have been migrated to another instance; " +
"please re-discover its location from the state metadata.");
}
}
return null;
}
|
@Test
public void shouldFetchKeyRangeAcrossStores() {
final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE);
stubProviderTwo.addStore(storeName, secondUnderlying);
underlyingWindowStore.put("a", "a", 0L);
secondUnderlying.put("b", "b", 10L);
final List<KeyValue<Windowed<String>, String>> results =
StreamsTestUtils.toList(windowStore.fetch("a", "b", ofEpochMilli(0), ofEpochMilli(10)));
assertThat(results, equalTo(Arrays.asList(
KeyValue.pair(new Windowed<>("a", new TimeWindow(0, WINDOW_SIZE)), "a"),
KeyValue.pair(new Windowed<>("b", new TimeWindow(10, 10 + WINDOW_SIZE)), "b"))));
}
|
@VisibleForTesting
static void validatePartitionStatistics(SchemaTableName table, Map<String, PartitionStatistics> partitionStatistics)
{
partitionStatistics.forEach((partition, statistics) -> {
HiveBasicStatistics basicStatistics = statistics.getBasicStatistics();
OptionalLong rowCount = basicStatistics.getRowCount();
rowCount.ifPresent(count -> checkStatistics(count >= 0, table, partition, "rowCount must be greater than or equal to zero: %s", count));
basicStatistics.getFileCount().ifPresent(count -> checkStatistics(count >= 0, table, partition, "fileCount must be greater than or equal to zero: %s", count));
basicStatistics.getInMemoryDataSizeInBytes().ifPresent(size -> checkStatistics(size >= 0, table, partition, "inMemoryDataSizeInBytes must be greater than or equal to zero: %s", size));
basicStatistics.getOnDiskDataSizeInBytes().ifPresent(size -> checkStatistics(size >= 0, table, partition, "onDiskDataSizeInBytes must be greater than or equal to zero: %s", size));
statistics.getColumnStatistics().forEach((column, columnStatistics) -> validateColumnStatistics(table, partition, column, rowCount, columnStatistics));
});
}
|
@Test
public void testValidatePartitionStatistics()
{
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(-1, 0, 0, 0))
.build(),
invalidPartitionStatistics("fileCount must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, -1, 0, 0))
.build(),
invalidPartitionStatistics("rowCount must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, -1, 0))
.build(),
invalidPartitionStatistics("inMemoryDataSizeInBytes must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, -1))
.build(),
invalidPartitionStatistics("onDiskDataSizeInBytes must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setMaxValueSizeInBytes(-1).build()))
.build(),
invalidColumnStatistics("maxValueSizeInBytes must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setTotalSizeInBytes(-1).build()))
.build(),
invalidColumnStatistics("totalSizeInBytes must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setNullsCount(-1).build()))
.build(),
invalidColumnStatistics("nullsCount must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setNullsCount(1).build()))
.build(),
invalidColumnStatistics("nullsCount must be less than or equal to rowCount. nullsCount: 1. rowCount: 0."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setDistinctValuesCount(-1).build()))
.build(),
invalidColumnStatistics("distinctValuesCount must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setDistinctValuesCount(1).build()))
.build(),
invalidColumnStatistics("distinctValuesCount must be less than or equal to rowCount. distinctValuesCount: 1. rowCount: 0."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 1, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, HiveColumnStatistics.builder().setDistinctValuesCount(1).setNullsCount(1).build()))
.build(),
invalidColumnStatistics("distinctValuesCount must be less than or equal to nonNullsCount. distinctValuesCount: 1. nonNullsCount: 0."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createIntegerColumnStatistics(OptionalLong.of(1), OptionalLong.of(-1), OptionalLong.empty(), OptionalLong.empty())))
.build(),
invalidColumnStatistics("integerStatistics.min must be less than or equal to integerStatistics.max. integerStatistics.min: 1. integerStatistics.max: -1."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createDoubleColumnStatistics(OptionalDouble.of(1), OptionalDouble.of(-1), OptionalLong.empty(), OptionalLong.empty())))
.build(),
invalidColumnStatistics("doubleStatistics.min must be less than or equal to doubleStatistics.max. doubleStatistics.min: 1.0. doubleStatistics.max: -1.0."));
validatePartitionStatistics(
TABLE,
ImmutableMap.of(
PARTITION,
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createDoubleColumnStatistics(OptionalDouble.of(NaN), OptionalDouble.of(NaN), OptionalLong.empty(), OptionalLong.empty())))
.build()));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createDecimalColumnStatistics(Optional.of(BigDecimal.valueOf(1)), Optional.of(BigDecimal.valueOf(-1)), OptionalLong.empty(), OptionalLong.empty())))
.build(),
invalidColumnStatistics("decimalStatistics.min must be less than or equal to decimalStatistics.max. decimalStatistics.min: 1. decimalStatistics.max: -1."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createDateColumnStatistics(Optional.of(LocalDate.ofEpochDay(1)), Optional.of(LocalDate.ofEpochDay(-1)), OptionalLong.empty(), OptionalLong.empty())))
.build(),
invalidColumnStatistics("dateStatistics.min must be less than or equal to dateStatistics.max. dateStatistics.min: 1970-01-02. dateStatistics.max: 1969-12-31."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createBooleanColumnStatistics(OptionalLong.of(-1), OptionalLong.empty(), OptionalLong.empty())))
.build(),
invalidColumnStatistics("trueCount must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createBooleanColumnStatistics(OptionalLong.empty(), OptionalLong.of(-1), OptionalLong.empty())))
.build(),
invalidColumnStatistics("falseCount must be greater than or equal to zero: -1"));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createBooleanColumnStatistics(OptionalLong.of(1), OptionalLong.empty(), OptionalLong.empty())))
.build(),
invalidColumnStatistics("booleanStatistics.trueCount must be less than or equal to rowCount. booleanStatistics.trueCount: 1. rowCount: 0."));
assertInvalidStatistics(
PartitionStatistics.builder()
.setBasicStatistics(new HiveBasicStatistics(0, 0, 0, 0))
.setColumnStatistics(ImmutableMap.of(COLUMN, createBooleanColumnStatistics(OptionalLong.empty(), OptionalLong.of(1), OptionalLong.empty())))
.build(),
invalidColumnStatistics("booleanStatistics.falseCount must be less than or equal to rowCount. booleanStatistics.falseCount: 1. rowCount: 0."));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.